The best way to control Claude Code, Codex and more from any computer or phone

main
ts 258 lines 8.4 KB
Raw
1 import * as Data from "effect/Data";
2 import * as Effect from "effect/Effect";
3 import { State, type StateService, type StateStoreError } from "./State.ts";
4 import { encodeState } from "./StateEncoding.ts";
5
6 // The store viewed as a filesystem: `stack/stage/fqn` for a resource record,
7 // `stack/stage/output` for a stage's outputs. Everything here addresses that
8 // tree by slash-separated path, so a CLI or an RPC client can walk state
9 // without knowing the backend's key layout.
10
11 /** Reading or listing a path. Omit `path` for the root. */
12 export interface TreeQuery {
13 readonly path?: string;
14 /** Recurse into every descendant instead of stopping at immediate children. */
15 readonly recursive?: boolean;
16 }
17
18 /** Deleting a path. The path is required — the root is not deletable. */
19 export interface TreeDelete {
20 readonly path: string;
21 /** Delete every descendant when the path identifies a directory. */
22 readonly recursive?: boolean;
23 }
24
25 /** One decoded record produced by {@link readState}. */
26 export interface StateEntry {
27 readonly path: string;
28 readonly kind: "resource" | "output";
29 readonly value: unknown;
30 }
31
32 /** The path does not exist, or does not support the requested operation. */
33 export class InvalidStatePath extends Data.TaggedError("InvalidStatePath")<{
34 readonly path: string;
35 readonly reason: string;
36 }> {}
37
38 export interface StateDeleted {
39 readonly _tag: "StateDeleted";
40 readonly path: string;
41 readonly deleted: ReadonlyArray<string>;
42 }
43
44 /**
45 * Every `(stack, stage)` pair the store holds, or the subset a filter pins.
46 *
47 * Enumerating them means `listStacks` then a `listStages` per stack, so the
48 * fan-out runs concurrently: against a remote store a serial walk is one
49 * round trip per stack before the first stage is even known. A pinned
50 * `stack`/`stage` is taken at face value and skips the corresponding call —
51 * naming a scope is not a claim that it exists, and callers report a missing
52 * one from the emptiness of what comes back.
53 *
54 * Ordered by stack then stage so every traversal built on it is deterministic.
55 */
56 export const allStages = Effect.fn("allStages")(function* (
57 filter: { readonly stack?: string; readonly stage?: string } = {},
58 ) {
59 return yield* stagesOf(yield* yield* State, filter);
60 });
61
62 const stagesOf = (
63 state: StateService,
64 filter: { readonly stack?: string; readonly stage?: string },
65 ): Effect.Effect<
66 ReadonlyArray<{ readonly stack: string; readonly stage: string }>,
67 StateStoreError
68 > =>
69 Effect.gen(function* () {
70 const stacks =
71 filter.stack !== undefined ? [filter.stack] : [...(yield* state.listStacks())].sort();
72 if (filter.stage !== undefined) {
73 const stage = filter.stage;
74 return stacks.map((stack) => ({ stack, stage }));
75 }
76 const perStack = yield* Effect.forEach(
77 stacks,
78 (stack) =>
79 Effect.map(state.listStages(stack), (stages) =>
80 [...stages].sort().map((stage) => ({ stack, stage })),
81 ),
82 { concurrency: "unbounded" },
83 );
84 return perStack.flat();
85 });
86
87 type StateFile =
88 | {
89 readonly kind: "resource";
90 readonly path: string;
91 readonly stack: string;
92 readonly stage: string;
93 readonly fqn: string;
94 }
95 | {
96 readonly kind: "output";
97 readonly path: string;
98 readonly stack: string;
99 readonly stage: string;
100 };
101
102 const pathParts = (path: string | undefined): ReadonlyArray<string> =>
103 (path ?? "").split("/").filter((part) => part !== "" && part !== ".");
104
105 const invalidPath = (path: string, reason = "path does not exist") =>
106 Effect.fail(new InvalidStatePath({ path, reason }));
107
108 const parsePath = (path: string | undefined) => {
109 const parts = pathParts(path);
110 return parts.includes("..")
111 ? invalidPath(path ?? "/", "parent path segments are not allowed")
112 : Effect.succeed(parts);
113 };
114
115 const stageFiles = Effect.fn(function* (state: StateService, stack: string, stage: string) {
116 const fqns = yield* state.list({ stack, stage });
117 return [
118 ...fqns.map((fqn): StateFile => ({
119 kind: "resource",
120 path: `${stack}/${stage}/${fqn}`,
121 stack,
122 stage,
123 fqn,
124 })),
125 {
126 kind: "output",
127 path: `${stack}/${stage}/output`,
128 stack,
129 stage,
130 } as const,
131 ];
132 });
133
134 /** Every file under the given scope, listed one stage at a time in parallel. */
135 const filesUnder = Effect.fn(function* (
136 state: StateService,
137 filter: { readonly stack?: string } = {},
138 ) {
139 const stages = yield* stagesOf(state, filter);
140 const perStage = yield* Effect.forEach(
141 stages,
142 ({ stack, stage }) => stageFiles(state, stack, stage),
143 { concurrency: "unbounded" },
144 );
145 return perStage.flat();
146 });
147
148 const filesAt = Effect.fn(function* (state: StateService, parts: ReadonlyArray<string>) {
149 const path = parts.join("/");
150 if (parts.length === 0) {
151 return { directory: true as const, files: yield* filesUnder(state) };
152 }
153 if (parts.length === 1) {
154 const stack = parts[0]!;
155 if (!(yield* state.listStacks()).includes(stack)) {
156 return yield* invalidPath(path);
157 }
158 return {
159 directory: true as const,
160 files: yield* filesUnder(state, { stack }),
161 };
162 }
163 if (parts.length === 2) {
164 const [stack, stage] = parts as [string, string];
165 if (!(yield* state.listStages(stack)).includes(stage)) {
166 return yield* invalidPath(path);
167 }
168 return {
169 directory: true as const,
170 files: yield* stageFiles(state, stack, stage),
171 };
172 }
173 const files = yield* stageFiles(state, parts[0]!, parts[1]!);
174 const exact = files.find((file) => file.path === path);
175 if (exact !== undefined) return { directory: false as const, files: [exact] };
176 const descendants = files.filter((file) => file.path.startsWith(`${path}/`));
177 if (descendants.length === 0) return yield* invalidPath(path);
178 return { directory: true as const, files: descendants };
179 });
180
181 export const listState = Effect.fn("listState")(function* ({ path, recursive = false }: TreeQuery) {
182 const state = yield* yield* State;
183 const parts = yield* parsePath(path);
184 const normalizedPath = parts.join("/");
185 if (parts.length === 0 && !recursive) {
186 return (yield* state.listStacks()).map((stack) => `${stack}/`);
187 }
188 const { directory, files } = yield* filesAt(state, parts);
189 if (!directory) return [normalizedPath];
190 const prefix = normalizedPath === "" ? "" : `${normalizedPath}/`;
191 if (recursive) return files.map((file) => file.path);
192 return [
193 ...new Set(
194 files.map((file) => {
195 const rest = file.path.slice(prefix.length);
196 const child = rest.split("/")[0]!;
197 return rest.includes("/") ? `${prefix}${child}/` : file.path;
198 }),
199 ),
200 ];
201 });
202
203 export const readState = Effect.fn("readState")(function* ({ path, recursive = false }: TreeQuery) {
204 const state = yield* yield* State;
205 const parts = yield* parsePath(path);
206 const target = yield* filesAt(state, parts);
207 if (target.directory && !recursive) {
208 return yield* invalidPath(
209 path ?? "/",
210 "path is a directory; set recursive to read its descendants",
211 );
212 }
213 return yield* Effect.forEach(target.files, (file) =>
214 (file.kind === "output" ? state.getOutput(file) : state.get(file)).pipe(
215 Effect.map((value): StateEntry => ({
216 path: file.path,
217 kind: file.kind,
218 value: encodeState(value) ?? null,
219 })),
220 ),
221 );
222 });
223
224 export const deleteState = Effect.fn("deleteState")(function* ({
225 path,
226 recursive = false,
227 }: TreeDelete) {
228 const state = yield* yield* State;
229 const parts = yield* parsePath(path);
230 if (parts.length === 0) {
231 return yield* invalidPath(path, "the state root cannot be deleted");
232 }
233 const target = yield* filesAt(state, parts);
234 if (target.directory && !recursive) {
235 return yield* invalidPath(path, "path is a directory; set recursive to delete its descendants");
236 }
237 if (parts.length === 1) {
238 yield* state.deleteStack({ stack: parts[0]! });
239 } else if (parts.length === 2) {
240 yield* state.deleteStack({ stack: parts[0]!, stage: parts[1]! });
241 } else {
242 const resources = target.files.filter(
243 (file): file is Extract<StateFile, { kind: "resource" }> => file.kind === "resource",
244 );
245 if (resources.length === 0) {
246 return yield* invalidPath(path, "output cannot be deleted independently");
247 }
248 yield* Effect.forEach(resources, (file) => state.delete(file), {
249 concurrency: 32,
250 discard: true,
251 });
252 }
253 return {
254 _tag: "StateDeleted" as const,
255 path: parts.join("/"),
256 deleted: target.files.map((file) => file.path),
257 };
258 });