@av-pi-studio/server 0.0.102 → 0.0.104

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -55,7 +55,8 @@ The daemon is **provider-agnostic**: the rest of the code only ever touches the
55
55
  - **Node.js ≥ 20** (developed and tested on Node 24). ESM only (`"type": "module"`).
56
56
  - **npm** with workspaces (this package lives in the Pi-Studio monorepo).
57
57
  - For the real **`pi` provider**: pi *credentials* only. The `pi` CLI is bundled as a dependency
58
- (`@earendil-works/pi-coding-agent`) — the daemon launches `node <pkg>/dist/cli.js --mode rpc`, so
58
+ (`@earendil-works/pi-coding-agent`) — the daemon launches `node <pkg>/<pi's declared bin> --mode
59
+ rpc` (`dist/bundle/cli.js` as of Pi 0.84.4), so
59
60
  **no global `pi` install is required**. Provide credentials via an API key
60
61
  (`ANTHROPIC_API_KEY`, etc.) in the daemon's environment, or a configured `~/.pi/agent/auth.json`.
61
62
  - The built-in **`mock` provider** needs **no credentials** and is ideal for smoke tests.
@@ -23,6 +23,15 @@ export declare function getTimeline(agentId: string): AgentTimelineStore | undef
23
23
  * `hydrateTimeline()`. No-op if a timeline already exists (never overwrites live/streamed rows).
24
24
  */
25
25
  export declare function seedTimeline(agentId: string, rows: import("./timeline-store.js").TimelineRow[]): void;
26
+ /**
27
+ * Unconditionally replace `agentId`'s in-memory timeline with `rows` (fork resync —
28
+ * features/conversation-fork.md § New daemon-internal surface). Unlike `seedTimeline`, this
29
+ * always replaces — a fork always happens on a live session, which always already has a store,
30
+ * so a no-op-if-exists entry point could never do the job. `rows` may legitimately be empty (a
31
+ * fork to before the first user message). Creates the store if none exists yet so callers never
32
+ * need to special-case a never-spawned session.
33
+ */
34
+ export declare function resetTimeline(agentId: string, rows: import("./timeline-store.js").TimelineRow[]): void;
26
35
  /**
27
36
  * Ensure `agentId` has a live provider session: resume from a persisted handle, or — for a
28
37
  * deferred draft that was never spawned (`record.persistence` absent; see `AgentService.handleCreate`
@@ -25,6 +25,17 @@ export function seedTimeline(agentId, rows) {
25
25
  return;
26
26
  timelinesByAgentId.set(agentId, new AgentTimelineStore({ initialRows: rows }));
27
27
  }
28
+ /**
29
+ * Unconditionally replace `agentId`'s in-memory timeline with `rows` (fork resync —
30
+ * features/conversation-fork.md § New daemon-internal surface). Unlike `seedTimeline`, this
31
+ * always replaces — a fork always happens on a live session, which always already has a store,
32
+ * so a no-op-if-exists entry point could never do the job. `rows` may legitimately be empty (a
33
+ * fork to before the first user message). Creates the store if none exists yet so callers never
34
+ * need to special-case a never-spawned session.
35
+ */
36
+ export function resetTimeline(agentId, rows) {
37
+ getOrCreateTimeline(agentId).replaceRows(rows);
38
+ }
28
39
  /**
29
40
  * Ensure `agentId` has a live provider session: resume from a persisted handle, or — for a
30
41
  * deferred draft that was never spawned (`record.persistence` absent; see `AgentService.handleCreate`
@@ -34,18 +34,18 @@ export declare function resolveBinaryOnPath(bin: string, env?: Record<string, st
34
34
  * imports of `expandHome` from this module (via `agent/index.ts`'s barrel) keep working. */
35
35
  export { expandHome };
36
36
  /**
37
- * Resolve the `pi` CLI **bundled inside the `@earendil-works/pi-coding-agent` dependency** (its
38
- * `bin` is `dist/cli.js`, a sibling of the package's `dist/index.js`). This is what lets pi-studio
39
- * run the agent without a separate global `pi` install. Returns `null` if the package isn't present.
37
+ * Resolve the `pi` CLI **bundled inside the `@earendil-works/pi-coding-agent` dependency**. This is
38
+ * what lets pi-studio run the agent without a separate global `pi` install. Returns `null` if the
39
+ * package isn't present.
40
40
  *
41
41
  * Note: `import.meta.resolve` is used (not `require.resolve`) because the package's `exports` map
42
42
  * only defines the `import` condition, so CJS resolution throws `ERR_PACKAGE_PATH_NOT_EXPORTED`.
43
43
  */
44
44
  export declare function resolveBundledPiCli(): string | null;
45
45
  /**
46
- * Default Pi launch command. Prefers the bundled CLI (`node <pkg>/dist/cli.js --mode rpc`) so no
47
- * global install is required; falls back to a global `pi --mode rpc` on `$PATH` if the dependency
48
- * is absent.
46
+ * Default Pi launch command. Prefers the bundled CLI (`node <pkg>/<pi's declared bin> --mode rpc`)
47
+ * so no global install is required; falls back to a global `pi --mode rpc` on `$PATH` if the
48
+ * dependency is absent.
49
49
  */
50
50
  export declare function defaultPiCommand(): string[];
51
51
  /**
@@ -1,5 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
- import { existsSync } from "node:fs";
2
+ import { existsSync, readFileSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import treeKill from "tree-kill";
@@ -16,31 +16,68 @@ export function resolveBinaryOnPath(bin, env = process.env) {
16
16
  * imports of `expandHome` from this module (via `agent/index.ts`'s barrel) keep working. */
17
17
  export { expandHome };
18
18
  /**
19
- * Resolve the `pi` CLI **bundled inside the `@earendil-works/pi-coding-agent` dependency** (its
20
- * `bin` is `dist/cli.js`, a sibling of the package's `dist/index.js`). This is what lets pi-studio
21
- * run the agent without a separate global `pi` install. Returns `null` if the package isn't present.
19
+ * Candidate CLI entrypoints inside the `@earendil-works/pi-coding-agent` package, relative to its
20
+ * root, tried in order when the package's own `bin.pi` cannot be read. `dist/bundle/cli.js` is the
21
+ * prebundled entry Pi declares as `bin` since 0.84.4; `dist/cli.js` is the unbundled entry it
22
+ * declared through 0.84.3 and still ships. Both start the same program.
23
+ */
24
+ const PI_CLI_FALLBACKS = [join("dist", "bundle", "cli.js"), join("dist", "cli.js")];
25
+ /**
26
+ * Resolve the `pi` CLI entrypoint inside an already-located package root, preferring whatever the
27
+ * package's own `package.json` declares as `bin.pi`.
28
+ *
29
+ * Reading the declared `bin` rather than hardcoding a path is deliberate: Pi moved it from
30
+ * `dist/cli.js` to `dist/bundle/cli.js` in 0.84.4, and the dependency range intentionally accepts
31
+ * future minor releases (`>=0.84.4 <1.0.0`), so a relocation must not silently fall back to a
32
+ * global `pi` — or to an entry upstream has stopped shipping.
33
+ */
34
+ function resolvePiCliInPackage(root) {
35
+ try {
36
+ const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
37
+ const declared = typeof manifest.bin === "string" ? manifest.bin : manifest.bin?.pi;
38
+ if (declared) {
39
+ const cli = join(root, declared);
40
+ if (existsSync(cli))
41
+ return cli;
42
+ }
43
+ }
44
+ catch {
45
+ // Unreadable/malformed manifest — fall through to the known entrypoints.
46
+ }
47
+ for (const rel of PI_CLI_FALLBACKS) {
48
+ const cli = join(root, rel);
49
+ if (existsSync(cli))
50
+ return cli;
51
+ }
52
+ return null;
53
+ }
54
+ /**
55
+ * Resolve the `pi` CLI **bundled inside the `@earendil-works/pi-coding-agent` dependency**. This is
56
+ * what lets pi-studio run the agent without a separate global `pi` install. Returns `null` if the
57
+ * package isn't present.
22
58
  *
23
59
  * Note: `import.meta.resolve` is used (not `require.resolve`) because the package's `exports` map
24
60
  * only defines the `import` condition, so CJS resolution throws `ERR_PACKAGE_PATH_NOT_EXPORTED`.
25
61
  */
26
62
  export function resolveBundledPiCli() {
27
- // 1) ESM resolution — works in the compiled daemon (real `node` ESM).
63
+ // 1) ESM resolution — works in the compiled daemon (real `node` ESM). Resolves the package's
64
+ // `main` (`dist/index.js`); its package root is the parent of that `dist` directory.
28
65
  try {
29
66
  const indexPath = fileURLToPath(import.meta.resolve("@earendil-works/pi-coding-agent"));
30
- const cli = join(dirname(indexPath), "cli.js");
31
- if (existsSync(cli))
67
+ const cli = resolvePiCliInPackage(dirname(dirname(indexPath)));
68
+ if (cli)
32
69
  return cli;
33
70
  }
34
71
  catch {
35
72
  // `import.meta.resolve` is unavailable under some loaders (e.g. vitest); fall through.
36
73
  }
37
74
  // 2) Walk up from cwd looking for the dependency in node_modules (loader-independent).
38
- const rel = join("node_modules", "@earendil-works", "pi-coding-agent", "dist", "cli.js");
75
+ const rel = join("node_modules", "@earendil-works", "pi-coding-agent");
39
76
  let dir = process.cwd();
40
77
  for (;;) {
41
- const candidate = join(dir, rel);
42
- if (existsSync(candidate))
43
- return candidate;
78
+ const cli = resolvePiCliInPackage(join(dir, rel));
79
+ if (cli)
80
+ return cli;
44
81
  const parent = dirname(dir);
45
82
  if (parent === dir)
46
83
  return null;
@@ -48,9 +85,9 @@ export function resolveBundledPiCli() {
48
85
  }
49
86
  }
50
87
  /**
51
- * Default Pi launch command. Prefers the bundled CLI (`node <pkg>/dist/cli.js --mode rpc`) so no
52
- * global install is required; falls back to a global `pi --mode rpc` on `$PATH` if the dependency
53
- * is absent.
88
+ * Default Pi launch command. Prefers the bundled CLI (`node <pkg>/<pi's declared bin> --mode rpc`)
89
+ * so no global install is required; falls back to a global `pi --mode rpc` on `$PATH` if the
90
+ * dependency is absent.
54
91
  */
55
92
  export function defaultPiCommand() {
56
93
  const cli = resolveBundledPiCli();
@@ -48,11 +48,37 @@ export declare class SlashCommandOperationsService {
48
48
  handleNewSession(msg: Record<string, unknown>, getSessions: () => Iterable<Session>): Promise<unknown>;
49
49
  /** `/resume` — loads a different session file in place; broadcast. */
50
50
  handleSwitchSession(msg: Record<string, unknown>, getSessions: () => Iterable<Session>): Promise<unknown>;
51
- /** `/fork` — read side effect (new branch), no live-record broadcast needed here. */
52
- handleFork(msg: Record<string, unknown>): Promise<unknown>;
53
- /** Fork picker — read-only. */
51
+ /**
52
+ * `/fork` — forks the session onto a new branch and, when the rebind actually happened,
53
+ * resyncs the daemon's in-memory timeline to the forked branch and broadcasts
54
+ * `agent_timeline_reset` to every active session (features/conversation-fork.md § Daemon:
55
+ * post-fork resync).
56
+ *
57
+ * The guard is "the persistence handle changed", not "the fork returned rows" or "provider is
58
+ * pi": a fork to before the first user message legitimately hydrates to a near-empty branch and
59
+ * MUST still reset, while the mock provider's inert stub fork changes no handle (its
60
+ * `nativeHandle` is derived from the session id, which fork never touches) and therefore resets
61
+ * nothing — provider-agnostic, no `provider === "pi"` check anywhere. The RPC response is
62
+ * returned only after the reset + broadcast, so the requester never observes success while the
63
+ * daemon-side timeline still shows the abandoned branch.
64
+ *
65
+ * Like `handleListCommands`, this must work on a recovered-but-unattached record (every agent
66
+ * survives a daemon restart with `managed.session === null` until something re-spawns it) or a
67
+ * never-spawned deferred draft — `requireSession`'s hard throw here was a real bug: a user could
68
+ * never fork a conversation that outlived a daemon restart without first provoking a live
69
+ * session some other way. Spawn/resume exactly as `handleListCommands`/`AgentService.
70
+ * handleSendPrompt` do.
71
+ */
72
+ handleFork(msg: Record<string, unknown>, getSessions: () => Iterable<Session>): Promise<unknown>;
73
+ /** Fork picker — read-only. Same "must work without a live session" requirement as
74
+ * `handleFork` above (and for the identical reason): the picker is the FIRST RPC the fork flow
75
+ * makes (`use-fork-action.ts` calls `forkMessages()` before ever showing a dialog), so if this
76
+ * one still hard-threw, no agent recovered from a restart could even OPEN the fork UI, let
77
+ * alone complete it. */
54
78
  handleForkMessages(msg: Record<string, unknown>): Promise<unknown>;
55
- /** `/clone` — duplicates the active branch into a new session at the current position. */
79
+ /** `/clone` — duplicates the active branch into a new session at the current position. Same
80
+ * "must work without a live session" requirement as `handleFork`/`handleForkMessages` above —
81
+ * cloning a recovered-but-unattached record is no less legitimate than cloning a live one. */
56
82
  handleClone(msg: Record<string, unknown>, getSessions: () => Iterable<Session>): Promise<unknown>;
57
83
  /** `/name` — sets the session display name; persist it to the record (single source of truth:
58
84
  * `AgentManager.updateRecord`) and broadcast the new title. */
@@ -1,4 +1,4 @@
1
- import { spawnOrResumeSession } from "./agent-service.js";
1
+ import { resetTimeline, spawnOrResumeSession } from "./agent-service.js";
2
2
  /** Resolve the live session for `agentId`, or throw an error the router turns into `rpc_error`. */
3
3
  function requireSession(manager, agentId) {
4
4
  const managed = manager.get(agentId);
@@ -22,7 +22,7 @@ export class SlashCommandOperationsService {
22
22
  registry.register("agent_compact_request", (ctx) => this.handleCompact(ctx.message, getActiveSessions));
23
23
  registry.register("agent_new_session_request", (ctx) => this.handleNewSession(ctx.message, getActiveSessions));
24
24
  registry.register("agent_switch_session_request", (ctx) => this.handleSwitchSession(ctx.message, getActiveSessions));
25
- registry.register("agent_fork_request", (ctx) => this.handleFork(ctx.message));
25
+ registry.register("agent_fork_request", (ctx) => this.handleFork(ctx.message, getActiveSessions));
26
26
  registry.register("agent_fork_messages_request", (ctx) => this.handleForkMessages(ctx.message));
27
27
  registry.register("agent_clone_request", (ctx) => this.handleClone(ctx.message, getActiveSessions));
28
28
  registry.register("agent_set_session_name_request", (ctx) => this.handleSetSessionName(ctx.message, getActiveSessions));
@@ -98,33 +98,83 @@ export class SlashCommandOperationsService {
98
98
  }
99
99
  return { type: "agent_switch_session_response", payload };
100
100
  }
101
- /** `/fork` — read side effect (new branch), no live-record broadcast needed here. */
102
- async handleFork(msg) {
101
+ /**
102
+ * `/fork` — forks the session onto a new branch and, when the rebind actually happened,
103
+ * resyncs the daemon's in-memory timeline to the forked branch and broadcasts
104
+ * `agent_timeline_reset` to every active session (features/conversation-fork.md § Daemon:
105
+ * post-fork resync).
106
+ *
107
+ * The guard is "the persistence handle changed", not "the fork returned rows" or "provider is
108
+ * pi": a fork to before the first user message legitimately hydrates to a near-empty branch and
109
+ * MUST still reset, while the mock provider's inert stub fork changes no handle (its
110
+ * `nativeHandle` is derived from the session id, which fork never touches) and therefore resets
111
+ * nothing — provider-agnostic, no `provider === "pi"` check anywhere. The RPC response is
112
+ * returned only after the reset + broadcast, so the requester never observes success while the
113
+ * daemon-side timeline still shows the abandoned branch.
114
+ *
115
+ * Like `handleListCommands`, this must work on a recovered-but-unattached record (every agent
116
+ * survives a daemon restart with `managed.session === null` until something re-spawns it) or a
117
+ * never-spawned deferred draft — `requireSession`'s hard throw here was a real bug: a user could
118
+ * never fork a conversation that outlived a daemon restart without first provoking a live
119
+ * session some other way. Spawn/resume exactly as `handleListCommands`/`AgentService.
120
+ * handleSendPrompt` do.
121
+ */
122
+ async handleFork(msg, getSessions) {
103
123
  const agentId = msg.agentId;
104
124
  const entryId = msg.entryId;
105
125
  if (!entryId)
106
126
  throw new Error("entryId is required");
107
- const session = requireSession(this.deps.manager, agentId);
127
+ const managed = this.deps.manager.get(agentId);
128
+ if (!managed)
129
+ throw new Error(`unknown agent: ${agentId}`);
130
+ const session = managed.session ?? (await spawnOrResumeSession(this.deps, agentId));
108
131
  if (!session.fork)
109
132
  throw unsupported(agentId, "fork");
110
133
  const payload = await session.fork(entryId);
111
- if (!payload.cancelled)
134
+ if (!payload.cancelled) {
135
+ const handleBefore = this.deps.manager.get(agentId)?.record.persistence?.nativeHandle;
112
136
  await this.deps.manager.persistSessionHandle(agentId);
137
+ const record = this.deps.manager.get(agentId)?.record;
138
+ const handleAfter = record?.persistence?.nativeHandle;
139
+ if (record && handleAfter != null && handleAfter !== handleBefore) {
140
+ const client = this.deps.resolveClient(record.provider);
141
+ const handle = record.persistence;
142
+ const rows = handle ? (client.hydrateTimeline?.(handle) ?? []) : [];
143
+ resetTimeline(agentId, rows);
144
+ this.deps.broadcast(getSessions(), {
145
+ type: "agent_timeline_reset",
146
+ agentId,
147
+ reason: "fork",
148
+ });
149
+ }
150
+ }
113
151
  return { type: "agent_fork_response", payload };
114
152
  }
115
- /** Fork picker — read-only. */
153
+ /** Fork picker — read-only. Same "must work without a live session" requirement as
154
+ * `handleFork` above (and for the identical reason): the picker is the FIRST RPC the fork flow
155
+ * makes (`use-fork-action.ts` calls `forkMessages()` before ever showing a dialog), so if this
156
+ * one still hard-threw, no agent recovered from a restart could even OPEN the fork UI, let
157
+ * alone complete it. */
116
158
  async handleForkMessages(msg) {
117
159
  const agentId = msg.agentId;
118
- const session = requireSession(this.deps.manager, agentId);
160
+ const managed = this.deps.manager.get(agentId);
161
+ if (!managed)
162
+ throw new Error(`unknown agent: ${agentId}`);
163
+ const session = managed.session ?? (await spawnOrResumeSession(this.deps, agentId));
119
164
  if (!session.getForkMessages)
120
165
  throw unsupported(agentId, "get_fork_messages");
121
166
  const messages = await session.getForkMessages();
122
167
  return { type: "agent_fork_messages_response", payload: { messages } };
123
168
  }
124
- /** `/clone` — duplicates the active branch into a new session at the current position. */
169
+ /** `/clone` — duplicates the active branch into a new session at the current position. Same
170
+ * "must work without a live session" requirement as `handleFork`/`handleForkMessages` above —
171
+ * cloning a recovered-but-unattached record is no less legitimate than cloning a live one. */
125
172
  async handleClone(msg, getSessions) {
126
173
  const agentId = msg.agentId;
127
- const session = requireSession(this.deps.manager, agentId);
174
+ const managed = this.deps.manager.get(agentId);
175
+ if (!managed)
176
+ throw new Error(`unknown agent: ${agentId}`);
177
+ const session = managed.session ?? (await spawnOrResumeSession(this.deps, agentId));
128
178
  if (!session.clone)
129
179
  throw unsupported(agentId, "clone");
130
180
  const payload = await session.clone();
@@ -83,12 +83,14 @@ export declare class AgentTimelineStore {
83
83
  allRows(): TimelineRow[];
84
84
  rowCount(): number;
85
85
  /**
86
- * Truncate the timeline back to just before the user message identified by messageId.
87
- * The messageId corresponds to the `messageId` field in user_message stream events.
88
- * Returns the ISO timestamp of the last retained row, or undefined if nothing was retained.
89
- * (features/rewind.md § Wire contract)
86
+ * Unconditionally replace the entire row set (fork resync — features/conversation-fork.md §
87
+ * Daemon: post-fork resync). Unlike the constructor's `initialRows` seeding, this always
88
+ * replaces, including when the store is already populated, and accepts an empty array as a
89
+ * legitimate result (forking to before the first user message). Epoch/seq continue from the
90
+ * installed rows' maximum so the next `startEpoch()`/`append()` never collides with or rewinds
91
+ * below them; an empty replacement resets both back to their initial state.
90
92
  */
91
- truncateBeforeMessage(messageId: string): string | undefined;
93
+ replaceRows(rows: TimelineRow[]): void;
92
94
  /**
93
95
  * Return a bounded page of projected items.
94
96
  *
@@ -135,25 +135,18 @@ export class AgentTimelineStore {
135
135
  return this.rows.length;
136
136
  }
137
137
  /**
138
- * Truncate the timeline back to just before the user message identified by messageId.
139
- * The messageId corresponds to the `messageId` field in user_message stream events.
140
- * Returns the ISO timestamp of the last retained row, or undefined if nothing was retained.
141
- * (features/rewind.md § Wire contract)
138
+ * Unconditionally replace the entire row set (fork resync — features/conversation-fork.md §
139
+ * Daemon: post-fork resync). Unlike the constructor's `initialRows` seeding, this always
140
+ * replaces, including when the store is already populated, and accepts an empty array as a
141
+ * legitimate result (forking to before the first user message). Epoch/seq continue from the
142
+ * installed rows' maximum so the next `startEpoch()`/`append()` never collides with or rewinds
143
+ * below them; an empty replacement resets both back to their initial state.
142
144
  */
143
- truncateBeforeMessage(messageId) {
144
- const idx = this.rows.findIndex((row) => {
145
- const event = row.event;
146
- return event.kind === "user_message" && event.messageId === messageId;
147
- });
148
- if (idx <= 0) {
149
- // Nothing to truncate or messageId not found — truncate all rows as safe fallback
150
- if (idx === 0)
151
- this.rows = [];
152
- return undefined;
153
- }
154
- this.rows = this.rows.slice(0, idx);
145
+ replaceRows(rows) {
146
+ this.rows = [...rows];
155
147
  const last = this.rows[this.rows.length - 1];
156
- return last?.timestamp;
148
+ this.epoch = last?.epoch ?? 0;
149
+ this.nextSeq = last ? last.seq + 1 : 0;
157
150
  }
158
151
  /**
159
152
  * Return a bounded page of projected items.
@@ -18,6 +18,14 @@ export interface DaemonOptions {
18
18
  /** Test-only injection for the preinstalled-extensions sync executor's process seam; production
19
19
  * always spawns the bundled `pi` (`defaultInstallSpawn`). */
20
20
  extensionsInstallSpawn?: InstallSpawn;
21
+ /**
22
+ * Called after an unrecoverable HTTP-server error (typically `EADDRINUSE` on bind) once the WS
23
+ * server has been torn down. `startDaemon` logs the error and sets `process.exitCode = 1`, but
24
+ * never terminates the process itself — a library must not kill its host. The process entry
25
+ * point supplies the actual exit (`daemon/main.ts`); tests leave it unset so a bind failure
26
+ * surfaces as a normal test failure instead of an opaque process kill.
27
+ */
28
+ onFatalError?: (err: NodeJS.ErrnoException) => void;
21
29
  }
22
30
  export interface DaemonHandle {
23
31
  httpServer: HttpServer;
@@ -728,6 +728,13 @@ export function startDaemon(opts) {
728
728
  logger.error({ err: err?.message ?? String(err) }, "agent recovery failed");
729
729
  });
730
730
  // Fail cleanly on a bind error (e.g. EADDRINUSE) instead of an unhandled 'error' throw.
731
+ //
732
+ // Deliberately does NOT call `process.exit()` itself: `startDaemon` is a library entry point
733
+ // (embedded by `packages/desktop`, and booted in-process by the daemon integration tests), and a
734
+ // library must never kill its host. Killing the process here made a port collision in the test
735
+ // suite surface as an opaque, misattributed "process.exit unexpectedly called with 1" unhandled
736
+ // rejection with every test still reported green. The process-level decision belongs to the
737
+ // process entry point, which passes `onFatalError` (see `daemon/main.ts`).
731
738
  httpServer.on("error", (err) => {
732
739
  if (err.code === "EADDRINUSE") {
733
740
  logger.error({ host: opts.host, port: opts.port }, "cannot bind — address already in use");
@@ -736,7 +743,7 @@ export function startDaemon(opts) {
736
743
  logger.error({ err: err.message }, "http server error");
737
744
  }
738
745
  process.exitCode = 1;
739
- void wsHandle.close().finally(() => process.exit(1));
746
+ void wsHandle.close().finally(() => opts.onFatalError?.(err));
740
747
  });
741
748
  httpServer.listen(opts.port, opts.host);
742
749
  logger.info({ host: opts.host, port: opts.port }, "http/ws server accepting connections");
@@ -12,6 +12,9 @@ const info = createDaemonRuntimeInfo({
12
12
  const handle = startDaemon({
13
13
  host: info.listen.host,
14
14
  port: info.listen.port,
15
+ // The process-level half of `startDaemon`'s fatal-error contract: the bootstrap logs the error
16
+ // and tears down the WS server, but leaves terminating the process to its entry point.
17
+ onFatalError: () => process.exit(1),
15
18
  });
16
19
  const log = handle.logger;
17
20
  log.info({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@av-pi-studio/server",
3
- "version": "0.0.102",
3
+ "version": "0.0.104",
4
4
  "bin": {
5
5
  "pi-studio-daemon": "dist/daemon/main.js"
6
6
  },
@@ -24,10 +24,10 @@
24
24
  "clean": "rm -rf dist *.tsbuildinfo"
25
25
  },
26
26
  "dependencies": {
27
- "@av-pi-studio/highlight": "^0.0.102",
28
- "@av-pi-studio/protocol": "^0.0.102",
29
- "@av-pi-studio/relay": "^0.0.102",
30
- "@earendil-works/pi-coding-agent": "^0.84.1",
27
+ "@av-pi-studio/highlight": "^0.0.104",
28
+ "@av-pi-studio/protocol": "^0.0.104",
29
+ "@av-pi-studio/relay": "^0.0.104",
30
+ "@earendil-works/pi-coding-agent": "^0.84.4",
31
31
  "@xterm/addon-serialize": "^0.14.0",
32
32
  "@xterm/headless": "^6.0.0",
33
33
  "bcryptjs": "^3.0.3",
@@ -1,15 +0,0 @@
1
- import type { HandlerRegistry } from "../ws/router.js";
2
- import { AgentTimelineStore as TimelineStore } from "./timeline-store.js";
3
- export interface RewindDeps {
4
- /** Look up an agent's timeline store by agentId. Returns undefined if not found. */
5
- getTimelineStore: (agentId: string) => TimelineStore | undefined;
6
- /**
7
- * Revert workspace file changes since the checkpoint at / before messageId.
8
- * For worktree-backed workspaces this means a git-based revert.
9
- * Returns a promise that resolves on success or rejects on failure.
10
- * TODO(verify): exact checkpoint strategy for non-git workspaces.
11
- */
12
- revertFilesSince: (agentId: string, messageId: string) => Promise<void>;
13
- }
14
- export declare function registerRewindHandler(registry: HandlerRegistry, deps: RewindDeps): void;
15
- //# sourceMappingURL=rewind-rpc.d.ts.map
@@ -1,30 +0,0 @@
1
- // Rewind RPC handler — sprint-015/task-007.
2
- // features/rewind.md § Wire contract, § Behavior & Algorithms (daemon side)
3
- import { agentRewindRequestSchema, agentRewindResponseSchema, } from "@av-pi-studio/protocol";
4
- import { AgentTimelineStore as TimelineStore } from "./timeline-store.js";
5
- export function registerRewindHandler(registry, deps) {
6
- registry.register("agent.rewind.request", async (ctx) => {
7
- const parsed = agentRewindRequestSchema.safeParse(ctx.message);
8
- if (!parsed.success)
9
- throw new Error(`Invalid rewind request: ${parsed.error.message}`);
10
- const { agentId, messageId, mode, requestId } = parsed.data;
11
- const rewindConversation = mode !== "files";
12
- const rewindFiles = mode !== "conversation";
13
- let truncatedAt;
14
- if (rewindConversation) {
15
- const store = deps.getTimelineStore(agentId);
16
- if (!store)
17
- throw new Error(`Agent not found: ${agentId}`);
18
- truncatedAt = store.truncateBeforeMessage(messageId);
19
- }
20
- if (rewindFiles) {
21
- await deps.revertFilesSince(agentId, messageId);
22
- }
23
- return agentRewindResponseSchema.parse({
24
- type: "agent.rewind.response",
25
- requestId,
26
- payload: { agentId, messageId, mode, truncatedAt },
27
- });
28
- });
29
- }
30
- //# sourceMappingURL=rewind-rpc.js.map