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

main
ts 68 lines 2.3 KB
Raw
1 /** Construct a streaming push from an application's own protocol or background job. */
2 import * as Effect from "effect/Effect";
3 import * as Fiber from "effect/Fiber";
4 import * as Schema from "effect/Schema";
5 import * as Stream from "effect/Stream";
6 import { Oid, RefName } from "./Api/Schema.ts";
7 import { StoreError } from "./Protocol/Store.ts";
8 import { incomingStates, type PushInput, type RefUpdate } from "./Push.ts";
9 import { makeStreamingSource } from "./Store/StreamingSource.ts";
10
11 const Commands = Schema.Array(Schema.Struct({ ref: RefName, oldOid: Oid, newOid: Oid }));
12
13 /**
14 * Prepare input from decoded ref updates and raw pack bytes, with no HTTP dependency.
15 * Use Stream.empty for a ref-only mutation. The input and producer share the caller's scope.
16 */
17 export const fromStream = <E, R>(
18 updates: ReadonlyArray<RefUpdate>,
19 pack: Stream.Stream<Uint8Array, E, R>,
20 options?: { readonly atomic?: boolean; readonly declaredBytes?: number },
21 ) =>
22 Effect.gen(function* () {
23 const commands = yield* Schema.decodeEffect(Commands)(updates);
24 const input: PushInput = Object.freeze({
25 updates: Object.freeze(commands.map((command) => Object.freeze({ ...command }))),
26 atomic: options?.atomic ?? true,
27 });
28 const feeder = makeStreamingSource();
29 let total = 0;
30 const receiving = yield* Effect.forkScoped(
31 pack.pipe(
32 Stream.runForEach((bytes) =>
33 Effect.andThen(
34 feeder.push(bytes),
35 Effect.sync(() => {
36 total += bytes.length;
37 }),
38 ),
39 ),
40 Effect.map(() => {
41 feeder.end();
42 return { total };
43 }),
44 Effect.mapError((error) =>
45 StoreError.make({ reason: `pack stream failed: ${String(error)}` }),
46 ),
47 Effect.tapError((error) => Effect.sync(() => feeder.fail(error))),
48 Effect.result,
49 ),
50 );
51 const state = {
52 feeder,
53 receiving,
54 packStart: 0,
55 declaredBytes: options?.declaredBytes,
56 active: true,
57 claimed: false,
58 };
59 incomingStates.set(input, state);
60 yield* Effect.addFinalizer(() =>
61 Effect.gen(function* () {
62 state.active = false;
63 feeder.fail(StoreError.make({ reason: "push scope closed" }));
64 yield* Fiber.interrupt(receiving);
65 }),
66 );
67 return input;
68 });