@nathanstephenson/flow 0.1.2 → 0.1.3

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.
@@ -158,6 +158,7 @@ class ClaudeSession {
158
158
  emit;
159
159
  stream;
160
160
  pump;
161
+ modelsReady;
161
162
  sdkSessionId = "";
162
163
  turnId;
163
164
  /** Set between asking the CLI for a compaction and the `result` that closes it. See `compact`. */
@@ -210,7 +211,7 @@ class ClaudeSession {
210
211
  this.parentWorkflow = workflowParentServer(options.tools === "none" ? undefined : options.workflow);
211
212
  this.options = options;
212
213
  this.backendOptions = backendOptions;
213
- this.workflowAutoCompaction = structuredClone(options.autoCompaction ?? {});
214
+ this.workflowAutoCompaction = structuredClone(options.autoCompaction);
214
215
  this.emit = options.emit;
215
216
  this.workflowGrants = new Set(options.standingAuthorisations ?? []);
216
217
  this.modelId = options.modelId;
@@ -227,7 +228,7 @@ class ClaudeSession {
227
228
  // pre-approved set. A Standing Authorisation is honoured in `canUseTool` instead, so that
228
229
  // `disallowedTools` — which an operator meant — still outranks a grant a human clicked.
229
230
  const startingEffort = sdkEffort(options.effort);
230
- const env = claudeAutoCompactionEnv(options.modelId ? this.workflowAutoCompaction[options.modelId] : undefined);
231
+ const env = claudeAutoCompactionEnv(this.workflowAutoCompaction);
231
232
  const queryOptions = {
232
233
  cwd: options.scope,
233
234
  ...(env ? { env } : {}),
@@ -276,7 +277,7 @@ class ClaudeSession {
276
277
  };
277
278
  this.stream = (backendOptions.query ?? query)({ prompt: this.inbox, options: queryOptions });
278
279
  this.pump = this.consume();
279
- void this.loadModels();
280
+ this.modelsReady = this.loadModels();
280
281
  // A meter that only fills once a turn ends reads as "no window" when it is really just early.
281
282
  // Occupancy is already meaningful here: system prompt, tools and memory files are loaded
282
283
  // before anything is sent.
@@ -960,10 +961,31 @@ export class ClaudeBackend {
960
961
  this.options = { ...options, ...(resolved ? { pathToClaudeCodeExecutable: resolved } : {}) };
961
962
  }
962
963
  async create(options) {
963
- // Deliberately not awaiting init: in streaming-input mode the SDK emits nothing until the
964
- // input stream yields, so waiting for the init message before returning would deadlock. The
965
- // session starts with provisional capabilities and emits capabilities_changed once known.
966
- return new ClaudeSession(options, this.options);
964
+ // Do not await the init message: streaming input yields none until the first prompt. The
965
+ // supportedModels control request does answer before that prompt, however. Returning while it
966
+ // is still in flight lets the first send race the empty provisional capabilities.
967
+ const session = new ClaudeSession(options, this.options);
968
+ let timer;
969
+ try {
970
+ await Promise.race([
971
+ session.modelsReady,
972
+ new Promise((_, reject) => {
973
+ timer = setTimeout(() => reject(new Error("Model capability discovery timed out")), 45_000);
974
+ }),
975
+ ]);
976
+ if (session.capabilities.models.length === 0) {
977
+ throw new Error("Claude model capabilities are unavailable; check the CLI and try again");
978
+ }
979
+ return session;
980
+ }
981
+ catch (error) {
982
+ await session.dispose();
983
+ throw error;
984
+ }
985
+ finally {
986
+ if (timer)
987
+ clearTimeout(timer);
988
+ }
967
989
  }
968
990
  }
969
991
  /** Claude reports one Provider, and per-model effort: haiku carries no supportedEffortLevels. */
@@ -26,7 +26,9 @@ export async function refreshClaudeMcp(stream, mcp, additional = {}) {
26
26
  break;
27
27
  await new Promise((resolve) => setTimeout(resolve, 25));
28
28
  }
29
- await stream.setMcpServers({});
29
+ // A failed external refresh must not remove the parent workflow controls. They are owned by
30
+ // this Backend Session, not by the external connection being retried.
31
+ await stream.setMcpServers(additional);
30
32
  throw new Error("MCP tools could not be registered");
31
33
  }
32
34
  export function claudeMcpServers(mcp) {
@@ -3,7 +3,10 @@ import { workflowInspectInput, workflowRecoverInput, workflowRelayInput, inspect
3
3
  export function workflowParentServer(parent) {
4
4
  if (!parent)
5
5
  return {};
6
- return { flow_workflow: createSdkMcpServer({ name: 'flow_workflow', tools: [
6
+ // The parent is woken with a request to call a specific relay tool. Newer Claude models
7
+ // defer MCP tools behind tool search by default, which can leave that tool unavailable
8
+ // in the relay turn. Keep these host-owned controls in the prompt from turn one.
9
+ return { flow_workflow: createSdkMcpServer({ name: 'flow_workflow', alwaysLoad: true, tools: [
7
10
  tool('workflow_inspect', inspectDescription, workflowInspectInput.shape, async (input) => ({ content: [{ type: 'text', text: JSON.stringify(await parent.inspect(input)) }] })),
8
11
  tool('workflow_recover', recoverDescription, workflowRecoverInput.shape, async (input, extra) => ({ content: [{ type: 'text', text: JSON.stringify(await parent.recover(input, extra?.signal)) }] })),
9
12
  tool('workflow_relay_enquiry', relayEnquiryDescription, workflowRelayInput.shape, async (input, extra) => ({ content: [{ type: 'text', text: JSON.stringify(await parent.relayEnquiry(input, extra?.signal)) }] })),
@@ -21,7 +21,7 @@ export class ClaudeWorkflowSubagent {
21
21
  launch;
22
22
  dependencies;
23
23
  autoCompaction;
24
- constructor(launch, options, grants, dependencies = {}, autoCompaction = {}) {
24
+ constructor(launch, options, grants, dependencies = {}, autoCompaction) {
25
25
  this.launch = launch;
26
26
  this.dependencies = dependencies;
27
27
  this.options = { ...options, input: structuredClone(options.input) };
@@ -105,7 +105,7 @@ export class ClaudeWorkflowSubagent {
105
105
  const skillContext = options.skill
106
106
  ? `You are workflow Subagent ${options.name}. The leading Skill invocation is expanded as the user prompt. Follow it together with the mapped workflow input below.\n\nMapped workflow input (JSON):\n${JSON.stringify(options.input)}\n\nWorkflow constraints:${options.instructions.slice(options.skill.invocation.length)}`
107
107
  : options.instructions;
108
- const compactionEnv = claudeAutoCompactionEnv(this.autoCompaction[options.modelId]) ?? process.env;
108
+ const compactionEnv = claudeAutoCompactionEnv(this.autoCompaction) ?? process.env;
109
109
  const stream = (this.dependencies.query ?? query)({ prompt: this.inbox, options: {
110
110
  ...this.launch, model: options.modelId,
111
111
  ...(options.effort === "off" ? {} : { effort: options.effort }),
@@ -1,8 +1,6 @@
1
- export function piAutoCompaction(settings, snapshot) {
1
+ export function piAutoCompaction(settings, setting) {
2
2
  const defaults = settings.getCompactionSettings();
3
3
  return (model) => {
4
- const id = model?.provider ? `${model.provider}/${model.id}` : model?.id;
5
- const setting = id ? snapshot[id] : undefined;
6
4
  const window = model?.contextWindow;
7
5
  const compaction = { ...defaults };
8
6
  if (setting?.mode === "disabled")
@@ -0,0 +1,38 @@
1
+ import { compact } from "@earendil-works/pi-coding-agent";
2
+ /** Keep Pi's preparation, split-turn handling, file tracking and usage accounting, changing only
3
+ * the model for its summary calls. External extensions remain disabled in Flow's Backend Sessions. */
4
+ export function compactionExtensionError(errors) {
5
+ return errors.find((entry) => entry.path === "<inline:flow-compaction-model>")?.error;
6
+ }
7
+ export function compactionModelExtension(modelId, notice) {
8
+ return { name: "flow-compaction-model", hidden: true, factory: (pi) => {
9
+ pi.on("session_before_compact", async (event, ctx) => {
10
+ try {
11
+ const model = ctx.modelRegistry.getAvailable().find((candidate) => `${candidate.provider}/${candidate.id}` === modelId);
12
+ if (!model)
13
+ throw new Error(`Configured compaction model “${modelId}” is unavailable`);
14
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
15
+ if (!auth.ok)
16
+ throw new Error(auth.error);
17
+ const requestModel = auth.baseUrl ? { ...model, baseUrl: auth.baseUrl } : model;
18
+ const headers = Object.fromEntries(Object.entries(auth.headers ?? {}).filter((entry) => entry[1] !== null));
19
+ const result = await compact(event.preparation, requestModel, auth.apiKey, headers, event.customInstructions, event.signal, "off", undefined, auth.env);
20
+ // Pi appends file-operation tags after generating the summary. Tags alone are not a
21
+ // usable checkpoint if the selected model answered with empty text.
22
+ const body = result.summary.replace(/<(read-files|modified-files)>[\s\S]*?<\/\1>/g, "").trim();
23
+ const prefix = body.split("**Turn Context (split turn):**")[1];
24
+ if (!body || (event.preparation.isSplitTurn && event.preparation.turnPrefixMessages.length > 0 && !prefix?.trim())) {
25
+ throw new Error("Compaction model returned an empty summary");
26
+ }
27
+ return { compaction: result };
28
+ }
29
+ catch (error) {
30
+ if (!event.signal.aborted)
31
+ notice(`Compaction with ${modelId} failed: ${error instanceof Error ? error.message : String(error)}. No other model was used.`);
32
+ // Errors in extension handlers are swallowed by Pi and fall back to its current model.
33
+ // Explicit cancellation instead protects the requested model choice.
34
+ return { cancel: true };
35
+ }
36
+ });
37
+ } };
38
+ }
@@ -6,6 +6,7 @@ import { PiWorkflowSubagent } from "./workflow-subagent.js";
6
6
  import { piEffortLevels } from "./effort-capabilities.js";
7
7
  import { clampEffort } from "../effort.js";
8
8
  import { piAutoCompaction } from "./auto-compaction.js";
9
+ import { compactionExtensionError, compactionModelExtension } from "./compaction-model.js";
9
10
  import { ASK_TOOL, PiEnquiries } from "./enquiries.js";
10
11
  import { backgroundTools } from "./background-calls.js";
11
12
  import { SUBAGENT_TOOL, subagentTool } from "./subagents.js";
@@ -18,8 +19,15 @@ export class PiSession {
18
19
  completions = [];
19
20
  workflows = new Map();
20
21
  mcp;
22
+ recreate;
21
23
  async refreshMcp() {
22
- this.session.agent.state.tools = [...this.session.agent.state.tools.filter((tool) => !tool.name.startsWith("mcp__")), ...piMcpTools(this.mcp)];
24
+ if (!this.recreate)
25
+ return;
26
+ const current = this.session;
27
+ this.unsubscribe();
28
+ current.dispose();
29
+ this.session = await this.recreate(current);
30
+ this.unsubscribe = this.session.subscribe((event) => this.translate(event));
23
31
  }
24
32
  standingAuthorisations;
25
33
  disposed = false;
@@ -28,6 +36,7 @@ export class PiSession {
28
36
  session;
29
37
  applyAutoCompaction;
30
38
  workflowAutoCompaction;
39
+ workflowCompactionModelId;
31
40
  emit;
32
41
  unsubscribe;
33
42
  sessionDir;
@@ -46,10 +55,12 @@ export class PiSession {
46
55
  currentMessageId;
47
56
  constructor(session, emit, sessionDir, support = {}) {
48
57
  this.mcp = support.mcp;
58
+ this.recreate = support.recreate;
49
59
  this.standingAuthorisations = [...(support.standingAuthorisations ?? [])];
50
60
  this.session = session;
51
61
  this.applyAutoCompaction = support.autoCompaction;
52
- this.workflowAutoCompaction = support.workflowAutoCompaction ?? {};
62
+ this.workflowAutoCompaction = support.workflowAutoCompaction;
63
+ this.workflowCompactionModelId = support.workflowCompactionModelId;
53
64
  this.applyAutoCompaction?.(session.model);
54
65
  this.emit = emit;
55
66
  this.sessionDir = sessionDir;
@@ -66,7 +77,7 @@ export class PiSession {
66
77
  throw new Error("Backend Session stopped");
67
78
  if (this.workflows.has(options.id))
68
79
  throw new Error(`Duplicate workflow Subagent: ${options.id}`);
69
- const handle = new PiWorkflowSubagent(this.session, options, this.standingAuthorisations, this.mcp, this.workflowAutoCompaction);
80
+ const handle = new PiWorkflowSubagent(this.session, options, this.standingAuthorisations, this.mcp, this.workflowAutoCompaction, this.workflowCompactionModelId);
70
81
  this.workflows.set(options.id, handle);
71
82
  void handle.done.finally(() => this.workflows.delete(options.id)).catch(() => { });
72
83
  return handle;
@@ -394,6 +405,7 @@ export class PiBackend {
394
405
  agentDir,
395
406
  settingsManager,
396
407
  noExtensions: true,
408
+ ...(options.compactionModelId ? { extensionFactories: [compactionModelExtension(options.compactionModelId, (text) => options.emit({ type: "notice", level: "error", text }))] } : {}),
397
409
  });
398
410
  await resourceLoader.reload();
399
411
  // Reviving reopens the most recent pi session in the directory we gave this Agent Session;
@@ -410,30 +422,39 @@ export class PiBackend {
410
422
  ])];
411
423
  const mcp = options.tools === "none" ? undefined : options.mcp;
412
424
  const workflowTools = workflowParentTools(options.tools === "none" ? undefined : options.workflow);
413
- tools.push(...workflowTools.map(tool => tool.name), ...piMcpTools(mcp).map((tool) => tool.name));
425
+ tools.push(...workflowTools.map(tool => tool.name));
414
426
  const enabled = (name) => tools.includes(name);
415
427
  const enquiries = enabled(ASK_TOOL) ? new PiEnquiries(options.emit) : undefined;
416
428
  const work = new PiWork(options.emit, (completion) => piSession.completed(completion));
417
429
  const subagents = enabled(SUBAGENT_TOOL);
418
430
  const customTools = [
419
431
  ...workflowTools,
420
- ...piMcpTools(mcp),
421
432
  ...backgroundTools(options.scope, settingsManager, work).filter((tool) => enabled(tool.name)),
422
433
  ...(enquiries ? [enquiries.tool] : []),
423
- ...(subagents ? [subagentTool(work, (id, input, signal) => runSubagent(session, options.scope, agentDir, work, id, input, signal, options.emit, mcp))] : []),
434
+ ...(subagents ? [subagentTool(work, (id, input, signal) => runSubagent(session, options.scope, agentDir, work, id, input, signal, options.emit, mcp, options.compactionModelId))] : []),
424
435
  ];
425
- const { session } = await createAgentSession({
426
- cwd: options.scope,
427
- agentDir,
428
- resourceLoader,
429
- settingsManager,
430
- customTools,
431
- tools,
432
- ...(sessionManager ? { sessionManager } : {}),
433
- ...(tools.length === 0 ? { noTools: "all" } : {}),
434
- });
435
- const autoCompaction = structuredClone(options.autoCompaction ?? {});
436
- const piSession = new PiSession(session, options.emit, sessionDir, { ...(mcp ? { mcp } : {}), work, subagents, standingAuthorisations: options.standingAuthorisations ?? [], autoCompaction: piAutoCompaction(settingsManager, autoCompaction), workflowAutoCompaction: autoCompaction, ...(enquiries ? { enquiries } : {}) });
436
+ const start = (current) => {
437
+ const mcpTools = piMcpTools(mcp);
438
+ return createAgentSession({
439
+ cwd: options.scope,
440
+ agentDir,
441
+ resourceLoader,
442
+ settingsManager,
443
+ customTools: [...customTools, ...mcpTools],
444
+ tools: [...tools, ...mcpTools.map((tool) => tool.name)],
445
+ ...(current ? { sessionManager: current.sessionManager, modelRuntime: current.modelRuntime, thinkingLevel: current.thinkingLevel, ...(current.model ? { model: current.model } : {}) }
446
+ : sessionManager ? { sessionManager } : {}),
447
+ ...(tools.length === 0 ? { noTools: "all" } : {}),
448
+ });
449
+ };
450
+ let { session, extensionsResult } = await start();
451
+ const extensionError = options.compactionModelId && compactionExtensionError(extensionsResult.errors);
452
+ if (extensionError) {
453
+ session.dispose();
454
+ throw new Error(`Could not load the Pi compaction model hook: ${extensionError}`);
455
+ }
456
+ const autoCompaction = structuredClone(options.autoCompaction);
457
+ const piSession = new PiSession(session, options.emit, sessionDir, { ...(mcp ? { mcp } : {}), work, subagents, standingAuthorisations: options.standingAuthorisations ?? [], autoCompaction: piAutoCompaction(settingsManager, autoCompaction), ...(autoCompaction ? { workflowAutoCompaction: autoCompaction } : {}), ...(options.compactionModelId ? { workflowCompactionModelId: options.compactionModelId } : {}), ...(enquiries ? { enquiries } : {}), ...(mcp ? { recreate: async (current) => (session = (await start(current)).session) } : {}) });
437
458
  if (options.modelId) {
438
459
  try {
439
460
  await piSession.setModel(options.modelId);
@@ -471,7 +492,7 @@ export class PiBackend {
471
492
  return piSession;
472
493
  }
473
494
  }
474
- async function runSubagent(parent, scope, agentDir, work, id, input, signal, emit, mcp) {
495
+ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emit, mcp, compactionModelId) {
475
496
  const available = parent.modelRuntime.getAvailableSnapshot();
476
497
  const model = input.model ? available.find((model) => describeModel(model).id === input.model) : parent.model;
477
498
  if (!model)
@@ -480,14 +501,20 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
480
501
  const tools = [...new Set([...parent.getActiveToolNames(), ...piMcpTools(mcp).map((tool) => tool.name)])].filter((name) => name !== ASK_TOOL && name !== SUBAGENT_TOOL && !name.startsWith("workflow_"));
481
502
  const settingsManager = SettingsManager.create(scope, agentDir);
482
503
  const resourceLoader = new DefaultResourceLoader({ cwd: scope, agentDir, settingsManager, noExtensions: true,
504
+ ...(compactionModelId ? { extensionFactories: [compactionModelExtension(compactionModelId, (text) => emit({ type: "notice", level: "error", text }))] } : {}),
483
505
  appendSystemPrompt: ["You are a Subagent. Complete the delegated work and return the result. If human input is needed, return that request to the parent. You cannot ask the human or create further Subagents."] });
484
506
  await resourceLoader.reload();
485
507
  signal.throwIfAborted();
486
508
  const producer = { subagentId: id };
487
- const { session: child } = await createAgentSession({ cwd: scope, agentDir, model, modelRuntime: parent.modelRuntime,
509
+ const { session: child, extensionsResult } = await createAgentSession({ cwd: scope, agentDir, model, modelRuntime: parent.modelRuntime,
488
510
  resourceLoader, settingsManager, sessionManager: SessionManager.inMemory(scope), tools,
489
511
  customTools: [...piMcpTools(mcp), ...backgroundTools(scope, settingsManager, work, producer, input.run_in_background === false).filter((tool) => tools.includes(tool.name))],
490
512
  });
513
+ const extensionError = compactionModelId && compactionExtensionError(extensionsResult.errors);
514
+ if (extensionError) {
515
+ child.dispose();
516
+ throw new Error(`Could not load the Pi compaction model hook: ${extensionError}`);
517
+ }
491
518
  let output = "";
492
519
  let failure;
493
520
  let reason = "complete";
@@ -28,7 +28,7 @@ export class PiWork {
28
28
  try {
29
29
  signal.throwIfAborted();
30
30
  const result = await execute(signal, (result) => { work.result = result; });
31
- return { brief, state: signal.aborted ? "aborted" : "complete", result };
31
+ return { brief, state: signal.aborted ? "aborted" : result.isError ? "error" : "complete", result };
32
32
  }
33
33
  catch (error) {
34
34
  return { brief, state: signal.aborted ? "aborted" : "error", result: textResult(error instanceof Error ? error.message : String(error)) };
@@ -3,6 +3,7 @@ import { createAgentSession, DefaultPackageManager, DefaultResourceLoader, getAg
3
3
  import { PiSession } from "./index.js";
4
4
  import { piAcceptsWorkflowEffort, piEffortLevels } from "./effort-capabilities.js";
5
5
  import { piAutoCompaction } from "./auto-compaction.js";
6
+ import { compactionExtensionError, compactionModelExtension } from "./compaction-model.js";
6
7
  import { PiEnquiries } from "./enquiries.js";
7
8
  import { backgroundTools } from "./background-calls.js";
8
9
  import { PiWork } from "./work.js";
@@ -16,11 +17,13 @@ export class PiWorkflowSubagent {
16
17
  permissions = new Map();
17
18
  options;
18
19
  autoCompaction;
20
+ compactionModelId;
19
21
  mcp;
20
- constructor(parent, options, grants, mcp, autoCompaction = {}) {
22
+ constructor(parent, options, grants, mcp, autoCompaction, compactionModelId) {
21
23
  this.mcp = mcp;
22
24
  this.options = { ...options, input: structuredClone(options.input) };
23
25
  this.autoCompaction = autoCompaction;
26
+ this.compactionModelId = compactionModelId;
24
27
  this.grants = new Set(grants);
25
28
  this.enquiries = new PiEnquiries((event) => this.emit(event));
26
29
  this.work = new PiWork((event) => this.emit(event), () => { });
@@ -95,6 +98,7 @@ export class PiWorkflowSubagent {
95
98
  }).resolve(async () => "skip") : undefined;
96
99
  const resourceLoader = new DefaultResourceLoader({ cwd: scope, agentDir: getAgentDir(), settingsManager,
97
100
  noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true,
101
+ ...(this.compactionModelId ? { extensionFactories: [compactionModelExtension(this.compactionModelId, (text) => this.emit({ type: "notice", level: "error", text }))] } : {}),
98
102
  additionalSkillPaths: resources?.skills.filter(resource => resource.enabled).map(resource => resource.path) ?? [],
99
103
  additionalPromptTemplatePaths: resources?.prompts.filter(resource => resource.enabled).map(resource => resource.path) ?? [],
100
104
  ...(options.skill ? {
@@ -136,10 +140,15 @@ export class PiWorkflowSubagent {
136
140
  ...backgroundTools(scope, settingsManager, this.work, undefined, false, true)];
137
141
  const customTools = definitions.filter((tool) => names.includes(tool.name)).map((tool) => this.wrap(tool));
138
142
  customTools.push(this.enquiries.tool);
139
- const { session } = await createAgentSession({ cwd: scope, model, modelRuntime: parent.modelRuntime,
143
+ const { session, extensionsResult } = await createAgentSession({ cwd: scope, model, modelRuntime: parent.modelRuntime,
140
144
  resourceLoader, settingsManager, sessionManager: SessionManager.inMemory(scope),
141
145
  tools: customTools.map((tool) => tool.name), customTools,
142
146
  });
147
+ const extensionError = this.compactionModelId && compactionExtensionError(extensionsResult.errors);
148
+ if (extensionError) {
149
+ session.dispose();
150
+ throw new Error(`Could not load the Pi compaction model hook: ${extensionError}`);
151
+ }
143
152
  // Session creation initializes SDK settings after resource loading, so apply the immutable
144
153
  // Flow policy at the same boundary PiSession uses for a parent model selection.
145
154
  piAutoCompaction(settingsManager, this.autoCompaction)(model);
package/dist/build-id CHANGED
@@ -1 +1 @@
1
- a05670ad-d8b7-4859-afde-7cc8ad2f6548
1
+ 3e073070-450d-4d29-9a8a-7645de508e01
@@ -883,7 +883,7 @@ async function bootstrap() {
883
883
  if (!managed) throw new Error("Missing systemd update configuration");
884
884
  await assertSystemdOwner(managed, managed.updater, process.pid);
885
885
  }
886
- const lease = await install.register("a05670ad-d8b7-4859-afde-7cc8ad2f6548", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
886
+ const lease = await install.register("3e073070-450d-4d29-9a8a-7645de508e01", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
887
887
  delete process.env.FLOW_UPDATE_CAPABILITY;
888
888
  process.on("exit", lease.release);
889
889
  if (args[0] === "update") {
@@ -84,7 +84,8 @@ export class ConfigStore {
84
84
  * method rather than the store itself, for the reason `retention` is one.
85
85
  */
86
86
  defaultModel = (backend) => this.config.providers?.defaults?.[backend];
87
- autoCompaction = (backend) => structuredClone(this.config.providers?.autoCompaction?.[backend] ?? {});
87
+ autoCompaction = (backend) => structuredClone(this.config.providers?.autoCompaction?.[backend]);
88
+ compactionModel = (backend) => this.config.providers?.compactionModels?.[backend];
88
89
  defaultBackend = () => this.config.providers?.defaultBackend;
89
90
  /** The Summary Model, asked fresh. Undefined means no Agent Session is named by a model. */
90
91
  summaryModel = (backend) => {
@@ -156,7 +156,7 @@ function parseProviders(parsed, warnings) {
156
156
  };
157
157
  }
158
158
  }
159
- for (const field of ["efforts", "summaries", "autoCompaction"]) {
159
+ for (const field of ["efforts", "summaries", "autoCompaction", "compactionModels"]) {
160
160
  const entries = section[field];
161
161
  if (entries === undefined)
162
162
  continue;
@@ -166,15 +166,24 @@ function parseProviders(parsed, warnings) {
166
166
  }
167
167
  for (const [backend, value] of Object.entries(entries)) {
168
168
  try {
169
- if (field === "autoCompaction" && typeof value === "object" && value !== null && !Array.isArray(value)) {
170
- for (const [model, setting] of Object.entries(value)) {
171
- try {
172
- providers = patchProviders(providers, { autoCompaction: { [backend]: { [model]: setting } } }) ?? {};
173
- }
174
- catch (error) {
175
- warnings.push(String(error));
169
+ if (field === "autoCompaction" && typeof value === "object" && value !== null && !Array.isArray(value) && !("mode" in value)) {
170
+ // Older files mapped each backend to models. Only promote identical entries: choosing
171
+ // one of several conflicting policies would silently impose it on other models.
172
+ const legacy = Object.entries(value);
173
+ if (!legacy.length)
174
+ continue;
175
+ const validated = legacy.map(([model, setting]) => {
176
+ const entry = patchProviders(undefined, { autoCompaction: { [backend]: setting } })?.autoCompaction?.[backend];
177
+ if (checkModelId(model, `providers.autoCompaction.${backend}.${model}`) || model !== model.trim() || !entry) {
178
+ throw new ConfigError(`Invalid legacy auto-compaction setting for ${backend}/${model}; using backend default`);
176
179
  }
180
+ return entry;
181
+ });
182
+ if (!validated.every((setting) => JSON.stringify(setting) === JSON.stringify(validated[0]))) {
183
+ warnings.push(`Conflicting legacy auto-compaction settings for ${backend}; using backend default`);
184
+ continue;
177
185
  }
186
+ providers = patchProviders(providers, { autoCompaction: { [backend]: validated[0] } }) ?? {};
178
187
  }
179
188
  else
180
189
  providers = patchProviders(providers, { [field]: { [backend]: value } }) ?? {};
@@ -404,9 +413,10 @@ export function applyPatch(current, patch) {
404
413
  function patchProviders(current, patch) {
405
414
  if (patch === undefined)
406
415
  return current;
407
- refuseUnknownKeys(patch, ["defaultBackend", "defaults", "summary", "efforts", "summaries", "autoCompaction"], "providers");
416
+ refuseUnknownKeys(patch, ["defaultBackend", "defaults", "summary", "efforts", "summaries", "autoCompaction", "compactionModels"], "providers");
408
417
  const next = {
409
418
  ...(current?.autoCompaction === undefined ? {} : { autoCompaction: { ...current.autoCompaction } }),
419
+ ...(current?.compactionModels === undefined ? {} : { compactionModels: { ...current.compactionModels } }),
410
420
  ...(current?.defaultBackend === undefined ? {} : { defaultBackend: current.defaultBackend }),
411
421
  ...(current?.efforts === undefined ? {} : { efforts: { ...current.efforts } }),
412
422
  ...(current?.summaries === undefined ? {} : { summaries: { ...current.summaries } }),
@@ -429,41 +439,54 @@ function patchProviders(current, patch) {
429
439
  throw new ConfigError("providers.autoCompaction must be an object");
430
440
  }
431
441
  const merged = { ...next.autoCompaction };
432
- for (const [backend, models] of Object.entries(entries)) {
433
- const path = `providers.autoCompaction.${backend}`;
434
- if (backend !== backend.trim() || checkModelId(backend, path) || typeof models !== "object" || models === null || Array.isArray(models)) {
435
- throw new ConfigError(`${path} must map model ids to auto-compaction settings`);
442
+ for (const [backend, value] of Object.entries(entries)) {
443
+ const field = `providers.autoCompaction.${backend}`;
444
+ if (backend !== backend.trim() || checkModelId(backend, field))
445
+ throw new ConfigError(`${field} must name a backend without surrounding whitespace`);
446
+ if (value === null) {
447
+ delete merged[backend];
448
+ continue;
436
449
  }
437
- const values = { ...merged[backend] };
438
- for (const [model, value] of Object.entries(models)) {
439
- const field = `${path}.${model}`;
440
- if (model !== model.trim() || checkModelId(model, field))
441
- throw new ConfigError(`${field} must name a model without surrounding whitespace`);
442
- if (value === null) {
443
- delete values[model];
444
- continue;
445
- }
446
- if (typeof value !== "object" || Array.isArray(value))
447
- throw new ConfigError(`${field} must be an auto-compaction setting`);
448
- refuseUnknownKeys(value, value.mode === "disabled" ? ["mode"] : ["mode", "targetPercent"], field);
449
- if (value.mode === "disabled")
450
- values[model] = { mode: "disabled" };
451
- else if (value.mode === "enabled" && Number.isInteger(value.targetPercent) && value.targetPercent >= 1 && value.targetPercent <= 99) {
452
- values[model] = { mode: "enabled", targetPercent: value.targetPercent };
453
- }
454
- else
455
- throw new ConfigError(`${field} must be disabled or enabled with an integer targetPercent from 1 to 99`);
450
+ if (typeof value !== "object" || Array.isArray(value))
451
+ throw new ConfigError(`${field} must be an auto-compaction setting`);
452
+ refuseUnknownKeys(value, value.mode === "disabled" ? ["mode"] : ["mode", "targetPercent"], field);
453
+ if (value.mode === "disabled")
454
+ merged[backend] = { mode: "disabled" };
455
+ else if (value.mode === "enabled" && Number.isInteger(value.targetPercent) && value.targetPercent >= 1 && value.targetPercent <= 99) {
456
+ merged[backend] = { mode: "enabled", targetPercent: value.targetPercent };
456
457
  }
457
- if (Object.keys(values).length)
458
- merged[backend] = values;
459
458
  else
460
- delete merged[backend];
459
+ throw new ConfigError(`${field} must be disabled or enabled with an integer targetPercent from 1 to 99`);
461
460
  }
462
461
  if (Object.keys(merged).length)
463
462
  next.autoCompaction = merged;
464
463
  else
465
464
  delete next.autoCompaction;
466
465
  }
466
+ if (patch.compactionModels !== undefined) {
467
+ const entries = patch.compactionModels;
468
+ if (typeof entries !== "object" || entries === null || Array.isArray(entries)) {
469
+ throw new ConfigError("providers.compactionModels must map a backend to a model id");
470
+ }
471
+ const merged = { ...next.compactionModels };
472
+ for (const [backend, modelId] of Object.entries(entries)) {
473
+ const field = `providers.compactionModels.${backend}`;
474
+ if (backend !== "pi")
475
+ throw new ConfigError(`${field} is supported only by Pi`);
476
+ if (modelId === "") {
477
+ delete merged[backend];
478
+ continue;
479
+ }
480
+ const problem = checkModelId(modelId, field);
481
+ if (problem || modelId !== modelId.trim())
482
+ throw new ConfigError(problem ?? `${field} must name a model without surrounding whitespace`);
483
+ merged[backend] = modelId;
484
+ }
485
+ if (Object.keys(merged).length)
486
+ next.compactionModels = merged;
487
+ else
488
+ delete next.compactionModels;
489
+ }
467
490
  const defaults = patch.defaults;
468
491
  if (defaults !== undefined) {
469
492
  if (typeof defaults !== "object" || defaults === null || Array.isArray(defaults)) {
@@ -202,6 +202,7 @@ export class SessionHost {
202
202
  defaultBackend;
203
203
  defaultModel;
204
204
  autoCompaction;
205
+ compactionModel;
205
206
  defaultEffort;
206
207
  summaryModel;
207
208
  closedListeners = new Set();
@@ -220,6 +221,7 @@ export class SessionHost {
220
221
  this.defaultBackend = options.defaultBackend;
221
222
  this.defaultModel = options.defaultModel;
222
223
  this.autoCompaction = options.autoCompaction;
224
+ this.compactionModel = options.compactionModel;
223
225
  this.defaultEffort = options.defaultEffort;
224
226
  this.summaryModel = options.summaryModel;
225
227
  }
@@ -586,7 +588,23 @@ export class SessionHost {
586
588
  this.sessions.set(id, record);
587
589
  this.persist(record);
588
590
  record.buffered = [];
589
- const session = await this.startBackendSession(record);
591
+ let session;
592
+ try {
593
+ session = await this.startBackendSession(record);
594
+ if (session.capabilities.models.length === 0) {
595
+ throw new CommandRefused("Model capabilities are unavailable. Check the backend and try again.");
596
+ }
597
+ }
598
+ catch (error) {
599
+ // Creation never returns an Agent Session without confirmed models. In particular, do not
600
+ // leave a persisted, empty Agent Session (or a newly cut worktree) after a failed probe.
601
+ await record.session?.dispose().catch(() => { });
602
+ await this.releaseWorktree(record);
603
+ record.log.closeSubscribers();
604
+ this.sessions.delete(id);
605
+ this.store?.deleteSession(id);
606
+ throw error;
607
+ }
590
608
  record.log.append({
591
609
  type: "session_started",
592
610
  backend: backend.name,
@@ -1842,6 +1860,8 @@ export class SessionHost {
1842
1860
  const mcp = new McpSession((this.mcpConnections?.() ?? []).filter((connection) => record.mcpConnectionIds?.includes(connection.id)), record.scope, this.mcpAuth ? (connection) => this.mcpAuth.provider(connection) : undefined, false, this.resolveSecret);
1843
1861
  record.mcp = mcp;
1844
1862
  const openingMcp = mcp.open();
1863
+ const autoCompaction = this.autoCompaction?.(backend.name);
1864
+ const compactionModelId = this.compactionModel?.(backend.name);
1845
1865
  const session = await backend.create({
1846
1866
  mcp,
1847
1867
  workflow: {
@@ -1856,7 +1876,8 @@ export class SessionHost {
1856
1876
  },
1857
1877
  scope: record.scope,
1858
1878
  emit: (event) => this.onBackendEvent(record.id, event),
1859
- ...(this.autoCompaction ? { autoCompaction: this.autoCompaction(backend.name) } : {}),
1879
+ ...(autoCompaction === undefined ? {} : { autoCompaction }),
1880
+ ...(compactionModelId === undefined ? {} : { compactionModelId }),
1860
1881
  ...(record.modelId === undefined ? {} : { modelId: record.modelId }),
1861
1882
  ...(record.effort === undefined ? {} : { effort: record.effort }),
1862
1883
  ...(record.resumeToken === undefined ? {} : { resume: record.resumeToken }),
@@ -35,7 +35,7 @@ export async function startRuntime(options) {
35
35
  mcpConnections: config.mcpConnections, mcpAuth,
36
36
  standingAuthorisations: config.standingAuthorisations, allowTool: config.allowTool,
37
37
  defaultBackend: config.defaultBackend, defaultModel: config.defaultModel,
38
- defaultEffort: config.defaultEffort, autoCompaction: config.autoCompaction, summaryModel: config.summaryModel,
38
+ defaultEffort: config.defaultEffort, autoCompaction: config.autoCompaction, compactionModel: config.compactionModel, summaryModel: config.summaryModel,
39
39
  });
40
40
  const shells = new ShellRegistry();
41
41
  let running;