@nathanstephenson/flow 0.1.1 → 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.
Files changed (32) hide show
  1. package/README.md +5 -2
  2. package/dist/backend/claude/index.js +29 -7
  3. package/dist/backend/claude/mcp.js +3 -1
  4. package/dist/backend/claude/workflow-parent.js +4 -1
  5. package/dist/backend/claude/workflow-subagent.js +2 -2
  6. package/dist/backend/pi/auto-compaction.js +1 -3
  7. package/dist/backend/pi/compaction-model.js +38 -0
  8. package/dist/backend/pi/index.js +47 -20
  9. package/dist/backend/pi/work.js +1 -1
  10. package/dist/backend/pi/workflow-subagent.js +11 -2
  11. package/dist/build-id +1 -1
  12. package/dist/cli/bootstrap.js +187 -36
  13. package/dist/cli/host-control.js +2 -2
  14. package/dist/cli/install-guard.js +5 -2
  15. package/dist/cli/systemd-update.js +129 -0
  16. package/dist/cli/update.js +36 -6
  17. package/dist/cli/web-update.js +22 -3
  18. package/dist/daemon/config-store.js +2 -1
  19. package/dist/daemon/config.js +58 -35
  20. package/dist/daemon/host-control-routes.js +18 -2
  21. package/dist/daemon/host.js +23 -2
  22. package/dist/daemon/runtime.js +1 -1
  23. package/dist/daemon/server.js +17 -1
  24. package/dist/daemon/workflow-executions.js +9 -2
  25. package/package.json +5 -4
  26. package/web/dist/assets/{index-CaJfF2tQ.js → index-BmX_AxCZ.js} +3 -3
  27. package/web/dist/assets/{settings-mcp-COi1p_1o.js → settings-mcp-CSLXJftV.js} +1 -1
  28. package/web/dist/assets/{settings-secrets-C599riFl.js → settings-secrets-DpEwZLL4.js} +1 -1
  29. package/web/dist/assets/{settings-workflows-BPjeFoaT.js → settings-workflows-Dt-GaRtX.js} +1 -1
  30. package/web/dist/assets/{workflows-Bmsrl5kE.js → workflows-DDRfFnAE.js} +1 -1
  31. package/web/dist/assets/{workflows-pane-DJ3UwHjd.js → workflows-pane-g5njqean.js} +1 -1
  32. package/web/dist/index.html +1 -1
package/README.md CHANGED
@@ -60,7 +60,7 @@ do not tag a version until its license and release contents are approved.
60
60
  ## Updating Flow
61
61
 
62
62
  Run `flow update` to install `@nathanstephenson/flow@latest` with the npm selected by PATH.
63
- An authorised browser connected to a background Session Host can perform the same guarded operation
63
+ An authorised browser connected to a background or configured systemd-owned Session Host can perform the same guarded operation
64
64
  from **Settings → General → Flow update** after explicit confirmation. The browser checks only npm's
65
65
  stable `latest` tag, cannot select a package/version/path or force active work to stop, and reconnects
66
66
  on the same address and port to verify the running version. Updates are never automatic.
@@ -73,7 +73,10 @@ installations manually with npm after stopping all Flow processes.
73
73
  Close all CLI/TUI clients and stop other Session Hosts that use this installation, including those
74
74
  under other `FLOW_STATE_DIR` roots. The selected root's background Session Host can stay running:
75
75
  Flow stops it, updates, and restores its saved address, port, working directory and OIDC settings
76
- with a new process. Use `--force` to interrupt active work. Foreground and embedded hosts are refused.
76
+ with a new process. Use `--force` to interrupt active work. Unmanaged foreground and embedded hosts are refused.
77
+ For foreground systemd services (including system units with `User=agent`), see
78
+ [systemd update setup](docs/systemd-updates.md): a separate non-root updater unit retains service ownership
79
+ and needs only narrowly scoped start/stop authority configured once by an administrator.
77
80
  The same OIDC configuration must be present when you update. No version argument is accepted.
78
81
 
79
82
  Before first adopting this release, stop **all** older Flow processes. Old processes have no
@@ -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
- ca236dea-ce0d-4f67-8bb5-ca21105f393d
1
+ 3e073070-450d-4d29-9a8a-7645de508e01