@av-pi-studio/server 0.0.99 → 0.0.100

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.
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { AgentManager, PARENT_AGENT_ID_LABEL } from "./agent-manager.js";
2
+ import { AgentManager } from "./agent-manager.js";
3
3
  import { AgentTimelineStore } from "./timeline-store.js";
4
4
  import { composeSystemPrompt } from "./compose-system-prompt.js";
5
5
  /** In-memory timeline per agentId; persisted rows are on the AgentRecord.timeline. */
@@ -54,6 +54,16 @@ export async function spawnOrResumeSession(deps, agentId) {
54
54
  const modelProvider = record.config?.modelProvider;
55
55
  if (modelId && modelProvider)
56
56
  await session.setProviderModel?.(modelProvider, modelId);
57
+ // Replay the pinned thinking level strictly AFTER the model (sprint-070/task-003): Pi
58
+ // clamps thinking against the model, so a thinking-first replay would be silently
59
+ // overwritten by the model switch's own clamp. Skipped entirely when the record has no
60
+ // explicit pick — never clobber Pi's own restored/default level with a synthetic value.
61
+ // On RESUME the block does not run — Pi restores its own level from the session JSONL,
62
+ // exactly like the model, and with the clamp write-back (slash-command-operations.ts)
63
+ // config and JSONL cannot diverge, so the restored value already matches the record.
64
+ const thinking = record.config?.thinkingOptionId;
65
+ if (thinking)
66
+ await session.setThinkingOption?.(thinking);
57
67
  }
58
68
  deps.manager.attachSession(agentId, session);
59
69
  await deps.manager.persistSessionHandle(agentId);
@@ -113,7 +123,7 @@ export class AgentService {
113
123
  config: effectiveConfig,
114
124
  timeline: [],
115
125
  };
116
- const managed = await this.deps.manager.add(record);
126
+ await this.deps.manager.add(record);
117
127
  const agentId = record.id;
118
128
  this.broadcastAll(getSessions(), {
119
129
  type: "agent_update",
@@ -29,6 +29,17 @@ export interface AgentModelDefinition {
29
29
  * pi/<modelId>"): Pi has no model registered under a provider literally named "pi".
30
30
  */
31
31
  provider?: string;
32
+ /**
33
+ * Whether the model supports reasoning (Pi's `Model.reasoning`, sprint-070/task-001). Absent
34
+ * ⇒ non-reasoning. Feeds the web-client's draft thinking-level list without a live session.
35
+ */
36
+ reasoning?: boolean;
37
+ /**
38
+ * The thinking levels the model supports (Pi's `Model.thinkingLevelMap` derived via the Pi
39
+ * adapter's `deriveThinkingLevels`, sprint-070/task-001; `["off"]` for non-reasoning models).
40
+ * Absent ⇒ unknown; clients fall back to the full ladder and Pi clamps at apply time.
41
+ */
42
+ thinkingLevels?: string[];
32
43
  }
33
44
  export interface AgentModeDefinition {
34
45
  id: string;
@@ -101,6 +112,10 @@ export interface ProviderRuntimeInfo {
101
112
  sessionId?: string;
102
113
  model?: string;
103
114
  thinkingOptionId?: string;
115
+ /** Effective thinking level of a LIVE session (sprint-070/task-001) — what the provider is
116
+ * actually running with after Pi's own clamping, re-read from Pi `get_state` after every
117
+ * set/model-switch. Distinct from `thinkingOptionId` (the requested/pinned option id). */
118
+ thinkingLevel?: string;
104
119
  modeId?: string;
105
120
  extra?: Record<string, unknown>;
106
121
  }
@@ -195,6 +210,10 @@ export interface AgentSession {
195
210
  listCommands?(): Promise<AgentCommandDefinition[]>;
196
211
  setModel?(id: string): Promise<void>;
197
212
  setThinkingOption?(id: string): Promise<void>;
213
+ /** Available thinking levels for the session's CURRENT model (sprint-070/task-001) — Pi RPC
214
+ * `get_available_thinking_levels`, authoritative for a live process. Absent on providers
215
+ * without thinking support. */
216
+ listThinkingLevels?(): Promise<string[]>;
198
217
  setFeature?(id: string, value: unknown): Promise<void>;
199
218
  tryHandleOutOfBand?(message: unknown): boolean;
200
219
  /** `steer` — queue a message delivered after the current assistant turn's tool calls. */
@@ -274,6 +293,7 @@ export interface AgentClient {
274
293
  }): Promise<{
275
294
  provider?: string;
276
295
  model?: string;
296
+ thinkingLevel?: string;
277
297
  } | null>;
278
298
  /**
279
299
  * Rebuild a full timeline from a provider-native resume handle, without spawning a live
@@ -37,6 +37,7 @@ export declare class MockAgentSession implements AgentSession {
37
37
  private completionTimer;
38
38
  private mode;
39
39
  private closed;
40
+ private thinkingLevel;
40
41
  private readonly uiSubscribers;
41
42
  readonly uiResponses: {
42
43
  providerRequestId: string;
@@ -74,6 +75,10 @@ export declare class MockAgentSession implements AgentSession {
74
75
  getAvailableModes(): AgentModeDefinition[];
75
76
  getCurrentMode(): string | null;
76
77
  setMode(id: string): Promise<void>;
78
+ /** Sprint-070/task-001: store the level clamped to the mock's static list, mirroring Pi's
79
+ * silent clamping so the dev daemon exercises the same effective-level semantics. */
80
+ setThinkingOption(id: string): Promise<void>;
81
+ listThinkingLevels(): Promise<string[]>;
77
82
  getPendingPermissions(): PendingPermission[];
78
83
  respondToPermission(): Promise<void>;
79
84
  onUiRequest(cb: (req: ProviderUiRequest) => void): Unsubscribe;
@@ -152,6 +157,7 @@ export declare class MockAgentClient implements AgentClient {
152
157
  resolveDefaultModel(): Promise<{
153
158
  provider?: string;
154
159
  model?: string;
160
+ thinkingLevel?: string;
155
161
  } | null>;
156
162
  isAvailable(): boolean;
157
163
  importSession(args: {
@@ -19,6 +19,9 @@ const MOCK_MODES = [
19
19
  { id: "default", label: "Default" },
20
20
  { id: "plan", label: "Plan" },
21
21
  ];
22
+ /** Static thinking-level list for the mock provider (sprint-070/task-001) — small enough to
23
+ * exercise clamping in the dev daemon without mirroring Pi's full 7-level ladder. */
24
+ const MOCK_THINKING_LEVELS = ["off", "low", "medium", "high"];
22
25
  /** Exported so tests (this file's, and downstream sprint-066 task-003/004 daemon-level tests) can
23
26
  * cast a created session to reach `emitUiRequest`/`uiResponses`, which are deliberately not part
24
27
  * of the provider-neutral `AgentSession` contract. */
@@ -34,6 +37,7 @@ export class MockAgentSession {
34
37
  completionTimer = null;
35
38
  mode = "default";
36
39
  closed = false;
40
+ thinkingLevel = "off";
37
41
  // Extension UI (features/extension-ui-rpc.md, sprint-066): no `pi` process exists to script this
38
42
  // family, so the mock provider exposes a scripted emitter (`emitUiRequest`) plus a recorder for
39
43
  // `respondToUi` calls, letting tasks 003-004 drive/assert the whole family without a child process.
@@ -204,6 +208,7 @@ export class MockAgentSession {
204
208
  provider: this.provider,
205
209
  sessionId: this.id,
206
210
  model: this.config.model ?? "mock-model",
211
+ thinkingLevel: this.thinkingLevel,
207
212
  modeId: this.mode,
208
213
  extra: { cwd: this.config.cwd },
209
214
  };
@@ -218,6 +223,15 @@ export class MockAgentSession {
218
223
  this.mode = id;
219
224
  return Promise.resolve();
220
225
  }
226
+ /** Sprint-070/task-001: store the level clamped to the mock's static list, mirroring Pi's
227
+ * silent clamping so the dev daemon exercises the same effective-level semantics. */
228
+ setThinkingOption(id) {
229
+ this.thinkingLevel = MOCK_THINKING_LEVELS.includes(id) ? id : "off";
230
+ return Promise.resolve();
231
+ }
232
+ listThinkingLevels() {
233
+ return Promise.resolve([...MOCK_THINKING_LEVELS]);
234
+ }
221
235
  getPendingPermissions() {
222
236
  return [];
223
237
  }
@@ -295,10 +309,10 @@ export class MockAgentSession {
295
309
  return Promise.resolve();
296
310
  }
297
311
  cycleModel() {
298
- return Promise.resolve({ model: { id: "mock-model" }, thinkingLevel: "medium" });
312
+ return Promise.resolve({ model: { id: "mock-model" }, thinkingLevel: this.thinkingLevel });
299
313
  }
300
314
  getLastAssistantText() {
301
- const last = [...this.history].reverse().find((e) => e.kind === "assistant_message");
315
+ const last = [...this.history].toReversed().find((e) => e.kind === "assistant_message");
302
316
  return Promise.resolve(last && "text" in last ? last.text : null);
303
317
  }
304
318
  /** Command discovery (sprint-040): a deterministic, dependency-free multi-source list — one
@@ -360,13 +374,20 @@ export class MockAgentClient {
360
374
  return Promise.resolve(new MockAgentSession({ provider: "mock", cwd, model: "mock-model" }, this.options));
361
375
  }
362
376
  listModels() {
363
- return Promise.resolve([{ id: "mock-model", label: "Mock Model" }]);
377
+ return Promise.resolve([
378
+ {
379
+ id: "mock-model",
380
+ label: "Mock Model",
381
+ reasoning: true,
382
+ thinkingLevels: [...MOCK_THINKING_LEVELS],
383
+ },
384
+ ]);
364
385
  }
365
386
  listModes() {
366
387
  return Promise.resolve(MOCK_MODES);
367
388
  }
368
389
  resolveDefaultModel() {
369
- return Promise.resolve({ provider: "mock", model: "mock-model" });
390
+ return Promise.resolve({ provider: "mock", model: "mock-model", thinkingLevel: "off" });
370
391
  }
371
392
  isAvailable() {
372
393
  return true;
@@ -104,6 +104,7 @@ export declare class PiAgentClient implements AgentClient {
104
104
  }): Promise<{
105
105
  provider?: string;
106
106
  model?: string;
107
+ thinkingLevel?: string;
107
108
  } | null>;
108
109
  private topLevel;
109
110
  /** Enumerate Pi JSONL session files for the import picker (rows only). */
@@ -4,6 +4,7 @@ import { join } from "node:path";
4
4
  import { createPiEventMapper } from "./event-mapper.js";
5
5
  import { hydrateTimelineFromSessionFile } from "./session-hydration.js";
6
6
  import { createProcessTransport, defaultPiCommand, resolveBinaryOnPath, } from "./rpc-transport.js";
7
+ import { deriveThinkingLevels } from "./thinking-levels.js";
7
8
  /**
8
9
  * Pi provider adapter (features/agent-providers.md § Pi lifecycle / § Models·modes·features /
9
10
  * § Import & resume). Spawns `pi --mode rpc` (or a configured `command`), maps RPC events to
@@ -96,6 +97,7 @@ class PiAgentSession {
96
97
  mode;
97
98
  model;
98
99
  sessionFile;
100
+ thinkingLevel;
99
101
  constructor(transport, opts) {
100
102
  this.transport = transport;
101
103
  this.provider = opts.provider;
@@ -156,6 +158,11 @@ class PiAgentSession {
156
158
  const modelId = modelIdFrom(state.model);
157
159
  if (modelId)
158
160
  this.model = modelId;
161
+ // Pi's `get_state` also reports the process's current thinking level (docs/rpc.md §
162
+ // get_state) — capture it so `getRuntimeInfo()` reflects the live truth from the first
163
+ // create/resume, not only after an explicit set/model-switch.
164
+ if (typeof state.thinkingLevel === "string")
165
+ this.thinkingLevel = state.thinkingLevel;
159
166
  }
160
167
  catch {
161
168
  /* best-effort */
@@ -256,6 +263,7 @@ class PiAgentSession {
256
263
  sessionId: this.id,
257
264
  modeId: this.mode ?? undefined,
258
265
  model: this.model,
266
+ thinkingLevel: this.thinkingLevel,
259
267
  };
260
268
  }
261
269
  getAvailableModes() {
@@ -384,6 +392,12 @@ class PiAgentSession {
384
392
  const resolved = modelIdFrom(data);
385
393
  if (resolved)
386
394
  this.model = resolved;
395
+ // `set_model`'s response is the bare Model object and does NOT carry `thinkingLevel`, even
396
+ // though a model switch is exactly when Pi clamps the level (sprint-070/task-001; verified
397
+ // against the bundled Pi: only `cycle_model`'s response includes it). Re-read `get_state`
398
+ // so `getRuntimeInfo()` reports the post-switch effective level, never a stale pre-switch
399
+ // one. Best-effort like `discoverState`: a probe failure leaves the level as it was.
400
+ await this.refreshThinkingLevel();
387
401
  return data;
388
402
  }
389
403
  async cycleModel() {
@@ -391,8 +405,38 @@ class PiAgentSession {
391
405
  const resolved = modelIdFrom(data?.model);
392
406
  if (resolved)
393
407
  this.model = resolved;
408
+ // `cycle_model`'s response DOES carry the post-switch level — no extra probe needed.
409
+ if (typeof data?.thinkingLevel === "string")
410
+ this.thinkingLevel = data.thinkingLevel;
394
411
  return data ?? {};
395
412
  }
413
+ /**
414
+ * `set_thinking_level` (docs/rpc.md) — Pi clamps silently to the current model's
415
+ * capabilities and the response carries no data, so re-read `get_state` to learn the
416
+ * EFFECTIVE level (sprint-070/task-001). The daemon persists/broadcasts that effective
417
+ * value, never the requested one.
418
+ */
419
+ async setThinkingOption(id) {
420
+ await this.transport.request("set_thinking_level", { level: id });
421
+ await this.refreshThinkingLevel();
422
+ }
423
+ /** `get_available_thinking_levels` (docs/rpc.md) — authoritative levels for the process's
424
+ * current model (`["off"]` for non-reasoning models). */
425
+ async listThinkingLevels() {
426
+ const data = (await this.transport.request("get_available_thinking_levels"));
427
+ return Array.isArray(data?.levels) ? data.levels : [];
428
+ }
429
+ /** Re-read `get_state` and store `thinkingLevel` (the silent-clamping write-back probe). */
430
+ async refreshThinkingLevel() {
431
+ try {
432
+ const state = (await this.transport.request("get_state"));
433
+ if (typeof state.thinkingLevel === "string")
434
+ this.thinkingLevel = state.thinkingLevel;
435
+ }
436
+ catch {
437
+ /* best-effort */
438
+ }
439
+ }
396
440
  async getLastAssistantText() {
397
441
  const data = (await this.transport.request("get_last_assistant_text"));
398
442
  return data?.text ?? null;
@@ -520,6 +564,11 @@ export class PiAgentClient {
520
564
  id: String(rec.id ?? rec.name ?? ""),
521
565
  label: typeof rec.name === "string" ? rec.name : String(rec.id ?? ""),
522
566
  provider: typeof rec.provider === "string" ? rec.provider : undefined,
567
+ // Raw Pi `Model` objects carry `reasoning` + `thinkingLevelMap`; surface the derived
568
+ // per-model level list so clients can offer draft sessions the right levels with no
569
+ // live process (sprint-070/task-001).
570
+ reasoning: typeof rec.reasoning === "boolean" ? rec.reasoning : undefined,
571
+ thinkingLevels: deriveThinkingLevels(rec),
523
572
  };
524
573
  });
525
574
  }
@@ -545,6 +594,10 @@ export class PiAgentClient {
545
594
  return {
546
595
  provider: typeof rec.provider === "string" ? rec.provider : undefined,
547
596
  model: modelIdFrom(rec),
597
+ // The `--no-session get_state` also reports the fresh default thinking level
598
+ // (sprint-070/task-003) — carried through the daemon's cache into
599
+ // `resolve_default_model`'s response so a brand-new draft can show it.
600
+ thinkingLevel: typeof data?.thinkingLevel === "string" ? data.thinkingLevel : undefined,
548
601
  };
549
602
  }
550
603
  async topLevel(command, cwd, opts) {
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Per-model thinking-level derivation for the Pi provider (sprint-070/task-001).
3
+ *
4
+ * Mirrors `getSupportedThinkingLevels` from `@earendil-works/pi-ai` (bundled Pi's
5
+ * `node_modules/@earendil-works/pi-ai/dist/models.js`): `!reasoning → ["off"]`; otherwise
6
+ * filter the 7-level ladder by the `thinkingLevelMap` tristate — a `null` entry removes the
7
+ * level; `xhigh`/`max` are opt-in (require a non-null map entry); the remaining levels are
8
+ * included unless mapped to `null`.
9
+ *
10
+ * NOT importable by the daemon — pi-ai lives in `@earendil-works/pi-coding-agent`'s nested
11
+ * transitive dependencies — so the Pi adapter mirrors it here as a documented, unit-tested
12
+ * pure function. Any drift self-corrects at set time: Pi clamps authoritatively
13
+ * (`set_thinking_level` / model switch) and the daemon writes the EFFECTIVE level back
14
+ * (sprint-070/task-003), so this mirror only feeds the level lists a client offers, never
15
+ * the level actually applied.
16
+ *
17
+ * Raw Pi `Model` objects are untyped records at this layer, so the derivation tolerates
18
+ * absent/malformed `reasoning`/`thinkingLevelMap` (absent `reasoning` ⇒ non-reasoning,
19
+ * matching Pi's own `if (!model.reasoning)`).
20
+ */
21
+ /** Derive the thinking levels a raw Pi `Model` object supports (see module header). */
22
+ export declare function deriveThinkingLevels(model: unknown): string[];
23
+ //# sourceMappingURL=thinking-levels.d.ts.map
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Per-model thinking-level derivation for the Pi provider (sprint-070/task-001).
3
+ *
4
+ * Mirrors `getSupportedThinkingLevels` from `@earendil-works/pi-ai` (bundled Pi's
5
+ * `node_modules/@earendil-works/pi-ai/dist/models.js`): `!reasoning → ["off"]`; otherwise
6
+ * filter the 7-level ladder by the `thinkingLevelMap` tristate — a `null` entry removes the
7
+ * level; `xhigh`/`max` are opt-in (require a non-null map entry); the remaining levels are
8
+ * included unless mapped to `null`.
9
+ *
10
+ * NOT importable by the daemon — pi-ai lives in `@earendil-works/pi-coding-agent`'s nested
11
+ * transitive dependencies — so the Pi adapter mirrors it here as a documented, unit-tested
12
+ * pure function. Any drift self-corrects at set time: Pi clamps authoritatively
13
+ * (`set_thinking_level` / model switch) and the daemon writes the EFFECTIVE level back
14
+ * (sprint-070/task-003), so this mirror only feeds the level lists a client offers, never
15
+ * the level actually applied.
16
+ *
17
+ * Raw Pi `Model` objects are untyped records at this layer, so the derivation tolerates
18
+ * absent/malformed `reasoning`/`thinkingLevelMap` (absent `reasoning` ⇒ non-reasoning,
19
+ * matching Pi's own `if (!model.reasoning)`).
20
+ */
21
+ /** Pi's full thinking-level ladder (pi-ai `EXTENDED_THINKING_LEVELS`, models.js). Deliberately
22
+ * `string[]`, not a union — levels are dynamic per model/proxy (repo convention,
23
+ * `messages.ts`' agentSessionConfigSchema comment). */
24
+ const EXTENDED_THINKING_LEVELS = [
25
+ "off",
26
+ "minimal",
27
+ "low",
28
+ "medium",
29
+ "high",
30
+ "xhigh",
31
+ "max",
32
+ ];
33
+ /** Derive the thinking levels a raw Pi `Model` object supports (see module header). */
34
+ export function deriveThinkingLevels(model) {
35
+ const rec = (typeof model === "object" && model !== null ? model : {});
36
+ if (!rec.reasoning)
37
+ return ["off"];
38
+ const rawMap = rec.thinkingLevelMap;
39
+ const map = (typeof rawMap === "object" && rawMap !== null ? rawMap : undefined);
40
+ return EXTENDED_THINKING_LEVELS.filter((level) => {
41
+ const mapped = map?.[level];
42
+ if (mapped === null)
43
+ return false;
44
+ if (level === "xhigh" || level === "max")
45
+ return mapped !== undefined;
46
+ return true;
47
+ });
48
+ }
49
+ //# sourceMappingURL=thinking-levels.js.map
@@ -99,15 +99,26 @@ export class SessionOperationsService {
99
99
  ...msg.config,
100
100
  };
101
101
  // Apply mode/model/thinking to the live session (if attached).
102
+ let effectiveThinking;
102
103
  if (managed.session) {
103
104
  if (typeof msg.modeId === "string")
104
105
  await managed.session.setMode(msg.modeId);
105
106
  if (typeof msg.model === "string")
106
107
  await managed.session.setModel?.(msg.model);
107
108
  if (typeof msg.thinkingOptionId === "string") {
108
- await managed.session.setThinkingOption?.(msg.thinkingOptionId);
109
+ // Same apply-then-effective semantics as `agent_set_thinking_request`
110
+ // (sprint-070/task-003): apply, then persist/broadcast the EFFECTIVE level the
111
+ // provider reports (Pi clamps silently), never the requested one. A provider
112
+ // without `setThinkingOption` keeps the old pin-only behavior.
113
+ if (managed.session.setThinkingOption) {
114
+ await managed.session.setThinkingOption(msg.thinkingOptionId);
115
+ effectiveThinking =
116
+ managed.session.getRuntimeInfo().thinkingLevel ?? msg.thinkingOptionId;
117
+ }
109
118
  }
110
119
  }
120
+ if (effectiveThinking !== undefined)
121
+ config.thinkingOptionId = effectiveThinking;
111
122
  // Persist updated record without recreating the session — actually write it to disk
112
123
  // (`$PI_STUDIO_HOME/agents/**.json`), not just mutate the in-memory copy.
113
124
  await this.deps.manager.updateRecord(agentId, {
@@ -121,6 +132,7 @@ export class SessionOperationsService {
121
132
  status: managed.record.lastStatus,
122
133
  title,
123
134
  labels,
135
+ ...(effectiveThinking !== undefined ? { thinkingLevel: effectiveThinking } : {}),
124
136
  });
125
137
  return { type: "update_agent_response", agentId, ok: true };
126
138
  }
@@ -159,7 +171,7 @@ export class SessionOperationsService {
159
171
  timeline: result.timeline.map((e) => ({ epoch: 0, seq: 0, timestamp: this.now(), event: e })),
160
172
  persistence: result.persistence,
161
173
  };
162
- const managed = await this.deps.manager.add(record);
174
+ await this.deps.manager.add(record);
163
175
  this.deps.manager.attachSession(record.id, result.session);
164
176
  // Publish only once the agent is ready.
165
177
  this.broadcastAll(getSessions(), {
@@ -67,6 +67,14 @@ export declare class SlashCommandOperationsService {
67
67
  * written here, which is why a restored session's model selector came back with no known
68
68
  * provider even though `/model` had been set earlier in the same session. */
69
69
  private persistModel;
70
+ /** Persist the effective thinking level into the record's config (`config.thinkingOptionId`) so
71
+ * `list_agents_request` can surface it after a daemon restart / fresh connection / pick on a
72
+ * still-unspawned deferred draft, and `spawnOrResumeSession` can replay it on first spawn
73
+ * (sprint-070). Mirror of `persistModel` — one helper serves both the `agent_set_thinking`
74
+ * handler and (task-003) `update_agent_request`'s thinkingOptionId branch. The value stored is
75
+ * always the EFFECTIVE level (Pi clamps silently; the provider re-reads `get_state`), so the
76
+ * wire, the record, and the live process can never disagree. */
77
+ private persistThinking;
70
78
  /** `/model` (set) — broadcast the model change and persist it (see `persistModel`). A
71
79
  * materialized draft with no live process yet (`managed.session === null` — deferred-draft
72
80
  * creation, `agent-service.ts` `handleCreate`, defers the real spawn to first send) has no
@@ -82,6 +90,20 @@ export declare class SlashCommandOperationsService {
82
90
  * resolved id back off `getRuntimeInfo()` rather than the raw `cycleModel()` payload since the
83
91
  * provider (`providers/pi/agent.ts`) already normalizes it there via `modelIdFrom`. */
84
92
  handleCycleModel(msg: Record<string, unknown>, getSessions: () => Iterable<Session>): Promise<unknown>;
93
+ /** Thinking level (set) — sprint-070. Mirrors `handleSetModel`'s two-branch shape exactly: a
94
+ * materialized draft with no live process yet (`managed.session === null`) pins the requested
95
+ * level into the persisted config and broadcasts it, for `spawnOrResumeSession` to replay on
96
+ * first spawn (after the model — Pi clamps thinking against the model); routing drafts to
97
+ * `requireSession` was the exact silently-swallowed-pick bug sprint-043's corrections fixed
98
+ * for model. The live branch applies via `setThinkingOption`, then answers/persists/broadcasts
99
+ * the EFFECTIVE level read back off `getRuntimeInfo().thinkingLevel` (the provider re-reads
100
+ * Pi `get_state` after the set, since Pi clamps silently and the RPC response carries no
101
+ * data) — never the requested one. */
102
+ handleSetThinking(msg: Record<string, unknown>, getSessions: () => Iterable<Session>): Promise<unknown>;
103
+ /** Thinking levels (list) — sprint-070. Live sessions only: a draft's level list comes from
104
+ * the model catalogue client-side (features/thinking-level-selector.md § Level discovery), so
105
+ * a draft here is a legitimate `rpc_error`, not a silent empty list. */
106
+ handleThinkingLevels(msg: Record<string, unknown>): Promise<unknown>;
85
107
  /** `/copy` — read-only. */
86
108
  handleLastAssistantText(msg: Record<string, unknown>): Promise<unknown>;
87
109
  /**
@@ -31,6 +31,8 @@ export class SlashCommandOperationsService {
31
31
  registry.register("agent_cycle_model_request", (ctx) => this.handleCycleModel(ctx.message, getActiveSessions));
32
32
  registry.register("agent_last_assistant_text_request", (ctx) => this.handleLastAssistantText(ctx.message));
33
33
  registry.register("agent_list_commands_request", (ctx) => this.handleListCommands(ctx.message));
34
+ registry.register("agent_set_thinking_request", (ctx) => this.handleSetThinking(ctx.message, getActiveSessions));
35
+ registry.register("agent_thinking_levels_request", (ctx) => this.handleThinkingLevels(ctx.message));
34
36
  }
35
37
  broadcastAgentUpdate(getSessions, agentId, extra = {}) {
36
38
  this.deps.broadcast(getSessions(), { type: "agent_update", agentId, ...extra });
@@ -174,6 +176,22 @@ export class SlashCommandOperationsService {
174
176
  };
175
177
  await this.deps.manager.updateRecord(agentId, { config });
176
178
  }
179
+ /** Persist the effective thinking level into the record's config (`config.thinkingOptionId`) so
180
+ * `list_agents_request` can surface it after a daemon restart / fresh connection / pick on a
181
+ * still-unspawned deferred draft, and `spawnOrResumeSession` can replay it on first spawn
182
+ * (sprint-070). Mirror of `persistModel` — one helper serves both the `agent_set_thinking`
183
+ * handler and (task-003) `update_agent_request`'s thinkingOptionId branch. The value stored is
184
+ * always the EFFECTIVE level (Pi clamps silently; the provider re-reads `get_state`), so the
185
+ * wire, the record, and the live process can never disagree. */
186
+ async persistThinking(agentId, level) {
187
+ if (!level)
188
+ return;
189
+ const config = {
190
+ ...this.deps.manager.get(agentId)?.record.config,
191
+ thinkingOptionId: level,
192
+ };
193
+ await this.deps.manager.updateRecord(agentId, { config });
194
+ }
177
195
  /** `/model` (set) — broadcast the model change and persist it (see `persistModel`). A
178
196
  * materialized draft with no live process yet (`managed.session === null` — deferred-draft
179
197
  * creation, `agent-service.ts` `handleCreate`, defers the real spawn to first send) has no
@@ -202,7 +220,17 @@ export class SlashCommandOperationsService {
202
220
  throw unsupported(agentId, "set_model");
203
221
  const payload = await managed.session.setProviderModel(provider, modelId);
204
222
  await this.persistModel(agentId, modelId, provider);
205
- this.broadcastAgentUpdate(getSessions, agentId, { model: modelId, modelProvider: provider });
223
+ // A model switch can silently clamp the thinking level (Pi clamps against the new model);
224
+ // task-001's `setProviderModel` re-read `get_state`, so write back the EFFECTIVE level or
225
+ // the record goes stale and dead-session `list_agents` would lie (sprint-070/task-003).
226
+ const thinkingLevel = managed.session.getRuntimeInfo().thinkingLevel;
227
+ if (thinkingLevel !== undefined)
228
+ await this.persistThinking(agentId, thinkingLevel);
229
+ this.broadcastAgentUpdate(getSessions, agentId, {
230
+ model: modelId,
231
+ modelProvider: provider,
232
+ ...(thinkingLevel !== undefined ? { thinkingLevel } : {}),
233
+ });
206
234
  return { type: "agent_set_model_response", payload };
207
235
  }
208
236
  /** `/model` (cycle) — broadcast and persist the resulting model (see `persistModel`). Reads the
@@ -216,9 +244,59 @@ export class SlashCommandOperationsService {
216
244
  const payload = await session.cycleModel();
217
245
  const modelId = session.getRuntimeInfo().model;
218
246
  await this.persistModel(agentId, modelId);
219
- this.broadcastAgentUpdate(getSessions, agentId, modelId ? { model: modelId } : {});
247
+ const thinkingLevel = session.getRuntimeInfo().thinkingLevel;
248
+ if (thinkingLevel !== undefined)
249
+ await this.persistThinking(agentId, thinkingLevel);
250
+ this.broadcastAgentUpdate(getSessions, agentId, {
251
+ ...(modelId ? { model: modelId } : {}),
252
+ ...(thinkingLevel !== undefined ? { thinkingLevel } : {}),
253
+ });
220
254
  return { type: "agent_cycle_model_response", payload };
221
255
  }
256
+ /** Thinking level (set) — sprint-070. Mirrors `handleSetModel`'s two-branch shape exactly: a
257
+ * materialized draft with no live process yet (`managed.session === null`) pins the requested
258
+ * level into the persisted config and broadcasts it, for `spawnOrResumeSession` to replay on
259
+ * first spawn (after the model — Pi clamps thinking against the model); routing drafts to
260
+ * `requireSession` was the exact silently-swallowed-pick bug sprint-043's corrections fixed
261
+ * for model. The live branch applies via `setThinkingOption`, then answers/persists/broadcasts
262
+ * the EFFECTIVE level read back off `getRuntimeInfo().thinkingLevel` (the provider re-reads
263
+ * Pi `get_state` after the set, since Pi clamps silently and the RPC response carries no
264
+ * data) — never the requested one. */
265
+ async handleSetThinking(msg, getSessions) {
266
+ const agentId = msg.agentId;
267
+ const level = msg.level;
268
+ if (!level)
269
+ throw new Error("level is required");
270
+ const managed = this.deps.manager.get(agentId);
271
+ if (!managed)
272
+ throw new Error(`unknown agent: ${agentId}`);
273
+ if (!managed.session) {
274
+ await this.persistThinking(agentId, level);
275
+ this.broadcastAgentUpdate(getSessions, agentId, { thinkingLevel: level });
276
+ return {
277
+ type: "agent_set_thinking_response",
278
+ payload: { agentId, level },
279
+ };
280
+ }
281
+ if (!managed.session.setThinkingOption)
282
+ throw unsupported(agentId, "set_thinking_level");
283
+ await managed.session.setThinkingOption(level);
284
+ const effective = managed.session.getRuntimeInfo().thinkingLevel ?? level;
285
+ await this.persistThinking(agentId, effective);
286
+ this.broadcastAgentUpdate(getSessions, agentId, { thinkingLevel: effective });
287
+ return { type: "agent_set_thinking_response", payload: { agentId, level: effective } };
288
+ }
289
+ /** Thinking levels (list) — sprint-070. Live sessions only: a draft's level list comes from
290
+ * the model catalogue client-side (features/thinking-level-selector.md § Level discovery), so
291
+ * a draft here is a legitimate `rpc_error`, not a silent empty list. */
292
+ async handleThinkingLevels(msg) {
293
+ const agentId = msg.agentId;
294
+ const session = requireSession(this.deps.manager, agentId);
295
+ if (!session.listThinkingLevels)
296
+ throw unsupported(agentId, "get_available_thinking_levels");
297
+ const levels = await session.listThinkingLevels();
298
+ return { type: "agent_thinking_levels_response", payload: { agentId, levels } };
299
+ }
222
300
  /** `/copy` — read-only. */
223
301
  async handleLastAssistantText(msg) {
224
302
  const agentId = msg.agentId;
@@ -153,6 +153,17 @@ export function wrapSessionEnvelope(message) {
153
153
  return message;
154
154
  return { type: "session", message };
155
155
  }
156
+ const lastAssistantText = (agentId) => {
157
+ const rows = getTimeline(agentId)?.allRows() ?? [];
158
+ for (let i = rows.length - 1; i >= 0; i--) {
159
+ const ev = rows[i].event;
160
+ // Skip textless `final` block-close markers (`assistant_message.final`) — they carry no
161
+ // text and would otherwise mask the real last reply.
162
+ if (ev.kind === "assistant_message" && ev.text)
163
+ return ev.text;
164
+ }
165
+ return undefined;
166
+ };
156
167
  /**
157
168
  * Start the real production daemon. Returns a handle exposing the HTTP server, serverId, and a
158
169
  * `close()` for graceful shutdown.
@@ -254,6 +265,8 @@ export function startDaemon(opts) {
254
265
  provider: m.record.provider,
255
266
  model: m.session?.getRuntimeInfo().model ?? m.record.config?.model,
256
267
  modelProvider: m.record.config?.modelProvider,
268
+ // Live wins over pinned, same shape as `model` one line above (sprint-070/task-003).
269
+ thinkingLevel: m.session?.getRuntimeInfo().thinkingLevel ?? m.record.config?.thinkingOptionId,
257
270
  })),
258
271
  }));
259
272
  // ── Archive (soft delete) / delete (hard delete) — real remote deletion for clients ──────────
@@ -293,9 +306,9 @@ export function startDaemon(opts) {
293
306
  models,
294
307
  };
295
308
  });
309
+ const defaultModelCache = new Map();
296
310
  // ── Default-model discovery (deferred-draft preselect: new chats show the model they'll
297
311
  // actually run on before anything is spawned) ──────────────────────────────
298
- const defaultModelCache = new Map();
299
312
  registry.register("resolve_default_model", async (ctx) => {
300
313
  const provider = String(ctx.message.provider ?? "pi");
301
314
  const cwd = ctx.message.cwd ? String(ctx.message.cwd) : undefined;
@@ -314,6 +327,7 @@ export function startDaemon(opts) {
314
327
  provider,
315
328
  model: resolved?.model,
316
329
  modelProvider: resolved?.provider,
330
+ thinkingLevel: resolved?.thinkingLevel,
317
331
  };
318
332
  });
319
333
  // ── Projects / workspaces (real disk registry) ────────────────────────────────
@@ -496,17 +510,6 @@ export function startDaemon(opts) {
496
510
  };
497
511
  const scheduleService = new ScheduleService({ home, executor: scheduleExecutor });
498
512
  const chatService = new ChatService({ home });
499
- const lastAssistantText = (agentId) => {
500
- const rows = getTimeline(agentId)?.allRows() ?? [];
501
- for (let i = rows.length - 1; i >= 0; i--) {
502
- const ev = rows[i].event;
503
- // Skip textless `final` block-close markers (`assistant_message.final`) — they carry no
504
- // text and would otherwise mask the real last reply.
505
- if (ev.kind === "assistant_message" && ev.text)
506
- return ev.text;
507
- }
508
- return undefined;
509
- };
510
513
  const loopExecutor = {
511
514
  async runWorker({ provider, model, modeId, cwd, prompt }) {
512
515
  const res = (await agentService.handleCreate({
@@ -27,24 +27,23 @@ import { FileExplorerService } from "../files/file-explorer.js";
27
27
  import { MAX_INLINE_FILE_READ_BYTES } from "../files/limits.js";
28
28
  import { createDaemonLogger } from "../logging/logger.js";
29
29
  import { wrapSessionEnvelope } from "./bootstrap.js";
30
+ /** Broadcast helper — see `bootstrap.ts`'s `wrapSessionEnvelope` for the full rationale. */
31
+ function broadcast(sessions, message) {
32
+ const envelope = wrapSessionEnvelope(message);
33
+ for (const s of sessions) {
34
+ try {
35
+ s.send(envelope);
36
+ }
37
+ catch {
38
+ /* ignore send errors on dead sockets */
39
+ }
40
+ }
41
+ }
30
42
  export function startDevDaemon(opts) {
31
43
  const serverId = opts.serverId ?? randomUUID();
32
44
  const logger = opts.logger ?? createDaemonLogger(undefined);
33
- // ── Broadcast helper ─────────────────────────────────────────────────────────
34
- // See `bootstrap.ts`'s `wrapSessionEnvelope` for the full rationale.
35
- const broadcast = (sessions, message) => {
36
- const envelope = wrapSessionEnvelope(message);
37
- for (const s of sessions) {
38
- try {
39
- s.send(envelope);
40
- }
41
- catch {
42
- /* ignore send errors on dead sockets */
43
- }
44
- }
45
- };
46
- // Session set is created by the WS server below; handlers close over this
47
- // mutable holder so they can be registered before the WS server exists.
45
+ // Services receive `getActiveSessions` backed by the module-level `broadcast` (hoisted
46
+ // above) and a mutable holder so they can be registered before the WS server exists.
48
47
  const sessionsHolder = { sessions: [] };
49
48
  const getActiveSessions = () => sessionsHolder.sessions;
50
49
  // ── Extension UI bridge (features/extension-ui-rpc.md) — constructed before the manager so
@@ -111,6 +110,7 @@ export function startDevDaemon(opts) {
111
110
  provider: m.record.provider,
112
111
  model: m.session?.getRuntimeInfo().model ?? m.record.config?.model,
113
112
  modelProvider: m.record.config?.modelProvider,
113
+ thinkingLevel: m.session?.getRuntimeInfo().thinkingLevel ?? m.record.config?.thinkingOptionId,
114
114
  }));
115
115
  return {
116
116
  type: "list_agents_response",
@@ -191,8 +191,8 @@ export function startDevDaemon(opts) {
191
191
  models,
192
192
  };
193
193
  });
194
- // ── Default-model discovery (deferred-draft preselect) ───────────────────
195
194
  const defaultModelCache = new Map();
195
+ // ── Default-model discovery (deferred-draft preselect) ───────────────────
196
196
  registry.register("resolve_default_model", async (ctx) => {
197
197
  const provider = String(ctx.message.provider ?? "pi");
198
198
  const cwd = ctx.message.cwd ? String(ctx.message.cwd) : undefined;
@@ -211,6 +211,7 @@ export function startDevDaemon(opts) {
211
211
  provider,
212
212
  model: resolved?.model,
213
213
  modelProvider: resolved?.provider,
214
+ thinkingLevel: resolved?.thinkingLevel,
214
215
  };
215
216
  });
216
217
  // ── File explorer: real directory listing + file preview from disk ───────
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@av-pi-studio/server",
3
- "version": "0.0.99",
3
+ "version": "0.0.100",
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.99",
28
- "@av-pi-studio/protocol": "^0.0.99",
29
- "@av-pi-studio/relay": "^0.0.99",
27
+ "@av-pi-studio/highlight": "^0.0.100",
28
+ "@av-pi-studio/protocol": "^0.0.100",
29
+ "@av-pi-studio/relay": "^0.0.100",
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",