@cortex-agent/server 2026.9.21 → 2026.9.25

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 (139) hide show
  1. package/defaults/config/thread-templates/agents/creative.json +17 -0
  2. package/defaults/prompts/systemPrompts/creative.md +13 -0
  3. package/defaults/prompts/systemPrompts/direct.md +1 -1
  4. package/dist/agent-adapter/claude/adapter.d.ts +12 -0
  5. package/dist/agent-adapter/claude/adapter.js +19 -1
  6. package/dist/agent-adapter/claude/spawn-args.d.ts +7 -0
  7. package/dist/agent-adapter/claude/spawn-args.js +10 -0
  8. package/dist/agent-adapter/pi/child-runner.d.ts +4 -2
  9. package/dist/agent-adapter/pi/child-runner.js +5 -1
  10. package/dist/agent-adapter/pi/event-parser.d.ts +3 -2
  11. package/dist/agent-adapter/pi/event-parser.js +46 -2
  12. package/dist/agent-adapter/pi/extensions.d.ts +7 -1
  13. package/dist/agent-adapter/pi/extensions.js +10 -3
  14. package/dist/agent-adapter/pi/mcp-bridge.js +8 -8
  15. package/dist/agent-adapter/pi/pi-session.js +5 -0
  16. package/dist/agent-adapter/pi/runtime.js +3 -0
  17. package/dist/agent-adapter/pi/session-options.js +5 -1
  18. package/dist/agent-adapter/pi/subagent.d.ts +15 -3
  19. package/dist/agent-adapter/pi/subagent.js +18 -0
  20. package/dist/agent-adapter/pi/tool-shims.d.ts +6 -1
  21. package/dist/agent-adapter/pi/tool-shims.js +34 -1
  22. package/dist/agent-adapter/types.d.ts +5 -0
  23. package/dist/core/agents/subagent/types.d.ts +3 -0
  24. package/dist/core/config-generator.js +17 -2
  25. package/dist/core/debug-mode.d.ts +11 -10
  26. package/dist/core/debug-mode.js +12 -18
  27. package/dist/core/exec-async.d.ts +26 -0
  28. package/dist/core/exec-async.js +47 -0
  29. package/dist/core/locales/en.d.ts +14 -1
  30. package/dist/core/locales/slices/commands.d.ts +12 -1
  31. package/dist/core/locales/slices/commands.js +24 -2
  32. package/dist/core/locales/slices/startup.d.ts +2 -0
  33. package/dist/core/locales/slices/startup.js +4 -0
  34. package/dist/core/rebuild-progress.d.ts +58 -0
  35. package/dist/core/rebuild-progress.js +103 -0
  36. package/dist/core/resilient-watch.js +5 -3
  37. package/dist/core/run-registry.d.ts +7 -0
  38. package/dist/core/run-registry.js +6 -0
  39. package/dist/core/types/thread-types.d.ts +23 -4
  40. package/dist/domain/agents/agent-state.d.ts +7 -0
  41. package/dist/domain/agents/agent-state.js +9 -1
  42. package/dist/domain/agents/agent-switch.d.ts +38 -0
  43. package/dist/domain/agents/agent-switch.js +106 -0
  44. package/dist/domain/agents/config.d.ts +20 -2
  45. package/dist/domain/agents/config.js +58 -4
  46. package/dist/domain/agents/index.d.ts +1 -0
  47. package/dist/domain/agents/index.js +1 -0
  48. package/dist/domain/agents/profile-manager.d.ts +6 -0
  49. package/dist/domain/agents/profile-manager.js +14 -1
  50. package/dist/domain/executions/registry.d.ts +2 -0
  51. package/dist/domain/executions/registry.js +84 -7
  52. package/dist/domain/plugins/runtime.js +1 -1
  53. package/dist/domain/plugins/skill-projection.d.ts +8 -2
  54. package/dist/domain/plugins/skill-projection.js +76 -19
  55. package/dist/domain/remote/client-bootstrap.js +1 -1
  56. package/dist/domain/remote/client-hot-reload.d.ts +1 -1
  57. package/dist/domain/remote/client-hot-reload.js +27 -23
  58. package/dist/domain/runs/engine-spec.js +4 -0
  59. package/dist/domain/runs/request.d.ts +6 -0
  60. package/dist/domain/runs/run.js +1 -0
  61. package/dist/domain/runs/spec-loader.d.ts +4 -3
  62. package/dist/domain/runs/spec-loader.js +4 -3
  63. package/dist/domain/scheduling/jobs/sync-public.js +6 -6
  64. package/dist/domain/scheduling/scheduler.js +14 -12
  65. package/dist/domain/sessions/session-lifecycle.d.ts +5 -0
  66. package/dist/domain/sessions/session-lifecycle.js +13 -1
  67. package/dist/domain/system/rebuild-hold.d.ts +44 -0
  68. package/dist/domain/system/rebuild-hold.js +91 -0
  69. package/dist/domain/system/server-update-check.d.ts +2 -1
  70. package/dist/domain/system/server-update-check.js +15 -13
  71. package/dist/domain/tasks/archiver.js +21 -13
  72. package/dist/domain/tasks/mutator.js +60 -59
  73. package/dist/domain/tasks/system/task-completion.d.ts +7 -2
  74. package/dist/domain/tasks/system/task-completion.js +69 -6
  75. package/dist/domain/tasks/system/task-lifecycle-edit.d.ts +6 -1
  76. package/dist/domain/tasks/system/task-lifecycle-edit.js +21 -2
  77. package/dist/domain/tasks/system/task-lock.d.ts +23 -0
  78. package/dist/domain/tasks/system/task-lock.js +29 -1
  79. package/dist/domain/tasks/system/task-mutations.d.ts +14 -1
  80. package/dist/domain/tasks/system/task-mutations.js +25 -2
  81. package/dist/domain/tasks/system/task-state.d.ts +12 -1
  82. package/dist/domain/tasks/system/task-state.js +19 -2
  83. package/dist/domain/threads/prompt-builder.d.ts +9 -6
  84. package/dist/domain/threads/prompt-builder.js +28 -10
  85. package/dist/domain/threads/runner.js +7 -3
  86. package/dist/domain/threads/state-machine.js +15 -11
  87. package/dist/domain/threads/template-loader.js +6 -4
  88. package/dist/domain/threads/template-validate.d.ts +43 -6
  89. package/dist/domain/threads/template-validate.js +12 -0
  90. package/dist/domain/ui-service/app-router.d.ts +10 -0
  91. package/dist/domain/ui-service/app-router.js +2 -1
  92. package/dist/domain/ui-service/input-schemas.d.ts +11 -0
  93. package/dist/domain/ui-service/input-schemas.js +11 -0
  94. package/dist/domain/ui-service/mutate/sessions.d.ts +2 -1
  95. package/dist/domain/ui-service/mutate/sessions.js +40 -0
  96. package/dist/domain/ui-service/mutate/tasks.js +4 -3
  97. package/dist/domain/ui-service/query/config.js +19 -1
  98. package/dist/domain/ui-service/query/memory.js +28 -34
  99. package/dist/domain/ui-service/query/sessions.js +89 -12
  100. package/dist/domain/ui-service/query/system.js +19 -0
  101. package/dist/domain/ui-service/query-input-schemas.d.ts +1 -0
  102. package/dist/domain/ui-service/query-input-schemas.js +2 -0
  103. package/dist/domain/ui-service/types.d.ts +97 -3
  104. package/dist/domain/ui-service/ui-service.js +2 -1
  105. package/dist/entry/app.js +23 -4
  106. package/dist/entry/daemon-notice.d.ts +10 -1
  107. package/dist/entry/daemon-notice.js +16 -1
  108. package/dist/entry/daemon.d.ts +43 -2
  109. package/dist/entry/daemon.js +163 -9
  110. package/dist/orchestration/agent-runner.js +16 -0
  111. package/dist/orchestration/conversation-request.d.ts +33 -0
  112. package/dist/orchestration/conversation-request.js +78 -16
  113. package/dist/orchestration/mid-turn-inject.d.ts +3 -0
  114. package/dist/orchestration/mid-turn-inject.js +9 -4
  115. package/dist/orchestration/resume-dispatcher.js +4 -2
  116. package/dist/orchestration/routing/commands/mode.js +114 -63
  117. package/dist/orchestration/thread-executor.js +13 -0
  118. package/dist/orchestration/turn/turn.js +1 -0
  119. package/dist/store/conversation-display-projection.d.ts +9 -1
  120. package/dist/store/conversation-display-projection.js +13 -6
  121. package/dist/store/conversation-history-reader.d.ts +19 -0
  122. package/dist/store/conversation-history-reader.js +163 -44
  123. package/dist/store/conversation-history-repo.d.ts +37 -10
  124. package/dist/store/conversation-history-repo.js +161 -139
  125. package/dist/store/session-registry-journal.d.ts +4 -0
  126. package/dist/store/session-registry-journal.js +4 -0
  127. package/dist/store/session-registry-repo.d.ts +2 -1
  128. package/dist/store/session-registry-repo.js +2 -0
  129. package/dist/store/task-repo.d.ts +6 -3
  130. package/dist/store/task-repo.js +26 -10
  131. package/package.json +2 -1
  132. package/web/dist/AGENTS.md +10 -0
  133. package/web/dist/assets/index-B1dBi8Za.css +1 -0
  134. package/web/dist/assets/{index-DZTuqUO4.js → index-BAeLybF0.js} +1 -1
  135. package/web/dist/assets/index-BcQI8Fh5.js +445 -0
  136. package/web/dist/index.html +12 -4
  137. package/web/dist/theme.css +211 -40
  138. package/web/dist/assets/index-CwwQNMpP.css +0 -1
  139. package/web/dist/assets/index-DLSfgq3o.js +0 -444
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "creative",
3
+ "description": "Clean-room creative environment: writing, image prompts, naming, copy. No skills, no project rules, minimal tools.",
4
+ "profile": "__active__",
5
+ "persistSession": true,
6
+ "promptTemplate": "{{input}}",
7
+ "systemPrompt": "file:creative.md",
8
+ "tools": "Read,Write,Edit",
9
+ "pluginDirs": [],
10
+ "skills": false,
11
+ "settingSources": [],
12
+ "mcpComposition": "direct",
13
+ "mcpToolAllowlist": ["send_file", "send_view", "cortex_ask_user"],
14
+ "loadRules": false,
15
+ "disableHooks": true,
16
+ "projectContext": false
17
+ }
@@ -0,0 +1,13 @@
1
+ You write. Every request is a piece of work in some form — a scene, a poem, lyrics, an image prompt, a name, a tagline, a character sketch — and the job is to make that piece well, in that form.
2
+
3
+ Start from the form. Each one carries its own rules: line breaks and sound in a poem, a turn in a short story, dense visual nouns in an image prompt, stress and rhythm in a lyric, the single reading a tagline has to survive. Know the genre the request is working in, then honour its conventions or break them on purpose. When the user names reference material — a file, a path, an earlier draft — read it with Read before writing.
4
+
5
+ Deliver the work and nothing else. No preamble, no "Here's a…", no note on what you were going for, no summary of what you just wrote, no closing line about how the reader might feel or what they could do next. If the piece wants a title it gets a title; otherwise it starts at its first word.
6
+
7
+ Write against the machine house style. Drop hedging openers — "I'd say", "it's worth noting", "certainly". No bullet lists unless the form itself is a list. Vary sentence length; three medium sentences in a row is a drone. Reach for the concrete noun over the abstraction: the chipped enamel mug, not a sense of domesticity. Cut stock transitions, symmetrical clause pairs, and the sentence at the end that tells the reader what to feel. Specific beats impressive.
8
+
9
+ Ask a question only when you genuinely cannot start — a missing fact that would change the whole piece. Otherwise make the call, write it, and let the draft carry the question.
10
+
11
+ Take feedback literally. "Shorter" means shorter, not restructured. "Colder" means colder, not more restrained and professional. Change what was named and leave the rest alone unless a rewrite is what was asked for.
12
+
13
+ Write in the language the user writes in, unless the request or the form calls for another. Write in the conversation. Save to a file only when the user asks for a file.
@@ -1,6 +1,6 @@
1
1
  You are Cortex, an AI assistant that helps users with research, software engineering, and project work. Understand the request, then act.
2
2
 
3
- Be concise and direct. Use formatting that makes the answer easy to read, and show file paths clearly.
3
+ For engineering and Q&A answers, be concise and direct; for creative deliverables, follow the requested form. Use formatting that makes the answer easy to read, and show file paths clearly.
4
4
 
5
5
  Read relevant files before changing them. Keep changes focused on the request, verify the result, and report what was and was not checked. Be explicit about uncertainty; do not invent facts, sources, or results.
6
6
 
@@ -37,6 +37,10 @@ interface ClaudeSessionOptions {
37
37
  browserMcpConfigIdentity?: string | null;
38
38
  pluginCapabilityFingerprint?: string | null;
39
39
  disableHooks?: boolean;
40
+ /** Drop the CLI's whole skill layer; see {@link ClaudeSpawnOptions.disableSkills}. */
41
+ disableSkills?: boolean;
42
+ /** Setting files the CLI may load; see {@link ClaudeSpawnOptions.settingSources}. */
43
+ settingSources?: string[];
40
44
  streamDeltas?: boolean;
41
45
  captureTranscriptLogs?: boolean;
42
46
  preserveUnreportedAccounting?: boolean;
@@ -74,6 +78,12 @@ export interface ClaudeSpawnCompatibility {
74
78
  /** Turning the browser on or off must force a FRESH process: a pooled Claude keeps whatever MCP
75
79
  * set it was spawned with, so without this the toggle would silently no-op until the process died. */
76
80
  browserMcpConfigIdentity: string | null;
81
+ /** `--disable-slash-commands`. Part of the identity for the same reason as the browser: the skill
82
+ * surface is fixed at spawn, so two agents that differ only here must not share a process. */
83
+ disableSkills: boolean;
84
+ /** `--setting-sources`. Null = the CLI's own default set; `[]` = load none. Both are decided at
85
+ * spawn and cannot be re-pointed afterwards. */
86
+ settingSources: string[] | null;
77
87
  }
78
88
  export declare function sameClaudeSpawnCompatibility(left: ClaudeSpawnCompatibility, right: ClaudeSpawnCompatibility): boolean;
79
89
  /**
@@ -115,6 +125,8 @@ declare class ClaudeSession implements TurnHost {
115
125
  private browserMcpConfigPath;
116
126
  private compatibility;
117
127
  private disableHooks;
128
+ private disableSkills;
129
+ private settingSources;
118
130
  private streamDeltas;
119
131
  captureTranscriptLogs: boolean;
120
132
  preserveUnreportedAccounting: boolean;
@@ -50,6 +50,8 @@ function deriveClaudeSpawnOptions(fields) {
50
50
  supplementalMcpConfigPath: fields.supplementalMcpConfigPath,
51
51
  browserMcpConfigPath: fields.browserMcpConfigPath,
52
52
  disableHooks: fields.disableHooks,
53
+ disableSkills: fields.disableSkills,
54
+ settingSources: fields.settingSources,
53
55
  streamDeltas: fields.streamDeltas,
54
56
  };
55
57
  }
@@ -76,9 +78,11 @@ export function sameClaudeSpawnCompatibility(left, right) {
76
78
  && left.pluginCapabilityFingerprint === right.pluginCapabilityFingerprint
77
79
  && left.supplementalMcpConfigIdentity === right.supplementalMcpConfigIdentity
78
80
  && left.browserMcpConfigIdentity === right.browserMcpConfigIdentity
81
+ && left.disableSkills === right.disableSkills
79
82
  && sameTextArray(left.pluginDirs, right.pluginDirs)
80
83
  && sameTextArray(left.mcpConfigPaths, right.mcpConfigPaths)
81
- && sameOptionalTextArray(left.mcpToolAllowlist, right.mcpToolAllowlist);
84
+ && sameOptionalTextArray(left.mcpToolAllowlist, right.mcpToolAllowlist)
85
+ && sameOptionalTextArray(left.settingSources, right.settingSources);
82
86
  }
83
87
  function compatibilityFromOptions(options) {
84
88
  const composition = resolveMcpComposition(options.mcpComposition, options.context?.useCoreMcp);
@@ -94,6 +98,8 @@ function compatibilityFromOptions(options) {
94
98
  mcpToolAllowlist: optionalTextArray(options.mcpToolAllowlist),
95
99
  supplementalMcpConfigIdentity: options.supplementalMcpConfigIdentity ?? null,
96
100
  browserMcpConfigIdentity: options.browserMcpConfigIdentity ?? null,
101
+ disableSkills: options.disableSkills === true,
102
+ settingSources: optionalTextArray(options.settingSources),
97
103
  };
98
104
  }
99
105
  /**
@@ -114,9 +120,11 @@ export function claudeCompatibilityIdentity(compatibility) {
114
120
  ['pluginCapabilityFingerprint', compatibility.pluginCapabilityFingerprint],
115
121
  ['supplementalMcpConfigIdentity', compatibility.supplementalMcpConfigIdentity],
116
122
  ['browserMcpConfigIdentity', compatibility.browserMcpConfigIdentity],
123
+ ['disableSkills', compatibility.disableSkills],
117
124
  ['pluginDirs', compatibility.pluginDirs],
118
125
  ['mcpConfigPaths', compatibility.mcpConfigPaths],
119
126
  ['mcpToolAllowlist', compatibility.mcpToolAllowlist],
127
+ ['settingSources', compatibility.settingSources],
120
128
  ];
121
129
  return JSON.stringify(fields);
122
130
  }
@@ -156,6 +164,8 @@ class ClaudeSession {
156
164
  browserMcpConfigPath;
157
165
  compatibility;
158
166
  disableHooks;
167
+ disableSkills;
168
+ settingSources;
159
169
  streamDeltas;
160
170
  captureTranscriptLogs;
161
171
  preserveUnreportedAccounting;
@@ -209,6 +219,8 @@ class ClaudeSession {
209
219
  this.browserMcpConfigPath = options.browserMcpConfigPath ?? null;
210
220
  this.compatibility = compatibilityFromOptions(options);
211
221
  this.disableHooks = options.disableHooks === true;
222
+ this.disableSkills = options.disableSkills === true;
223
+ this.settingSources = options.settingSources;
212
224
  this.streamDeltas = options.streamDeltas;
213
225
  this.onSelfClose = options.onSelfClose;
214
226
  this.onEvict = options.onEvict;
@@ -244,6 +256,8 @@ class ClaudeSession {
244
256
  supplementalMcpConfigPath: this.supplementalMcpConfigPath,
245
257
  browserMcpConfigPath: this.browserMcpConfigPath,
246
258
  disableHooks: this.disableHooks,
259
+ disableSkills: this.disableSkills,
260
+ settingSources: this.settingSources,
247
261
  streamDeltas: this.streamDeltas,
248
262
  });
249
263
  }
@@ -566,6 +580,8 @@ function sessionRuntimeOptions(spec, composition) {
566
580
  browserMcpConfigIdentity: browser?.identity ?? null,
567
581
  pluginCapabilityFingerprint: spec.plugins.fingerprint ?? null,
568
582
  disableHooks: spec.flags.disableHooks,
583
+ disableSkills: spec.flags.disableSkills,
584
+ settingSources: spec.flags.settingSources,
569
585
  streamDeltas: spec.flags.streamDeltas,
570
586
  captureTranscriptLogs: spec.flags.captureTranscripts,
571
587
  preserveUnreportedAccounting: spec.flags.preserveUnreportedAccounting,
@@ -610,6 +626,8 @@ function computeSpawnArgsForSpec(spec) {
610
626
  supplementalMcpConfigPath: opts.supplementalMcpConfigPath,
611
627
  browserMcpConfigPath: opts.browserMcpConfigPath,
612
628
  disableHooks: opts.disableHooks,
629
+ disableSkills: opts.disableSkills,
630
+ settingSources: opts.settingSources,
613
631
  streamDeltas: opts.streamDeltas,
614
632
  });
615
633
  spawnOptions.isUserInitiated = spec.flags.isUserInitiated;
@@ -20,6 +20,13 @@ export interface ClaudeSpawnOptions {
20
20
  supplementalMcpConfigPath?: string | null;
21
21
  /** Omit all configured ambient hooks. */
22
22
  disableHooks?: boolean;
23
+ /** Drop the CLI's whole skill layer (`--disable-slash-commands`). This is the only lever that
24
+ * reaches the skills Cortex never supplied — user-level plugins, `~/.claude/skills/` and the
25
+ * CLI's built-ins — since `--plugin-dir` only ever adds Cortex's own. */
26
+ disableSkills?: boolean;
27
+ /** Setting files the CLI may load (`--setting-sources`). Absent keeps its default set; an empty
28
+ * array is passed as an empty value, which the CLI accepts as "load none". */
29
+ settingSources?: string[];
23
30
  /** Explicit partial-message policy; absent reads the daemon setting. */
24
31
  streamDeltas?: boolean;
25
32
  /** Select Slack tools in the bundled server for Slack-originated direct sessions. */
@@ -141,6 +141,15 @@ function appendRepeatedOption(args, flag, values) {
141
141
  for (const value of values ?? [])
142
142
  args.push(flag, value);
143
143
  }
144
+ /** The two levers that narrow what the CLI loads on its own behalf. `--setting-sources` takes the
145
+ * list verbatim, so an empty array spells the empty value the CLI reads as "load none" — that is
146
+ * what keeps a user's `enabledPlugins` and ambient hooks out of a minimal-surface session. */
147
+ function appendEnvironmentOptions(args, options) {
148
+ if (options.disableSkills)
149
+ args.push('--disable-slash-commands');
150
+ if (options.settingSources)
151
+ args.push('--setting-sources', options.settingSources.join(','));
152
+ }
144
153
  function appendExtraOptions(args, options) {
145
154
  for (const [flag, value] of Object.entries(options ?? {}))
146
155
  args.push(flag, value);
@@ -169,6 +178,7 @@ export function buildSpawnArgs(options) {
169
178
  appendCoreArgs(args, configs, composition, tools);
170
179
  appendPromptOptions(args, options);
171
180
  appendRepeatedOption(args, '--plugin-dir', options.pluginDirs);
181
+ appendEnvironmentOptions(args, options);
172
182
  appendExtraOptions(args, options.extraOption);
173
183
  args.push('--settings', JSON.stringify(buildClaudeSettings(options, tools)));
174
184
  appendSessionIdentity(args, options);
@@ -18,8 +18,10 @@ export interface PiChildRequest {
18
18
  fallbackModel?: PiModelFallback | null;
19
19
  /** Nested session factory; tests substitute a fake. */
20
20
  createSession?: ChildSessionFactory;
21
- /** The Cortex extensions the child loads, closed over the child's own env. */
22
- childExtensions: (env: NodeJS.ProcessEnv) => InlineExtension[];
21
+ /** The Cortex extensions the child loads, closed over the child's own env and the provider the
22
+ * child declared — null whenever the selection names a model without one, which is the only
23
+ * honest answer before PI's resolver has run. */
24
+ childExtensions: (env: NodeJS.ProcessEnv, childProvider: string | null) => InlineExtension[];
23
25
  signal?: AbortSignal;
24
26
  forward?: ChildEventForwarder;
25
27
  }
@@ -37,7 +37,7 @@ export async function runPiChild(request) {
37
37
  model: selection.model ?? null,
38
38
  tools: roleToolsForBackend(role, 'pi'),
39
39
  appendSystemPrompt: role.systemPrompt ? [role.systemPrompt] : [],
40
- extensions: request.childExtensions(buildChildEnv(request.parentEnv, request.agentDir)),
40
+ extensions: request.childExtensions(buildChildEnv(request.parentEnv, request.agentDir), selection.provider ?? null),
41
41
  });
42
42
  try {
43
43
  const result = await collectChild(handle, task, request.signal, request.forward);
@@ -82,6 +82,7 @@ export function childResult(task, accumulator) {
82
82
  output: accumulator.output,
83
83
  usage: accumulator.usage,
84
84
  model: accumulator.model,
85
+ provider: accumulator.provider,
85
86
  backend: 'pi',
86
87
  stopReason: accumulator.stopReason,
87
88
  errorMessage: accumulator.errorMessage,
@@ -135,5 +136,8 @@ function recordAssistantMessage(accumulator, message) {
135
136
  return;
136
137
  accumulator.output = textFromMessage(message) || accumulator.output;
137
138
  accumulator.model = stringOrPrevious(message.model, accumulator.model);
139
+ // Read off the child's own messages, never inherited from the parent: a child may run on another
140
+ // provider entirely, and a guessed name would file its spend under a provider it never used.
141
+ accumulator.provider = stringOrPrevious(message.provider, accumulator.provider);
138
142
  recordTerminalState(accumulator, message);
139
143
  }
@@ -47,8 +47,9 @@ export interface PIEventParserState {
47
47
  export declare function createPIEventParserState(): PIEventParserState;
48
48
  /**
49
49
  * Translate one PI session event (as delivered by `AgentSession.subscribe`, an
50
- * `extension_ui_request` the host raised for an extension, or a `cortex_subagent_event` the Agent
51
- * tool forwarded from a nested session) to zero or more NormalizedEvents.
50
+ * `extension_ui_request` the host raised for an extension, or a `cortex_subagent_event` /
51
+ * `cortex_subagent_usage` record the Agent tool raised for a nested session) to zero or more
52
+ * NormalizedEvents.
52
53
  *
53
54
  * Dropped events (return []): turn_start, turn_end, message_start, agent_start,
54
55
  * queue_update, compaction_end, auto_retry_start/end, message_update without text_delta,
@@ -9,8 +9,9 @@ export function createPIEventParserState() {
9
9
  }
10
10
  /**
11
11
  * Translate one PI session event (as delivered by `AgentSession.subscribe`, an
12
- * `extension_ui_request` the host raised for an extension, or a `cortex_subagent_event` the Agent
13
- * tool forwarded from a nested session) to zero or more NormalizedEvents.
12
+ * `extension_ui_request` the host raised for an extension, or a `cortex_subagent_event` /
13
+ * `cortex_subagent_usage` record the Agent tool raised for a nested session) to zero or more
14
+ * NormalizedEvents.
14
15
  *
15
16
  * Dropped events (return []): turn_start, turn_end, message_start, agent_start,
16
17
  * queue_update, compaction_end, auto_retry_start/end, message_update without text_delta,
@@ -84,6 +85,10 @@ export function piEventToNormalized(event, state) {
84
85
  const notice = subagentNoticeFrom(ev['notice']);
85
86
  return notice ? subagentNoticeEvents(notice) : [];
86
87
  }
88
+ // --- cortex_subagent_usage → one cost_record for the nested child that just ended ---
89
+ if (type === 'cortex_subagent_usage') {
90
+ return subagentUsageEvents(ev['report'], state);
91
+ }
87
92
  // --- extension_error → error (non-fatal) ---
88
93
  if (type === 'extension_error') {
89
94
  const errVal = ev['error'];
@@ -249,6 +254,41 @@ function sumNullableCosts(left, right) {
249
254
  return null;
250
255
  return (left ?? 0) + (right ?? 0);
251
256
  }
257
+ /**
258
+ * One finished child's spend → the `cost_record` that files it, plus its cost added to the turn
259
+ * the child ran inside. The turn's own `numTurns` is left alone: a subagent is work the parent
260
+ * delegated, not another turn the parent took.
261
+ *
262
+ * Unlike the parent's `agent_end`, a child's accumulator has already collapsed "the provider did
263
+ * not report this category" into 0, so these counts are what was observed rather than a proven
264
+ * exact total. Filed anyway: the alternative on record is nothing at all.
265
+ */
266
+ function subagentUsageEvents(value, state) {
267
+ const report = asRecord(value);
268
+ const provider = report['provider'];
269
+ if (typeof provider !== 'string' || provider === '')
270
+ return [];
271
+ const usage = asRecord(report['usage']);
272
+ const input = nonNegativeCount(usage['input']);
273
+ const output = nonNegativeCount(usage['output']);
274
+ const cacheRead = nonNegativeCount(usage['cacheRead']);
275
+ const cacheCreation = nonNegativeCount(usage['cacheWrite']);
276
+ const turns = nonNegativeCount(usage['turns']);
277
+ const cost = nullableNonNegativeNumber(usage['cost']);
278
+ state.pendingCompletion.totalCostUsd = sumNullableCosts(state.pendingCompletion.totalCostUsd, cost);
279
+ const model = report['model'];
280
+ return [{
281
+ type: 'cost_record',
282
+ provider,
283
+ model: typeof model === 'string' ? model : '',
284
+ tokens_in: input, tokens_out: output,
285
+ prompt_tokens: input + cacheRead + cacheCreation, cached_tokens: cacheRead,
286
+ input_tokens: input, output_tokens: output,
287
+ cache_read_tokens: cacheRead, cache_creation_tokens: cacheCreation,
288
+ provider_requests: turns > 0 ? turns : null,
289
+ cost_usd: cost,
290
+ }];
291
+ }
252
292
  function isSubagentEndStatus(value) {
253
293
  return value === 'completed' || value === 'failed' || value === 'killed';
254
294
  }
@@ -347,6 +387,10 @@ export function piContextUsageFromStats(data) {
347
387
  accuracy: 'estimate',
348
388
  };
349
389
  }
390
+ /** A count the child reported, floored at 0: the accumulator only ever holds finite numbers. */
391
+ function nonNegativeCount(value) {
392
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
393
+ }
350
394
  function nullableNonNegativeNumber(value) {
351
395
  return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
352
396
  }
@@ -2,12 +2,16 @@ import type { InlineExtension } from '@earendil-works/pi-coding-agent';
2
2
  import type { CodexQuotaReading } from '../../core/codex-quota.js';
3
3
  import type { PiSessionRequest } from './session-options.js';
4
4
  import type { SubagentNotice } from './event-parser.js';
5
+ import type { SubagentUsageReport } from './subagent.js';
5
6
  import type { PiSubagentBridge } from './subagent-bridge.js';
6
7
  import { type OpenBundledMcpServer } from './mcp-bridge.js';
7
8
  export interface CortexExtensionHooks {
9
+ /** Receives every provider quota reading, from this session and from its nested children alike. */
8
10
  onProviderQuota?: (reading: CodexQuotaReading) => void;
9
11
  /** Receives each event a subagent forwards for the parent's transcript. */
10
12
  onSubagentEvent?: (notice: SubagentNotice) => void;
13
+ /** Receives each finished nested PI child's spend, so a child's tokens reach the cost ledger. */
14
+ onSubagentUsage?: (report: SubagentUsageReport) => void;
11
15
  /** The daemon's subagent machinery — cross-backend children and background runs. Injected
12
16
  * because it reaches the run registry and the delivery route (D10); left unset, the `agent`
13
17
  * tool still delegates to nested PI children and refuses everything else. */
@@ -20,6 +24,8 @@ export interface CortexExtensionHooks {
20
24
  * The four Cortex extensions a session runs with, each closed over the session's request rather
21
25
  * than `process.env`: the MCP bridge (Cortex bundles in-process, plugin servers as independent
22
26
  * connections), the tool shims, the hook bridge unless the role disabled hooks, and the quota
23
- * probe for gateway-routed runs that have somewhere to report to.
27
+ * probe for gateway-routed runs that have somewhere to report to. The same quota reporter reaches
28
+ * nested child sessions through the shims: a child's provider calls are the parent's spend, and
29
+ * codex publishes quota only on real responses, so dropping the child's would starve the reading.
24
30
  */
25
31
  export declare function createCortexExtensions(request: PiSessionRequest, hooks?: CortexExtensionHooks): InlineExtension[];
@@ -6,9 +6,14 @@ import { createQuotaProbe } from './quota-probe.js';
6
6
  * The four Cortex extensions a session runs with, each closed over the session's request rather
7
7
  * than `process.env`: the MCP bridge (Cortex bundles in-process, plugin servers as independent
8
8
  * connections), the tool shims, the hook bridge unless the role disabled hooks, and the quota
9
- * probe for gateway-routed runs that have somewhere to report to.
9
+ * probe for gateway-routed runs that have somewhere to report to. The same quota reporter reaches
10
+ * nested child sessions through the shims: a child's provider calls are the parent's spend, and
11
+ * codex publishes quota only on real responses, so dropping the child's would starve the reading.
10
12
  */
11
13
  export function createCortexExtensions(request, hooks = {}) {
14
+ // Resolved once and handed to both probes — the session's own and the one the shims install on
15
+ // inheriting children — so "does this run report quota" is decided in exactly one place.
16
+ const reportQuota = request.reportsProviderQuota ? hooks.onProviderQuota : undefined;
12
17
  const extensions = [
13
18
  {
14
19
  name: 'cortex-mcp-bridge',
@@ -18,6 +23,8 @@ export function createCortexExtensions(request, hooks = {}) {
18
23
  name: 'cortex-tool-shims',
19
24
  factory: (pi) => installToolShims(pi, request.env, {
20
25
  onSubagentEvent: hooks.onSubagentEvent,
26
+ onSubagentUsage: hooks.onSubagentUsage,
27
+ onProviderQuota: reportQuota,
21
28
  runForeignSubagent: hooks.subagent?.runForeignSubagent,
22
29
  startBackgroundSubagent: hooks.subagent?.startBackgroundSubagent,
23
30
  stopBackgroundSubagent: hooks.subagent?.stopBackgroundSubagent,
@@ -28,8 +35,8 @@ export function createCortexExtensions(request, hooks = {}) {
28
35
  if (!request.disableHooks) {
29
36
  extensions.push({ name: 'cortex-hook-bridge', factory: (pi) => installHookBridge(pi, request.env) });
30
37
  }
31
- if (request.reportsProviderQuota && hooks.onProviderQuota) {
32
- extensions.push({ name: 'cortex-quota-probe', factory: createQuotaProbe(hooks.onProviderQuota) });
38
+ if (reportQuota) {
39
+ extensions.push({ name: 'cortex-quota-probe', factory: createQuotaProbe(reportQuota) });
33
40
  }
34
41
  return extensions;
35
42
  }
@@ -6,7 +6,7 @@ import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
6
6
  import { Type } from '@sinclair/typebox';
7
7
  import { createLogger } from '../../core/log.js';
8
8
  import { MCP_INFRASTRUCTURE_TIMEOUT_MS } from '../../core/mcp-timeout.js';
9
- import { MCP_TOOL_ALLOWLIST_ENV, MCP_TOOLS_BY_SERVER, parseMcpToolAllowlist, validateMcpToolAllowlist, withoutSubagentTools, } from '../../core/mcp-tool-gate.js';
9
+ import { MCP_TOOL_ALLOWLIST_ENV, parseMcpToolAllowlist, withoutSubagentTools, } from '../../core/mcp-tool-gate.js';
10
10
  import { createRedirectRejectingFetch } from '../mcp-remote-fetch.js';
11
11
  import { mapMcpContent, shouldLoadFeishu, shouldLoadSlack, shouldLoadThreadControl, shouldLoadWeb, } from './mcp-bridge-logic.js';
12
12
  import { PI_INTERACTION_BRIDGE_ENV, PI_MCP_COMPOSITION_ENV, } from './session-options.js';
@@ -68,13 +68,13 @@ function assertUniqueServerStateNames(states) {
68
68
  return states;
69
69
  }
70
70
  function validateToolGatedStates(env, states) {
71
- const allowlist = parseMcpToolAllowlist(env[MCP_TOOL_ALLOWLIST_ENV]);
72
- if (allowlist === null)
73
- return states;
74
- const core = states.find(state => state.name === 'core');
75
- const bundles = core?.source.kind === 'bundled' ? core.source.bundles : [];
76
- const known = new Set(bundles.flatMap(bundle => MCP_TOOLS_BY_SERVER[bundle] ?? []));
77
- validateMcpToolAllowlist([...allowlist], known);
71
+ // `parseMcpToolAllowlist` already rejects a name that exists in no bundle at all — that is the
72
+ // typo check, and it is the only one worth making. A name that exists but belongs to a bundle
73
+ // this session does not compose (`send_file` outside a web session) is simply absent here: an
74
+ // allowlist is an upper bound on the surface, not a demand for it, and the gate drops what it
75
+ // cannot register. Validating against the COMPOSED bundles used to turn "this agent also
76
+ // delivers files on the web" into "this agent may not run on Slack".
77
+ parseMcpToolAllowlist(env[MCP_TOOL_ALLOWLIST_ENV]);
78
78
  return states;
79
79
  }
80
80
  function optionalBundles(env) {
@@ -291,6 +291,11 @@ export class PISession {
291
291
  handleRawEvent(event) {
292
292
  if (!this.alive)
293
293
  return;
294
+ // A backgrounded child can settle after the turn that spawned it. With no turn open there is
295
+ // no run to file its spend under, and folding it into the parser's pending total would bill it
296
+ // to whichever turn comes next — so it is left unaccounted, as it was before children reported.
297
+ if (event.type === 'cortex_subagent_usage' && this.turnStream === null)
298
+ return;
294
299
  this.resetIdleTimer();
295
300
  this.bumpTurnIdleTimer();
296
301
  this.observeLoop(event);
@@ -113,6 +113,9 @@ export async function createPiRuntime(request, callbacks, collaborators = {}) {
113
113
  onProviderQuota: callbacks.onProviderQuota,
114
114
  // A subagent's events reach the parent's stream as one raw record per event, no codec in between.
115
115
  onSubagentEvent: (notice) => callbacks.onEvent({ type: 'cortex_subagent_event', notice }),
116
+ // Spend travels its own record rather than riding the transcript channel: the parser turns it
117
+ // into a cost_record, and the transcript never renders it.
118
+ onSubagentUsage: (report) => callbacks.onEvent({ type: 'cortex_subagent_usage', report }),
116
119
  });
117
120
  const sessionManager = openSessionManager(sdk, request);
118
121
  const runtime = await sdk.createAgentSessionRuntime(runtimeFactory(sdk, request, extensions), {
@@ -146,7 +146,11 @@ export function buildSessionRequest(spec, inputs) {
146
146
  thinking: thinkingLevel(spec),
147
147
  systemPrompt: spec.prompt.system || null,
148
148
  appendSystemPrompt: promptValues(spec.prompt.append),
149
- skillPaths: [...(spec.plugins.skillDirs ?? []), ...(spec.plugins.dirs ?? [])],
149
+ // PI has no skill layer of its own to switch off: its skills are exactly the roots handed to
150
+ // it here, so an agent that wants none gets none by handing it nothing.
151
+ skillPaths: spec.flags.disableSkills
152
+ ? []
153
+ : [...(spec.plugins.skillDirs ?? []), ...(spec.plugins.dirs ?? [])],
150
154
  disableHooks: spec.flags.disableHooks === true,
151
155
  reportsProviderQuota: !!spec.route.gatewayBaseUrl,
152
156
  pluginMcpServers: pluginMcpServers(spec, composition, marker),
@@ -1,7 +1,7 @@
1
1
  import type { InlineExtension, ToolDefinition } from '@earendil-works/pi-coding-agent';
2
2
  import { type AgentRole } from '../../core/agents/roles.js';
3
3
  import { type SubagentCatalog, type SubagentFieldDescriptions } from '../../core/agents/subagent/catalog.js';
4
- import type { SubagentDetails, SubagentResult, SubagentTask } from '../../core/agents/subagent/types.js';
4
+ import type { SubagentDetails, SubagentResult, SubagentTask, SubagentUsage } from '../../core/agents/subagent/types.js';
5
5
  import type { Backend } from '../types.js';
6
6
  import type { ChildSessionFactory } from './child-session.js';
7
7
  import type { StartBackgroundSubagent, StopBackgroundSubagent } from './background-subagent.js';
@@ -60,6 +60,13 @@ export interface ForeignSubagentRequest {
60
60
  onNotice?: (notice: SubagentNotice) => void;
61
61
  }
62
62
  export type RunForeignSubagent = (request: ForeignSubagentRequest) => Promise<SubagentResult>;
63
+ /** One nested PI child's spend, handed to the host when that child ends. The ledger's unit is the
64
+ * child, not the message: a run of eight children files eight records, each naming who answered. */
65
+ export interface SubagentUsageReport {
66
+ provider: string;
67
+ model: string;
68
+ usage: SubagentUsage;
69
+ }
63
70
  export interface SubagentToolDeps {
64
71
  /** PI agent dir whose auth/models the `pi` children use. */
65
72
  agentDir: string;
@@ -68,12 +75,17 @@ export interface SubagentToolDeps {
68
75
  ensureRoles(): void;
69
76
  /** Creates one nested in-process PI session per `pi` child. */
70
77
  createSession: ChildSessionFactory;
71
- /** The Cortex extensions a child session runs with, closed over the child's env. */
72
- childExtensions: (env: NodeJS.ProcessEnv) => InlineExtension[];
78
+ /** The Cortex extensions a child session runs with, closed over the child's env and the provider
79
+ * the child declared (null when only PI's resolver will know it). */
80
+ childExtensions: (env: NodeJS.ProcessEnv, childProvider: string | null) => InlineExtension[];
73
81
  /** The parent session's env; each child's env is derived from it. */
74
82
  parentEnv: NodeJS.ProcessEnv;
75
83
  /** Receives every forwarded child event for the parent's transcript. Absent: no attribution. */
76
84
  onEvent?: (notice: SubagentNotice) => void;
85
+ /** Receives each finished nested PI child's spend so it reaches the cost ledger. Absent: the
86
+ * child's tokens stay in the tool result and are never accounted. Children on another backend
87
+ * are not reported here: the daemon runner records those as runs of their own. */
88
+ onUsage?: (report: SubagentUsageReport) => void;
77
89
  /** Runs children whose backend is not `pi`. Absent: such a task is an error, not a silent
78
90
  * downgrade — a role asking for `claude` must not quietly answer from a PI model. */
79
91
  runForeignSubagent?: RunForeignSubagent;
@@ -45,6 +45,22 @@ function buildSubagentParameters(described) {
45
45
  const StopParameters = Type.Object({
46
46
  agent_id: Type.String({ description: 'The agent_id returned when the subagent was started.' }),
47
47
  });
48
+ /**
49
+ * Hand a nested PI child's spend to the host, once, as the child ends.
50
+ *
51
+ * Reported only when the child's own messages named the provider that answered: without one the
52
+ * ledger has nowhere honest to file the record, and a child that never reached a provider spent
53
+ * nothing to file. An aborted child files nothing — its accumulator dies with the cancelled run.
54
+ * Best-effort by contract: accounting must never fail a subagent that already did its work.
55
+ */
56
+ function reportChildUsage(deps, result) {
57
+ if (!deps.onUsage || !result.provider || result.usage.turns === 0)
58
+ return;
59
+ try {
60
+ deps.onUsage({ provider: result.provider, model: result.model ?? '', usage: result.usage });
61
+ }
62
+ catch { /* best-effort */ }
63
+ }
48
64
  function fallbackModel(ctx) {
49
65
  return ctx.model ? { id: ctx.model.id, provider: ctx.model.provider } : null;
50
66
  }
@@ -74,6 +90,8 @@ function buildRunChild(ctx, deps, roles, parentToolCallId) {
74
90
  childExtensions: deps.childExtensions, signal, forward,
75
91
  })
76
92
  : await runForeignChild(ctx, deps, task, role, backend, ref, signal);
93
+ if (backend === 'pi')
94
+ reportChildUsage(deps, result);
77
95
  seal(endStatusOf(result));
78
96
  return result;
79
97
  }
@@ -1,12 +1,17 @@
1
1
  import type { ExtensionAPI, InlineExtension } from '@earendil-works/pi-coding-agent';
2
+ import type { CodexQuotaReading } from '../../core/codex-quota.js';
2
3
  import { type ChildSessionFactory } from './child-session.js';
3
4
  import type { SubagentNotice } from './event-parser.js';
4
5
  import { type OpenBundledMcpServer } from './mcp-bridge.js';
5
6
  import type { StartBackgroundSubagent, StopBackgroundSubagent } from './background-subagent.js';
6
- import { type RunForeignSubagent } from './subagent.js';
7
+ import { type RunForeignSubagent, type SubagentUsageReport } from './subagent.js';
7
8
  export interface ToolShimHooks {
8
9
  /** Receives each event a subagent forwards for the parent's transcript. */
9
10
  onSubagentEvent?: (notice: SubagentNotice) => void;
11
+ /** Reports provider quota read off a nested child's responses; set only for runs that report it. */
12
+ onProviderQuota?: (reading: CodexQuotaReading) => void;
13
+ /** Receives each finished nested PI child's spend, for the cost ledger. */
14
+ onSubagentUsage?: (report: SubagentUsageReport) => void;
10
15
  /** Nested session factory for subagents; tests substitute a fake. */
11
16
  createChildSession?: ChildSessionFactory;
12
17
  /** Runs children whose backend is not `pi`. Supplied by the host (D10); absent ⇒ the `agent`
@@ -5,6 +5,7 @@ import { loadRoles } from '../../core/agents/roles.js';
5
5
  import { claudeModelOptions, decodeSubagentModels, piModelOptions, roleOptionsFrom, } from '../../core/agents/subagent/catalog.js';
6
6
  import { createChildSession } from './child-session.js';
7
7
  import { createMcpBridgeDeps, installMcpBridge, } from './mcp-bridge.js';
8
+ import { createQuotaProbe } from './quota-probe.js';
8
9
  import { createSubagentStopTool, createSubagentTool, } from './subagent.js';
9
10
  import { webFetchTool } from './web-fetch.js';
10
11
  import { webSearchTool } from './web-search.js';
@@ -79,21 +80,53 @@ export function childExtensions(env, openBundledMcpServer) {
79
80
  },
80
81
  ];
81
82
  }
83
+ /**
84
+ * The quota probe a nested child session runs with, or null when the child must not report.
85
+ *
86
+ * The host labels every reading with the provider *this run* was routed as (the adapter's
87
+ * `quotaReporter`), so a child that reached a different provider would have its quota filed under
88
+ * the parent's — throttling a provider that never produced the reading. A child's provider is only
89
+ * known here when it inherited the session's model outright; the moment a role or task names a
90
+ * model, PI's resolver picks the provider later and this side cannot prove they match. So the
91
+ * probe goes on inheriting children only, and an overridden child simply reports nothing.
92
+ *
93
+ * One extension serves every child: PI hands each bound session its own `pi`, so a single factory
94
+ * registers one listener per child rather than sharing state between them.
95
+ */
96
+ function childQuotaProbe(hooks) {
97
+ if (!hooks.onProviderQuota)
98
+ return () => null;
99
+ const extension = {
100
+ name: 'cortex-quota-probe',
101
+ factory: createQuotaProbe(hooks.onProviderQuota),
102
+ };
103
+ return (sessionProvider, childProvider) => (sessionProvider && childProvider === sessionProvider ? extension : null);
104
+ }
82
105
  function registerRuntimeAgent(pi, env, hooks) {
83
106
  const agentDir = env.PI_CODING_AGENT_DIR ?? PI_AGENT_DIR;
107
+ // The provider this session's own model is on, known once the session starts. A child that
108
+ // inherited it is the only one whose quota readings can be filed under this run's provider.
109
+ let sessionProvider = null;
110
+ const quotaProbe = childQuotaProbe(hooks);
84
111
  const deps = {
85
112
  agentDir,
86
113
  ensureRoles: () => ensurePIAgentRoles({ legacyDir: path.join(agentDir, 'agents') }),
87
114
  createSession: hooks.createChildSession ?? createChildSession,
88
115
  // The child inherits this session's opener: it is the same daemon, hosting the same bundles.
89
- childExtensions: (childEnv) => childExtensions(childEnv, hooks.openBundledMcpServer),
116
+ childExtensions: (childEnv, childProvider) => {
117
+ const extensions = childExtensions(childEnv, hooks.openBundledMcpServer);
118
+ const probe = quotaProbe(sessionProvider, childProvider);
119
+ return probe ? [...extensions, probe] : extensions;
120
+ },
90
121
  parentEnv: env,
91
122
  onEvent: hooks.onSubagentEvent,
123
+ onUsage: hooks.onSubagentUsage,
92
124
  runForeignSubagent: hooks.runForeignSubagent,
93
125
  startBackgroundSubagent: hooks.startBackgroundSubagent,
94
126
  stopBackgroundSubagent: hooks.stopBackgroundSubagent,
95
127
  };
96
128
  pi.on('session_start', (_event, ctx) => {
129
+ sessionProvider = ctx.model?.provider ?? null;
97
130
  pi.registerTool(createSubagentTool(deps, runtimeCatalog(ctx, env, deps)));
98
131
  const stopTool = createSubagentStopTool(deps);
99
132
  if (stopTool)