@av-pi-studio/server 0.0.101 → 0.0.103

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.
@@ -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`
@@ -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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@av-pi-studio/server",
3
- "version": "0.0.101",
3
+ "version": "0.0.103",
4
4
  "bin": {
5
5
  "pi-studio-daemon": "dist/daemon/main.js"
6
6
  },
@@ -24,9 +24,9 @@
24
24
  "clean": "rm -rf dist *.tsbuildinfo"
25
25
  },
26
26
  "dependencies": {
27
- "@av-pi-studio/highlight": "^0.0.101",
28
- "@av-pi-studio/protocol": "^0.0.101",
29
- "@av-pi-studio/relay": "^0.0.101",
27
+ "@av-pi-studio/highlight": "^0.0.103",
28
+ "@av-pi-studio/protocol": "^0.0.103",
29
+ "@av-pi-studio/relay": "^0.0.103",
30
30
  "@earendil-works/pi-coding-agent": "^0.84.1",
31
31
  "@xterm/addon-serialize": "^0.14.0",
32
32
  "@xterm/headless": "^6.0.0",
@@ -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