@av-pi-studio/server 0.0.108 → 0.0.110
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/dist/agent/agent-service.d.ts +15 -0
- package/dist/agent/agent-service.js +37 -11
- package/dist/agent/provider-contract.d.ts +8 -0
- package/dist/agent/providers/mock/mock-provider.d.ts +5 -6
- package/dist/agent/providers/mock/mock-provider.js +25 -3
- package/dist/agent/providers/pi/agent.d.ts +4 -6
- package/dist/agent/providers/pi/agent.js +31 -22
- package/dist/agent/providers/pi/event-mapper.js +52 -2
- package/dist/agent/providers/pi/session-hydration.js +13 -0
- package/dist/agent/slash-command-operations.d.ts +27 -3
- package/dist/agent/slash-command-operations.js +86 -9
- package/dist/agent/timeline-rpc.js +3 -13
- package/dist/daemon/bootstrap.js +0 -13
- package/dist/daemon/dev-bootstrap.js +0 -13
- package/package.json +3 -3
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { AgentStreamEvent } from "@av-pi-studio/protocol";
|
|
1
2
|
import type { Logger } from "../logging/logger.js";
|
|
2
3
|
import type { Session } from "../ws/session.js";
|
|
3
4
|
import type { HandlerRegistry } from "../ws/router.js";
|
|
@@ -37,6 +38,20 @@ export declare function seedTimeline(agentId: string, rows: import("./timeline-s
|
|
|
37
38
|
* need to special-case a never-spawned session.
|
|
38
39
|
*/
|
|
39
40
|
export declare function resetTimeline(agentId: string, rows: import("./timeline-store.js").TimelineRow[]): void;
|
|
41
|
+
/**
|
|
42
|
+
* Record `event` on `agentId`'s timeline and broadcast it as an `agent_stream` frame carrying the
|
|
43
|
+
* daemon-owned seq/timestamp. The one append-and-broadcast path for stream events: `runTurn`'s
|
|
44
|
+
* subscription and any operation that subscribes outside a turn (today: compaction) both use it.
|
|
45
|
+
*/
|
|
46
|
+
export declare function appendStreamEvent(agentId: string, event: AgentStreamEvent, broadcast: (sessions: Iterable<Session>, message: unknown) => void, sessions: Iterable<Session>): void;
|
|
47
|
+
/**
|
|
48
|
+
* Seed `agentId`'s in-memory timeline from its provider's durable history when it has none yet (a
|
|
49
|
+
* restarted daemon never has one). No-op when a store exists, or when the record has no persisted
|
|
50
|
+
* handle / the provider has nothing to replay. Anything that is about to append to a timeline
|
|
51
|
+
* outside `runTurn` must call this first: the first append would otherwise create an empty store,
|
|
52
|
+
* and `seedTimeline` never overwrites an existing one, so history would never hydrate.
|
|
53
|
+
*/
|
|
54
|
+
export declare function ensureTimelineSeeded(agentId: string, manager: AgentManager, resolveClient: (provider: string) => AgentClient): void;
|
|
40
55
|
/**
|
|
41
56
|
* Ensure `agentId` has a live provider session: resume from a persisted handle, or — for a
|
|
42
57
|
* deferred draft that was never spawned (`record.persistence` absent; see `AgentService.handleCreate`
|
|
@@ -39,6 +39,42 @@ export function seedTimeline(agentId, rows) {
|
|
|
39
39
|
export function resetTimeline(agentId, rows) {
|
|
40
40
|
getOrCreateTimeline(agentId).replaceRows(rows);
|
|
41
41
|
}
|
|
42
|
+
/**
|
|
43
|
+
* Record `event` on `agentId`'s timeline and broadcast it as an `agent_stream` frame carrying the
|
|
44
|
+
* daemon-owned seq/timestamp. The one append-and-broadcast path for stream events: `runTurn`'s
|
|
45
|
+
* subscription and any operation that subscribes outside a turn (today: compaction) both use it.
|
|
46
|
+
*/
|
|
47
|
+
export function appendStreamEvent(agentId, event, broadcast, sessions) {
|
|
48
|
+
const row = getOrCreateTimeline(agentId).append(event);
|
|
49
|
+
broadcast(sessions, {
|
|
50
|
+
type: "session",
|
|
51
|
+
message: {
|
|
52
|
+
type: "agent_stream",
|
|
53
|
+
agentId,
|
|
54
|
+
seq: row.seq,
|
|
55
|
+
timestamp: row.timestamp,
|
|
56
|
+
event,
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Seed `agentId`'s in-memory timeline from its provider's durable history when it has none yet (a
|
|
62
|
+
* restarted daemon never has one). No-op when a store exists, or when the record has no persisted
|
|
63
|
+
* handle / the provider has nothing to replay. Anything that is about to append to a timeline
|
|
64
|
+
* outside `runTurn` must call this first: the first append would otherwise create an empty store,
|
|
65
|
+
* and `seedTimeline` never overwrites an existing one, so history would never hydrate.
|
|
66
|
+
*/
|
|
67
|
+
export function ensureTimelineSeeded(agentId, manager, resolveClient) {
|
|
68
|
+
if (timelinesByAgentId.has(agentId))
|
|
69
|
+
return;
|
|
70
|
+
const record = manager.get(agentId)?.record;
|
|
71
|
+
const handle = record?.persistence;
|
|
72
|
+
if (!record || !handle)
|
|
73
|
+
return;
|
|
74
|
+
const rows = resolveClient(record.provider).hydrateTimeline?.(handle) ?? [];
|
|
75
|
+
if (rows.length > 0)
|
|
76
|
+
seedTimeline(agentId, rows);
|
|
77
|
+
}
|
|
42
78
|
/**
|
|
43
79
|
* Ensure `agentId` has a live provider session: resume from a persisted handle, or — for a
|
|
44
80
|
* deferred draft that was never spawned (`record.persistence` absent; see `AgentService.handleCreate`
|
|
@@ -249,17 +285,7 @@ export class AgentService {
|
|
|
249
285
|
}
|
|
250
286
|
}
|
|
251
287
|
// All other events: append + broadcast.
|
|
252
|
-
|
|
253
|
-
this.broadcastAll(getSessions(), {
|
|
254
|
-
type: "session",
|
|
255
|
-
message: {
|
|
256
|
-
type: "agent_stream",
|
|
257
|
-
agentId,
|
|
258
|
-
seq: row.seq,
|
|
259
|
-
timestamp: row.timestamp,
|
|
260
|
-
event,
|
|
261
|
-
},
|
|
262
|
-
});
|
|
288
|
+
appendStreamEvent(agentId, event, this.deps.broadcast, getSessions());
|
|
263
289
|
});
|
|
264
290
|
// If provider never emits a user_message, emit one ourselves.
|
|
265
291
|
if (!userMessageEmitted) {
|
|
@@ -95,6 +95,8 @@ export interface AgentCompactResult {
|
|
|
95
95
|
summary?: string;
|
|
96
96
|
firstKeptEntryId?: string;
|
|
97
97
|
tokensBefore?: number;
|
|
98
|
+
/** Pi's estimate of the context size after compaction (not persisted). */
|
|
99
|
+
estimatedTokensAfter?: number;
|
|
98
100
|
details?: unknown;
|
|
99
101
|
}
|
|
100
102
|
export interface AgentForkMessage {
|
|
@@ -251,6 +253,9 @@ export interface AgentSession {
|
|
|
251
253
|
}>;
|
|
252
254
|
/** `/model` (set) — mirrors Pi RPC `set_model` (distinct from the legacy string-only `setModel?`). */
|
|
253
255
|
setProviderModel?(provider: string, modelId: string): Promise<unknown>;
|
|
256
|
+
/** The models THIS process can switch to — mirrors Pi RPC `get_available_models`. Pi loads
|
|
257
|
+
* `models.json` once at spawn, so after an edit a fresh process's list can differ from this one. */
|
|
258
|
+
listModels?(): Promise<AgentModelDefinition[]>;
|
|
254
259
|
/** `/model` (cycle) — mirrors Pi RPC `cycle_model`. */
|
|
255
260
|
cycleModel?(): Promise<AgentCycleModelResult>;
|
|
256
261
|
/** `/copy` — mirrors Pi RPC `get_last_assistant_text`. */
|
|
@@ -266,8 +271,11 @@ export interface AgentClient {
|
|
|
266
271
|
readonly capabilities: AgentCapabilityFlags;
|
|
267
272
|
createSession(config: AgentSessionConfig, launchContext?: LaunchContext, options?: CreateSessionOptions): Promise<AgentSession>;
|
|
268
273
|
resumeSession(handle: PersistenceHandle, overrides?: Partial<AgentSessionConfig>, launchContext?: LaunchContext): Promise<AgentSession>;
|
|
274
|
+
/** `session`: a live session of this provider whose own list should answer (see
|
|
275
|
+
* `AgentSession.listModels`) — otherwise a fresh, sessionless discovery. */
|
|
269
276
|
listModels(opts?: {
|
|
270
277
|
cwd?: string;
|
|
278
|
+
session?: AgentSession;
|
|
271
279
|
}): Promise<AgentModelDefinition[]>;
|
|
272
280
|
isAvailable(): Promise<boolean> | boolean;
|
|
273
281
|
listModes?(opts?: {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AgentCapabilityFlags, AgentSessionConfig, AgentStreamEvent } from "@av-pi-studio/protocol";
|
|
2
|
-
import type { AgentClient, AgentCommandDefinition, AgentModeDefinition, AgentModelDefinition, AgentSession, CreateSessionOptions, LaunchContext, PendingPermission, PersistenceHandle, ProviderRuntimeInfo, ProviderUiRequest, ProviderUiResponse, Unsubscribe } from "../../provider-contract.js";
|
|
2
|
+
import type { AgentClient, AgentCommandDefinition, AgentCompactResult, AgentModeDefinition, AgentModelDefinition, AgentSession, CreateSessionOptions, LaunchContext, PendingPermission, PersistenceHandle, ProviderRuntimeInfo, ProviderUiRequest, ProviderUiResponse, Unsubscribe } from "../../provider-contract.js";
|
|
3
3
|
/**
|
|
4
4
|
* In-process `mock` provider (features/agent-providers.md § Provider entry — dev/test only). It
|
|
5
5
|
* implements the `AgentClient`/`AgentSession` contracts in memory and emits a scripted turn. Never
|
|
@@ -9,6 +9,8 @@ export declare const MOCK_CAPABILITIES: AgentCapabilityFlags;
|
|
|
9
9
|
export interface MockSessionOptions {
|
|
10
10
|
/** Delay before a started turn completes (ms). Small but non-zero so `interrupt` can win. */
|
|
11
11
|
turnDelayMs?: number;
|
|
12
|
+
/** How long a mock `compact()` stays in its `started` phase (ms). */
|
|
13
|
+
compactDelayMs?: number;
|
|
12
14
|
}
|
|
13
15
|
/** Exported so tests (this file's, and downstream sprint-066 task-003/004 daemon-level tests) can
|
|
14
16
|
* cast a created session to reach `emitUiRequest`/`uiResponses`, which are deliberately not part
|
|
@@ -33,6 +35,7 @@ export declare class MockAgentSession implements AgentSession {
|
|
|
33
35
|
private readonly subscribers;
|
|
34
36
|
private readonly history;
|
|
35
37
|
private readonly turnDelayMs;
|
|
38
|
+
private readonly compactDelayMs;
|
|
36
39
|
private activeTurn;
|
|
37
40
|
private completionTimer;
|
|
38
41
|
private mode;
|
|
@@ -96,11 +99,7 @@ export declare class MockAgentSession implements AgentSession {
|
|
|
96
99
|
total: number;
|
|
97
100
|
};
|
|
98
101
|
}>;
|
|
99
|
-
compact(): Promise<
|
|
100
|
-
summary: string;
|
|
101
|
-
firstKeptEntryId: string;
|
|
102
|
-
tokensBefore: number;
|
|
103
|
-
}>;
|
|
102
|
+
compact(): Promise<AgentCompactResult>;
|
|
104
103
|
newSession(): Promise<{
|
|
105
104
|
cancelled: boolean;
|
|
106
105
|
}>;
|
|
@@ -22,6 +22,10 @@ const MOCK_MODES = [
|
|
|
22
22
|
/** Static thinking-level list for the mock provider (sprint-070/task-001) — small enough to
|
|
23
23
|
* exercise clamping in the dev daemon without mirroring Pi's full 7-level ladder. */
|
|
24
24
|
const MOCK_THINKING_LEVELS = ["off", "low", "medium", "high"];
|
|
25
|
+
/** Long enough to see the in-progress state in `npm run dev:daemon`. */
|
|
26
|
+
const MOCK_COMPACT_DELAY_MS = 1500;
|
|
27
|
+
const MOCK_COMPACT_TOKENS_BEFORE = 168_000;
|
|
28
|
+
const MOCK_COMPACT_TOKENS_AFTER = 14_000;
|
|
25
29
|
/** Exported so tests (this file's, and downstream sprint-066 task-003/004 daemon-level tests) can
|
|
26
30
|
* cast a created session to reach `emitUiRequest`/`uiResponses`, which are deliberately not part
|
|
27
31
|
* of the provider-neutral `AgentSession` contract. */
|
|
@@ -33,6 +37,7 @@ export class MockAgentSession {
|
|
|
33
37
|
subscribers = new Set();
|
|
34
38
|
history = [];
|
|
35
39
|
turnDelayMs;
|
|
40
|
+
compactDelayMs;
|
|
36
41
|
activeTurn = null;
|
|
37
42
|
completionTimer = null;
|
|
38
43
|
mode = "default";
|
|
@@ -51,6 +56,7 @@ export class MockAgentSession {
|
|
|
51
56
|
constructor(config, options = {}) {
|
|
52
57
|
this.config = config;
|
|
53
58
|
this.turnDelayMs = options.turnDelayMs ?? 5;
|
|
59
|
+
this.compactDelayMs = options.compactDelayMs ?? MOCK_COMPACT_DELAY_MS;
|
|
54
60
|
}
|
|
55
61
|
emit(event) {
|
|
56
62
|
this.history.push(event);
|
|
@@ -282,12 +288,28 @@ export class MockAgentSession {
|
|
|
282
288
|
tokens: { total: 0 },
|
|
283
289
|
});
|
|
284
290
|
}
|
|
285
|
-
compact() {
|
|
286
|
-
|
|
291
|
+
async compact() {
|
|
292
|
+
const compactionId = randomUUID();
|
|
293
|
+
this.emit({ kind: "compaction", compactionId, phase: "started", reason: "manual" });
|
|
294
|
+
const delay = Promise.withResolvers();
|
|
295
|
+
setTimeout(delay.resolve, this.compactDelayMs);
|
|
296
|
+
await delay.promise;
|
|
297
|
+
const result = {
|
|
287
298
|
summary: "mock compaction summary",
|
|
288
299
|
firstKeptEntryId: "mock-entry-0",
|
|
289
|
-
tokensBefore:
|
|
300
|
+
tokensBefore: MOCK_COMPACT_TOKENS_BEFORE,
|
|
301
|
+
estimatedTokensAfter: MOCK_COMPACT_TOKENS_AFTER,
|
|
302
|
+
};
|
|
303
|
+
this.emit({
|
|
304
|
+
kind: "compaction",
|
|
305
|
+
compactionId,
|
|
306
|
+
phase: "completed",
|
|
307
|
+
reason: "manual",
|
|
308
|
+
tokensBefore: result.tokensBefore,
|
|
309
|
+
estimatedTokensAfter: result.estimatedTokensAfter,
|
|
310
|
+
summary: result.summary,
|
|
290
311
|
});
|
|
312
|
+
return result;
|
|
291
313
|
}
|
|
292
314
|
newSession() {
|
|
293
315
|
return Promise.resolve({ cancelled: false });
|
|
@@ -77,15 +77,13 @@ export declare class PiAgentClient implements AgentClient {
|
|
|
77
77
|
*/
|
|
78
78
|
resumeSession(handle: PersistenceHandle, overrides?: Partial<AgentSessionConfig>, launchContext?: LaunchContext): Promise<AgentSession>;
|
|
79
79
|
/**
|
|
80
|
-
* Discover models via the Pi RPC `get_available_models` command (no scratch session)
|
|
81
|
-
*
|
|
82
|
-
*
|
|
83
|
-
* (sprint-043: dropping this field here caused every `agent_set_model_request` to fail with
|
|
84
|
-
* "Model not found: pi/<modelId>" — "pi" is the pi-studio `AgentClient` id, never a real LLM
|
|
85
|
-
* provider Pi recognizes).
|
|
80
|
+
* Discover models via the Pi RPC `get_available_models` command (no scratch session): from the
|
|
81
|
+
* given live `session`'s own process when there is one — the only list its `set_model` accepts —
|
|
82
|
+
* else from a fresh top-level process, which reads the current `models.json`.
|
|
86
83
|
*/
|
|
87
84
|
listModels(opts?: {
|
|
88
85
|
cwd?: string;
|
|
86
|
+
session?: AgentSession;
|
|
89
87
|
}): Promise<AgentModelDefinition[]>;
|
|
90
88
|
/** Pi RPC has no `list_modes`; modes come from the provider manifest, not the process. */
|
|
91
89
|
listModes(): Promise<AgentModeDefinition[]>;
|
|
@@ -43,6 +43,28 @@ function modelIdFrom(model) {
|
|
|
43
43
|
return rec.name;
|
|
44
44
|
return undefined;
|
|
45
45
|
}
|
|
46
|
+
/** Map a `get_available_models` response (raw Pi `Model` objects, docs/rpc.md § Model) to the
|
|
47
|
+
* contract's definitions. Each entry's own `provider` (the underlying LLM provider, e.g.
|
|
48
|
+
* `"anthropic"`) is REQUIRED to call `set_model` back (sprint-043: dropping it caused every
|
|
49
|
+
* `agent_set_model_request` to fail with "Model not found: pi/<modelId>" — "pi" is the pi-studio
|
|
50
|
+
* `AgentClient` id, never a real LLM provider Pi recognizes). */
|
|
51
|
+
function toModelDefinitions(data) {
|
|
52
|
+
const raw = data && typeof data === "object" && "models" in data ? data.models : undefined;
|
|
53
|
+
const models = Array.isArray(raw) ? raw : [];
|
|
54
|
+
return models.map((m) => {
|
|
55
|
+
const rec = m;
|
|
56
|
+
return {
|
|
57
|
+
id: String(rec.id ?? rec.name ?? ""),
|
|
58
|
+
label: typeof rec.name === "string" ? rec.name : String(rec.id ?? ""),
|
|
59
|
+
provider: typeof rec.provider === "string" ? rec.provider : undefined,
|
|
60
|
+
// Raw Pi `Model` objects carry `reasoning` + `thinkingLevelMap`; surface the derived
|
|
61
|
+
// per-model level list so clients can offer draft sessions the right levels with no
|
|
62
|
+
// live process (sprint-070/task-001).
|
|
63
|
+
reasoning: typeof rec.reasoning === "boolean" ? rec.reasoning : undefined,
|
|
64
|
+
thinkingLevels: deriveThinkingLevels(rec),
|
|
65
|
+
};
|
|
66
|
+
});
|
|
67
|
+
}
|
|
46
68
|
/** Dialog methods block for a client answer; every other extension UI method is fire-and-forget
|
|
47
69
|
* (docs/rpc.md § Extension UI Protocol). The single place the blocking set is encoded — a future Pi
|
|
48
70
|
* release that adds a method only ever touches this constant. */
|
|
@@ -384,6 +406,9 @@ class PiAgentSession {
|
|
|
384
406
|
const data = (await this.transport.request("export_html", params));
|
|
385
407
|
return { path: data?.path ?? "" };
|
|
386
408
|
}
|
|
409
|
+
async listModels() {
|
|
410
|
+
return toModelDefinitions(await this.transport.request("get_available_models"));
|
|
411
|
+
}
|
|
387
412
|
async setProviderModel(provider, modelId) {
|
|
388
413
|
const data = await this.transport.request("set_model", { provider, modelId });
|
|
389
414
|
const resolved = modelIdFrom(data);
|
|
@@ -544,30 +569,14 @@ export class PiAgentClient {
|
|
|
544
569
|
return session;
|
|
545
570
|
}
|
|
546
571
|
/**
|
|
547
|
-
* Discover models via the Pi RPC `get_available_models` command (no scratch session)
|
|
548
|
-
*
|
|
549
|
-
*
|
|
550
|
-
* (sprint-043: dropping this field here caused every `agent_set_model_request` to fail with
|
|
551
|
-
* "Model not found: pi/<modelId>" — "pi" is the pi-studio `AgentClient` id, never a real LLM
|
|
552
|
-
* provider Pi recognizes).
|
|
572
|
+
* Discover models via the Pi RPC `get_available_models` command (no scratch session): from the
|
|
573
|
+
* given live `session`'s own process when there is one — the only list its `set_model` accepts —
|
|
574
|
+
* else from a fresh top-level process, which reads the current `models.json`.
|
|
553
575
|
*/
|
|
554
576
|
async listModels(opts) {
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
return models.map((m) => {
|
|
559
|
-
const rec = m;
|
|
560
|
-
return {
|
|
561
|
-
id: String(rec.id ?? rec.name ?? ""),
|
|
562
|
-
label: typeof rec.name === "string" ? rec.name : String(rec.id ?? ""),
|
|
563
|
-
provider: typeof rec.provider === "string" ? rec.provider : undefined,
|
|
564
|
-
// Raw Pi `Model` objects carry `reasoning` + `thinkingLevelMap`; surface the derived
|
|
565
|
-
// per-model level list so clients can offer draft sessions the right levels with no
|
|
566
|
-
// live process (sprint-070/task-001).
|
|
567
|
-
reasoning: typeof rec.reasoning === "boolean" ? rec.reasoning : undefined,
|
|
568
|
-
thinkingLevels: deriveThinkingLevels(rec),
|
|
569
|
-
};
|
|
570
|
-
});
|
|
577
|
+
if (opts?.session?.listModels)
|
|
578
|
+
return opts.session.listModels();
|
|
579
|
+
return toModelDefinitions(await this.topLevel("get_available_models", opts?.cwd));
|
|
571
580
|
}
|
|
572
581
|
/** Pi RPC has no `list_modes`; modes come from the provider manifest, not the process. */
|
|
573
582
|
listModes() {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
1
2
|
/**
|
|
2
3
|
* Maps raw Pi RPC events → provider-neutral `AgentStreamEvent`s, and Pi tool calls →
|
|
3
4
|
* `ToolCallDetail` kinds (features/agent-sessions.md § Stream events). The exact Pi event schema is
|
|
@@ -9,6 +10,7 @@ function asRecord(value) {
|
|
|
9
10
|
function str(value) {
|
|
10
11
|
return typeof value === "string" ? value : undefined;
|
|
11
12
|
}
|
|
13
|
+
const COMPACTION_REASONS = ["manual", "threshold", "overflow"];
|
|
12
14
|
/** Join `result.content` text blocks (Pi RPC `tool_execution_end` shape) into one string. */
|
|
13
15
|
function outputOf(tool) {
|
|
14
16
|
const content = asRecord(tool.result).content;
|
|
@@ -98,6 +100,8 @@ export function createPiEventMapper() {
|
|
|
98
100
|
disposition = next;
|
|
99
101
|
error = nextError;
|
|
100
102
|
};
|
|
103
|
+
/** Id of the compaction between `compaction_start` and its `compaction_end`, if any. */
|
|
104
|
+
let openCompactionId;
|
|
101
105
|
return {
|
|
102
106
|
map(raw) {
|
|
103
107
|
const event = asRecord(raw);
|
|
@@ -216,6 +220,54 @@ export function createPiEventMapper() {
|
|
|
216
220
|
return { kind: "error", message: str(event.error) };
|
|
217
221
|
case "error":
|
|
218
222
|
return { kind: "error", message: str(event.message ?? event.error) };
|
|
223
|
+
// ── Context compaction (manual + automatic) ──
|
|
224
|
+
// Pi emits `compaction_start {reason}` and `compaction_end {reason, result?, aborted,
|
|
225
|
+
// willRetry, errorMessage?}`; the mapper mints one id per compaction so the two halves
|
|
226
|
+
// upsert a single timeline row. Every failure path inside Pi's `compact()` emits an end
|
|
227
|
+
// (no `result`, `errorMessage`) before throwing, so an end always closes the row.
|
|
228
|
+
case "compaction_start": {
|
|
229
|
+
openCompactionId = randomUUID();
|
|
230
|
+
const reason = COMPACTION_REASONS.find((r) => r === event.reason);
|
|
231
|
+
return {
|
|
232
|
+
kind: "compaction",
|
|
233
|
+
compactionId: openCompactionId,
|
|
234
|
+
phase: "started",
|
|
235
|
+
...(reason ? { reason } : {}),
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
case "compaction_end": {
|
|
239
|
+
const compactionId = openCompactionId ?? randomUUID();
|
|
240
|
+
openCompactionId = undefined;
|
|
241
|
+
const reason = COMPACTION_REASONS.find((r) => r === event.reason);
|
|
242
|
+
const base = { kind: "compaction", compactionId, ...(reason ? { reason } : {}) };
|
|
243
|
+
if (event.aborted === true)
|
|
244
|
+
return { ...base, phase: "canceled" };
|
|
245
|
+
if (event.result && typeof event.result === "object") {
|
|
246
|
+
const result = asRecord(event.result);
|
|
247
|
+
return {
|
|
248
|
+
...base,
|
|
249
|
+
phase: "completed",
|
|
250
|
+
tokensBefore: typeof result.tokensBefore === "number" ? result.tokensBefore : undefined,
|
|
251
|
+
estimatedTokensAfter: typeof result.estimatedTokensAfter === "number"
|
|
252
|
+
? result.estimatedTokensAfter
|
|
253
|
+
: undefined,
|
|
254
|
+
summary: str(result.summary),
|
|
255
|
+
...(event.willRetry === true ? { willRetry: true } : {}),
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
// Pi formats its own failure text as `Compaction failed: <cause>` (manual) or
|
|
259
|
+
// `Auto-compaction failed: <cause>` (automatic), and the web client's row label already
|
|
260
|
+
// says "Compaction failed" - so carry only the cause. Other texts, e.g. `Context overflow
|
|
261
|
+
// recovery failed: ...`, say something the label does not and pass through untouched.
|
|
262
|
+
const cause = str(event.errorMessage)
|
|
263
|
+
?.replace(/^(?:auto-)?compaction failed:?\s*/i, "")
|
|
264
|
+
.trim();
|
|
265
|
+
return {
|
|
266
|
+
...base,
|
|
267
|
+
phase: "failed",
|
|
268
|
+
...(cause ? { error: cause } : {}),
|
|
269
|
+
};
|
|
270
|
+
}
|
|
219
271
|
// ── Ignored (handled elsewhere / not surfaced as timeline events) ──
|
|
220
272
|
// `auto_retry_end` left Pi's *declared* session-event union in 0.85.0 but the shipped
|
|
221
273
|
// bundle still emits it, so the case stays. This switch is on a loose `string`, not Pi's
|
|
@@ -226,8 +278,6 @@ export function createPiEventMapper() {
|
|
|
226
278
|
case "message_start":
|
|
227
279
|
case "message_end":
|
|
228
280
|
case "tool_execution_update":
|
|
229
|
-
case "compaction_start":
|
|
230
|
-
case "compaction_end":
|
|
231
281
|
case "auto_retry_start":
|
|
232
282
|
case "auto_retry_end":
|
|
233
283
|
return null;
|
|
@@ -112,6 +112,19 @@ function mapMessage(message) {
|
|
|
112
112
|
function mapEntry(entry) {
|
|
113
113
|
if (entry.type === "message")
|
|
114
114
|
return mapMessage(entry.message);
|
|
115
|
+
// Pi persists neither `reason` nor `estimatedTokensAfter`, and writes nothing for a failed or
|
|
116
|
+
// cancelled compaction — so a replayed one is always a lone `completed` row.
|
|
117
|
+
if (entry.type === "compaction") {
|
|
118
|
+
return [
|
|
119
|
+
{
|
|
120
|
+
kind: "compaction",
|
|
121
|
+
phase: "completed",
|
|
122
|
+
compactionId: entry.id,
|
|
123
|
+
tokensBefore: entry.tokensBefore,
|
|
124
|
+
summary: entry.summary,
|
|
125
|
+
},
|
|
126
|
+
];
|
|
127
|
+
}
|
|
115
128
|
return [];
|
|
116
129
|
}
|
|
117
130
|
/**
|
|
@@ -2,7 +2,7 @@ import type { Session } from "../ws/session.js";
|
|
|
2
2
|
import type { HandlerRegistry } from "../ws/router.js";
|
|
3
3
|
import type { Logger } from "../logging/logger.js";
|
|
4
4
|
import type { AgentManager } from "./agent-manager.js";
|
|
5
|
-
import type { AgentClient } from "./provider-contract.js";
|
|
5
|
+
import type { AgentClient, AgentModelDefinition } from "./provider-contract.js";
|
|
6
6
|
/**
|
|
7
7
|
* Slash-command operations (sprint-037): Pi built-in commands that have a real Pi RPC equivalent
|
|
8
8
|
* — /session, /compact, /new, /resume, /fork, /clone, /name, /export, /model, /copy — surfaced as
|
|
@@ -12,7 +12,8 @@ import type { AgentClient } from "./provider-contract.js";
|
|
|
12
12
|
*
|
|
13
13
|
* Also hosts command *discovery* (sprint-040): `agent_list_commands_request` surfaces Pi's
|
|
14
14
|
* `get_commands` (extension commands, prompt templates, skills) for a live session — a disjoint
|
|
15
|
-
* set from the built-in slash commands above
|
|
15
|
+
* set from the built-in slash commands above — and the model picker's `list_provider_models`,
|
|
16
|
+
* next to the `set_model` it feeds.
|
|
16
17
|
*
|
|
17
18
|
* Pi's own RPC contract is explicit that TUI-only built-ins (/settings, /hotkeys, etc.) have no
|
|
18
19
|
* RPC equivalent and would not execute if sent via `prompt` — those are intentionally NOT
|
|
@@ -24,6 +25,12 @@ export interface SlashCommandOpsDeps {
|
|
|
24
25
|
broadcast: (sessions: Iterable<Session>, message: unknown) => void;
|
|
25
26
|
logger?: Logger;
|
|
26
27
|
}
|
|
28
|
+
export interface ListProviderModelsResult {
|
|
29
|
+
type: "list_provider_models_response";
|
|
30
|
+
requestId: string;
|
|
31
|
+
provider: string;
|
|
32
|
+
models: AgentModelDefinition[];
|
|
33
|
+
}
|
|
27
34
|
export declare class SlashCommandOperationsService {
|
|
28
35
|
private readonly deps;
|
|
29
36
|
constructor(deps: SlashCommandOpsDeps);
|
|
@@ -34,7 +41,18 @@ export declare class SlashCommandOperationsService {
|
|
|
34
41
|
* stats poll a self-correcting source for the status bar's model segment, covering `/model`
|
|
35
42
|
* cycle and cross-client changes that `agent_update` alone doesn't fully convey). */
|
|
36
43
|
handleSessionStats(msg: Record<string, unknown>): Promise<unknown>;
|
|
37
|
-
/**
|
|
44
|
+
/**
|
|
45
|
+
* `/compact` — context changed, broadcast.
|
|
46
|
+
*
|
|
47
|
+
* Pi's `compact()` starts with `abort()`, so compacting mid-turn would kill the run and a second
|
|
48
|
+
* concurrent compact would cancel the first: both are refused with `busy` BEFORE anything is
|
|
49
|
+
* resumed or subscribed. A record with no live process (every record after a daemon restart) is
|
|
50
|
+
* resumed first — compacting an old, oversized session before continuing it is a primary use.
|
|
51
|
+
*
|
|
52
|
+
* Compaction runs outside any turn, so `runTurn`'s subscription is not there to record its
|
|
53
|
+
* `compaction` events: this handler holds its own subscription window for the duration of the
|
|
54
|
+
* call and forwards only `compaction` events through the shared `appendStreamEvent` path.
|
|
55
|
+
*/
|
|
38
56
|
handleCompact(msg: Record<string, unknown>, getSessions: () => Iterable<Session>): Promise<unknown>;
|
|
39
57
|
/**
|
|
40
58
|
* `/new` — starts a fresh session in place; broadcast.
|
|
@@ -101,6 +119,12 @@ export declare class SlashCommandOperationsService {
|
|
|
101
119
|
* always the EFFECTIVE level (Pi clamps silently; the provider re-reads `get_state`), so the
|
|
102
120
|
* wire, the record, and the live process can never disagree. */
|
|
103
121
|
private persistThinking;
|
|
122
|
+
/** Model picker list (sprint-043). With an `agentId` whose live session belongs to `provider`,
|
|
123
|
+
* the agent's own process answers: Pi loads `models.json` once at spawn, so a fresh process can
|
|
124
|
+
* offer a model this agent's `set_model` then rejects ("Model not found") after the file was
|
|
125
|
+
* edited. With no agent, or no live process (it spawns fresh, reading the current file), a
|
|
126
|
+
* sessionless discovery answers as before. */
|
|
127
|
+
handleListProviderModels(msg: Record<string, unknown>, requestId: string | undefined): Promise<ListProviderModelsResult>;
|
|
104
128
|
/** `/model` (set) — broadcast the model change and persist it (see `persistModel`). A
|
|
105
129
|
* materialized draft with no live process yet (`managed.session === null` — deferred-draft
|
|
106
130
|
* creation, `agent-service.ts` `handleCreate`, defers the real spawn to first send) has no
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { resetTimeline, spawnOrResumeSession } from "./agent-service.js";
|
|
1
|
+
import { appendStreamEvent, ensureTimelineSeeded, 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);
|
|
@@ -12,6 +12,9 @@ function requireSession(manager, agentId) {
|
|
|
12
12
|
function unsupported(agentId, op) {
|
|
13
13
|
return new Error(`agent ${agentId}'s provider does not support '${op}'`);
|
|
14
14
|
}
|
|
15
|
+
/** Agent ids with a `compact` call in flight (a daemon restart kills the Pi child and any
|
|
16
|
+
* compaction with it, so in-memory is enough). */
|
|
17
|
+
const compactionsInFlight = new Set();
|
|
15
18
|
export class SlashCommandOperationsService {
|
|
16
19
|
deps;
|
|
17
20
|
constructor(deps) {
|
|
@@ -27,6 +30,7 @@ export class SlashCommandOperationsService {
|
|
|
27
30
|
registry.register("agent_clone_request", (ctx) => this.handleClone(ctx.message, getActiveSessions));
|
|
28
31
|
registry.register("agent_set_session_name_request", (ctx) => this.handleSetSessionName(ctx.message, getActiveSessions));
|
|
29
32
|
registry.register("agent_export_html_request", (ctx) => this.handleExportHtml(ctx.message));
|
|
33
|
+
registry.register("list_provider_models", (ctx) => this.handleListProviderModels(ctx.message, ctx.requestId));
|
|
30
34
|
registry.register("agent_set_model_request", (ctx) => this.handleSetModel(ctx.message, getActiveSessions));
|
|
31
35
|
registry.register("agent_cycle_model_request", (ctx) => this.handleCycleModel(ctx.message, getActiveSessions));
|
|
32
36
|
registry.register("agent_last_assistant_text_request", (ctx) => this.handleLastAssistantText(ctx.message));
|
|
@@ -50,16 +54,75 @@ export class SlashCommandOperationsService {
|
|
|
50
54
|
const payload = stats.model !== undefined ? stats : { ...stats, model: session.getRuntimeInfo().model };
|
|
51
55
|
return { type: "agent_session_stats_response", payload };
|
|
52
56
|
}
|
|
53
|
-
/**
|
|
57
|
+
/**
|
|
58
|
+
* `/compact` — context changed, broadcast.
|
|
59
|
+
*
|
|
60
|
+
* Pi's `compact()` starts with `abort()`, so compacting mid-turn would kill the run and a second
|
|
61
|
+
* concurrent compact would cancel the first: both are refused with `busy` BEFORE anything is
|
|
62
|
+
* resumed or subscribed. A record with no live process (every record after a daemon restart) is
|
|
63
|
+
* resumed first — compacting an old, oversized session before continuing it is a primary use.
|
|
64
|
+
*
|
|
65
|
+
* Compaction runs outside any turn, so `runTurn`'s subscription is not there to record its
|
|
66
|
+
* `compaction` events: this handler holds its own subscription window for the duration of the
|
|
67
|
+
* call and forwards only `compaction` events through the shared `appendStreamEvent` path.
|
|
68
|
+
*/
|
|
54
69
|
async handleCompact(msg, getSessions) {
|
|
55
70
|
const agentId = msg.agentId;
|
|
56
|
-
const
|
|
57
|
-
if (!
|
|
58
|
-
throw
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
71
|
+
const managed = this.deps.manager.get(agentId);
|
|
72
|
+
if (!managed)
|
|
73
|
+
throw new Error(`unknown agent: ${agentId}`);
|
|
74
|
+
if (managed.record.lastStatus === "running") {
|
|
75
|
+
throw new Error(`busy: agent ${agentId} is running; wait for the turn to finish before compacting`);
|
|
76
|
+
}
|
|
77
|
+
if (compactionsInFlight.has(agentId)) {
|
|
78
|
+
throw new Error(`busy: agent ${agentId} is already compacting`);
|
|
79
|
+
}
|
|
80
|
+
compactionsInFlight.add(agentId);
|
|
81
|
+
try {
|
|
82
|
+
const session = managed.session ?? (await spawnOrResumeSession(this.deps, agentId));
|
|
83
|
+
if (!session.compact)
|
|
84
|
+
throw unsupported(agentId, "compact");
|
|
85
|
+
const customInstructions = typeof msg.customInstructions === "string" ? msg.customInstructions : undefined;
|
|
86
|
+
// Before the first append: otherwise the compaction row would create an empty store that
|
|
87
|
+
// `seedTimeline` (never overwrites) could no longer hydrate history into.
|
|
88
|
+
ensureTimelineSeeded(agentId, this.deps.manager, this.deps.resolveClient);
|
|
89
|
+
let openId;
|
|
90
|
+
let terminalSeen = false;
|
|
91
|
+
const unsubscribe = session.subscribe((event) => {
|
|
92
|
+
if (event.kind !== "compaction")
|
|
93
|
+
return;
|
|
94
|
+
if (event.phase === "started")
|
|
95
|
+
openId = event.compactionId;
|
|
96
|
+
else
|
|
97
|
+
terminalSeen = true;
|
|
98
|
+
appendStreamEvent(agentId, event, this.deps.broadcast, getSessions());
|
|
99
|
+
});
|
|
100
|
+
let payload;
|
|
101
|
+
try {
|
|
102
|
+
payload = await session.compact(customInstructions);
|
|
103
|
+
}
|
|
104
|
+
catch (err) {
|
|
105
|
+
// A started row must never be left without its terminal row (process crash, transport
|
|
106
|
+
// failure). Pi's own failures emit `failed` before throwing, so `terminalSeen` is set then.
|
|
107
|
+
if (openId !== undefined && !terminalSeen) {
|
|
108
|
+
appendStreamEvent(agentId, {
|
|
109
|
+
kind: "compaction",
|
|
110
|
+
compactionId: openId,
|
|
111
|
+
phase: "failed",
|
|
112
|
+
error: err instanceof Error ? err.message : String(err),
|
|
113
|
+
}, this.deps.broadcast, getSessions());
|
|
114
|
+
}
|
|
115
|
+
throw err;
|
|
116
|
+
}
|
|
117
|
+
finally {
|
|
118
|
+
unsubscribe();
|
|
119
|
+
}
|
|
120
|
+
this.broadcastAgentUpdate(getSessions, agentId, { compacted: true });
|
|
121
|
+
return { type: "agent_compact_response", payload };
|
|
122
|
+
}
|
|
123
|
+
finally {
|
|
124
|
+
compactionsInFlight.delete(agentId);
|
|
125
|
+
}
|
|
63
126
|
}
|
|
64
127
|
/**
|
|
65
128
|
* `/new` — starts a fresh session in place; broadcast.
|
|
@@ -242,6 +305,20 @@ export class SlashCommandOperationsService {
|
|
|
242
305
|
};
|
|
243
306
|
await this.deps.manager.updateRecord(agentId, { config });
|
|
244
307
|
}
|
|
308
|
+
/** Model picker list (sprint-043). With an `agentId` whose live session belongs to `provider`,
|
|
309
|
+
* the agent's own process answers: Pi loads `models.json` once at spawn, so a fresh process can
|
|
310
|
+
* offer a model this agent's `set_model` then rejects ("Model not found") after the file was
|
|
311
|
+
* edited. With no agent, or no live process (it spawns fresh, reading the current file), a
|
|
312
|
+
* sessionless discovery answers as before. */
|
|
313
|
+
async handleListProviderModels(msg, requestId) {
|
|
314
|
+
const provider = String(msg.provider ?? "pi");
|
|
315
|
+
const cwd = msg.cwd ? String(msg.cwd) : undefined;
|
|
316
|
+
const agentId = typeof msg.agentId === "string" ? msg.agentId : undefined;
|
|
317
|
+
const live = agentId ? this.deps.manager.get(agentId)?.session : undefined;
|
|
318
|
+
const session = live?.provider === provider ? live : undefined;
|
|
319
|
+
const models = await this.deps.resolveClient(provider).listModels({ cwd, session });
|
|
320
|
+
return { type: "list_provider_models_response", requestId: requestId ?? "", provider, models };
|
|
321
|
+
}
|
|
245
322
|
/** `/model` (set) — broadcast the model change and persist it (see `persistModel`). A
|
|
246
323
|
* materialized draft with no live process yet (`managed.session === null` — deferred-draft
|
|
247
324
|
* creation, `agent-service.ts` `handleCreate`, defers the real spawn to first send) has no
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ensureTimelineSeeded, getTimeline } from "./agent-service.js";
|
|
2
2
|
import { DEFAULT_PAGE_SIZE } from "./timeline-store.js";
|
|
3
3
|
/**
|
|
4
4
|
* `fetch_agent_timeline_request` handler (features/timeline-streaming.md § Fetch request/response,
|
|
@@ -19,18 +19,8 @@ export function registerTimelineHandler(registry, deps) {
|
|
|
19
19
|
const direction = msg.direction ?? "after";
|
|
20
20
|
const cursor = msg.cursor;
|
|
21
21
|
const limit = typeof msg.limit === "number" && msg.limit > 0 ? msg.limit : DEFAULT_PAGE_SIZE;
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
const record = deps.manager.get(agentId)?.record;
|
|
25
|
-
const handle = record?.persistence;
|
|
26
|
-
if (record && handle) {
|
|
27
|
-
const client = deps.resolveClient(record.provider);
|
|
28
|
-
const rows = client.hydrateTimeline?.(handle) ?? [];
|
|
29
|
-
if (rows.length > 0)
|
|
30
|
-
seedTimeline(agentId, rows);
|
|
31
|
-
}
|
|
32
|
-
timeline = getTimeline(agentId);
|
|
33
|
-
}
|
|
22
|
+
ensureTimelineSeeded(agentId, deps.manager, deps.resolveClient);
|
|
23
|
+
const timeline = getTimeline(agentId);
|
|
34
24
|
if (!timeline) {
|
|
35
25
|
// No in-memory timeline and no rehydratable native history — genuinely empty.
|
|
36
26
|
return {
|
package/dist/daemon/bootstrap.js
CHANGED
|
@@ -301,19 +301,6 @@ export function startDaemon(opts) {
|
|
|
301
301
|
requestId: ctx.requestId ?? "",
|
|
302
302
|
providers: providerRegistry.listMetadata(),
|
|
303
303
|
}));
|
|
304
|
-
// ── Provider model discovery (sprint-043: composer model selector) ──────────
|
|
305
|
-
registry.register("list_provider_models", async (ctx) => {
|
|
306
|
-
const provider = String(ctx.message.provider ?? "pi");
|
|
307
|
-
const cwd = ctx.message.cwd ? String(ctx.message.cwd) : undefined;
|
|
308
|
-
const client = resolveClient(provider);
|
|
309
|
-
const models = await client.listModels(cwd ? { cwd } : undefined);
|
|
310
|
-
return {
|
|
311
|
-
type: "list_provider_models_response",
|
|
312
|
-
requestId: ctx.requestId ?? "",
|
|
313
|
-
provider,
|
|
314
|
-
models,
|
|
315
|
-
};
|
|
316
|
-
});
|
|
317
304
|
const defaultModelCache = new Map();
|
|
318
305
|
// ── Default-model discovery (deferred-draft preselect: new chats show the model they'll
|
|
319
306
|
// actually run on before anything is spawned) ──────────────────────────────
|
|
@@ -198,19 +198,6 @@ export function startDevDaemon(opts) {
|
|
|
198
198
|
requestId: ctx.requestId ?? "",
|
|
199
199
|
providers: providerRegistry.listMetadata(),
|
|
200
200
|
}));
|
|
201
|
-
// ── Provider model discovery (sprint-043: composer model selector) ──────────
|
|
202
|
-
registry.register("list_provider_models", async (ctx) => {
|
|
203
|
-
const provider = String(ctx.message.provider ?? "pi");
|
|
204
|
-
const cwd = ctx.message.cwd ? String(ctx.message.cwd) : undefined;
|
|
205
|
-
const client = resolveClient(provider);
|
|
206
|
-
const models = await client.listModels(cwd ? { cwd } : undefined);
|
|
207
|
-
return {
|
|
208
|
-
type: "list_provider_models_response",
|
|
209
|
-
requestId: ctx.requestId ?? "",
|
|
210
|
-
provider,
|
|
211
|
-
models,
|
|
212
|
-
};
|
|
213
|
-
});
|
|
214
201
|
const defaultModelCache = new Map();
|
|
215
202
|
// ── Default-model discovery (deferred-draft preselect) ───────────────────
|
|
216
203
|
registry.register("resolve_default_model", async (ctx) => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@av-pi-studio/server",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.110",
|
|
4
4
|
"bin": {
|
|
5
5
|
"pi-studio-daemon": "dist/daemon/main.js"
|
|
6
6
|
},
|
|
@@ -24,8 +24,8 @@
|
|
|
24
24
|
"clean": "rm -rf dist *.tsbuildinfo"
|
|
25
25
|
},
|
|
26
26
|
"dependencies": {
|
|
27
|
-
"@av-pi-studio/protocol": "^0.0.
|
|
28
|
-
"@av-pi-studio/relay": "^0.0.
|
|
27
|
+
"@av-pi-studio/protocol": "^0.0.110",
|
|
28
|
+
"@av-pi-studio/relay": "^0.0.110",
|
|
29
29
|
"@earendil-works/pi-coding-agent": "^1.1.0",
|
|
30
30
|
"@xterm/addon-serialize": "^0.14.0",
|
|
31
31
|
"@xterm/headless": "^6.0.0",
|