@oyasmi/pipiclaw 0.9.0-beta.1 → 0.9.0-beta.2

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.
@@ -508,6 +508,9 @@ export function createSubAgentTool(options) {
508
508
  purpose: runContext.purpose,
509
509
  taskId: runContext.taskId,
510
510
  leaseKey,
511
+ mutates: config.mutates,
512
+ workspaceDir: options.workspaceDir,
513
+ securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
511
514
  });
512
515
  }
513
516
  catch (error) {
@@ -546,7 +549,14 @@ export function createSubAgentTool(options) {
546
549
  };
547
550
  }
548
551
  const scopedExecutor = new DirectoryExecutor(options.executor, runContext.workingDirectory);
549
- const apiKey = await options.resolveApiKey(config.model);
552
+ let apiKey;
553
+ try {
554
+ apiKey = await options.resolveApiKey(config.model);
555
+ }
556
+ catch (error) {
557
+ releaseWorkspaceLease(leaseKey);
558
+ throw error;
559
+ }
550
560
  const startedAt = Date.now();
551
561
  const usage = createEmptyUsageTotals();
552
562
  let assistantTurns = 0;
@@ -559,22 +569,30 @@ export function createSubAgentTool(options) {
559
569
  /** True once the sync grace window has elapsed and a "still running" placeholder has been returned. */
560
570
  let detached = false;
561
571
  let lastUpdateText = "";
562
- const runManager = getSubAgentRunManager(options.runtimeContext.channelId);
563
- await runManager.register({
564
- runId: runContext.runId,
565
- channelId: options.runtimeContext.channelId,
566
- runtime: "internal",
567
- agent: config.name,
568
- label: params.label,
569
- source: config.source,
570
- tools: [...config.tools],
571
- model: formatModelReference(config.model),
572
- purpose: runContext.purpose,
573
- taskId: runContext.taskId,
574
- workingDirectory: runContext.workingDirectory,
575
- artifactDir: runContext.artifactDir,
576
- leaseKey,
577
- });
572
+ const runManager = (options.getRunManager ?? getSubAgentRunManager)(options.runtimeContext.channelId);
573
+ try {
574
+ await runManager.register({
575
+ runId: runContext.runId,
576
+ channelId: options.runtimeContext.channelId,
577
+ runtime: "internal",
578
+ agent: config.name,
579
+ label: params.label,
580
+ source: config.source,
581
+ tools: [...config.tools],
582
+ model: formatModelReference(config.model),
583
+ purpose: runContext.purpose,
584
+ taskId: runContext.taskId,
585
+ workingDirectory: runContext.workingDirectory,
586
+ artifactDir: runContext.artifactDir,
587
+ leaseKey,
588
+ });
589
+ }
590
+ catch (error) {
591
+ // Until the durable running record exists, setup still owns the lease. A channel/host
592
+ // admission rejection or required persist failure must leave no invisible writer lock.
593
+ releaseWorkspaceLease(leaseKey);
594
+ throw error;
595
+ }
578
596
  const emitUpdate = (text) => {
579
597
  // Once detached, execute() has already returned to the SDK; nothing is listening
580
598
  // for further progress on this (from its view, finished) tool call.
@@ -590,71 +608,109 @@ export function createSubAgentTool(options) {
590
608
  details: createDetails(config, runContext, usage, assistantTurns, toolCalls, Date.now() - startedAt, Boolean(failureReason), failureReason),
591
609
  });
592
610
  };
593
- const availableTools = buildSubagentTools(scopedExecutor, config.bashTimeoutSec, options, runContext);
594
- const verifierGitStateBefore = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
595
- const verifierSubjectBefore = runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
596
- const worker = options.createWorker?.({
597
- subAgent: config,
598
- apiKey,
599
- tools: filterToolsByName(availableTools, config.tools),
600
- }) ??
601
- new Agent({
602
- initialState: {
603
- systemPrompt: config.systemPrompt,
604
- model: config.model,
605
- thinkingLevel: config.thinkingLevel,
611
+ let worker;
612
+ let wallClockTimer;
613
+ let unsubscribe;
614
+ let verifierGitStateBefore;
615
+ let verifierSubjectBefore;
616
+ try {
617
+ const availableTools = (options.buildTools ?? buildSubagentTools)(scopedExecutor, config.bashTimeoutSec, options, runContext);
618
+ verifierGitStateBefore =
619
+ runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
620
+ verifierSubjectBefore =
621
+ runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
622
+ worker =
623
+ options.createWorker?.({
624
+ subAgent: config,
625
+ apiKey,
606
626
  tools: filterToolsByName(availableTools, config.tools),
607
- },
608
- convertToLlm,
609
- getApiKey: async () => apiKey,
610
- streamFn: streamSimple,
627
+ }) ??
628
+ new Agent({
629
+ initialState: {
630
+ systemPrompt: config.systemPrompt,
631
+ model: config.model,
632
+ thinkingLevel: config.thinkingLevel,
633
+ tools: filterToolsByName(availableTools, config.tools),
634
+ },
635
+ convertToLlm,
636
+ getApiKey: async () => apiKey,
637
+ streamFn: streamSimple,
638
+ });
639
+ runManager.registerCancelHandle(runContext.runId, () => {
640
+ externallyCancelled = true;
641
+ worker?.abort();
611
642
  });
612
- runManager.registerCancelHandle(runContext.runId, () => {
613
- externallyCancelled = true;
614
- worker.abort();
615
- });
616
- const wallClockTimer = setTimeout(() => {
617
- failureReason = `Wall time budget exceeded (${config.maxWallTimeSec}s)`;
618
- budgetExceeded = true;
619
- worker.abort();
620
- }, config.maxWallTimeSec * 1000);
621
- const unsubscribe = worker.subscribe((event) => {
622
- if (event.type === "message_end" && isAssistantMessage(event.message)) {
623
- assistantTurns++;
624
- const messageUsage = event.message.usage;
625
- usage.input += messageUsage.input;
626
- usage.output += messageUsage.output;
627
- usage.cacheRead += messageUsage.cacheRead;
628
- usage.cacheWrite += messageUsage.cacheWrite;
629
- usage.total += messageUsage.totalTokens;
630
- usage.cost.input += messageUsage.cost.input;
631
- usage.cost.output += messageUsage.cost.output;
632
- usage.cost.cacheRead += messageUsage.cost.cacheRead;
633
- usage.cost.cacheWrite += messageUsage.cost.cacheWrite;
634
- usage.cost.total += messageUsage.cost.total;
635
- }
636
- if (event.type === "tool_execution_start") {
637
- toolCalls++;
638
- const label = extractLabelFromArgs(event.args) || event.toolName;
639
- emitUpdate(formatStatus(config.name, label));
640
- if (toolCalls > config.maxToolCalls) {
641
- failureReason = `Tool call budget exceeded (${config.maxToolCalls})`;
643
+ wallClockTimer = setTimeout(() => {
644
+ failureReason = `Wall time budget exceeded (${config.maxWallTimeSec}s)`;
645
+ budgetExceeded = true;
646
+ worker?.abort();
647
+ }, config.maxWallTimeSec * 1000);
648
+ unsubscribe = worker.subscribe((event) => {
649
+ if (event.type === "message_end" && isAssistantMessage(event.message)) {
650
+ assistantTurns++;
651
+ const messageUsage = event.message.usage;
652
+ usage.input += messageUsage.input;
653
+ usage.output += messageUsage.output;
654
+ usage.cacheRead += messageUsage.cacheRead;
655
+ usage.cacheWrite += messageUsage.cacheWrite;
656
+ usage.total += messageUsage.totalTokens;
657
+ usage.cost.input += messageUsage.cost.input;
658
+ usage.cost.output += messageUsage.cost.output;
659
+ usage.cost.cacheRead += messageUsage.cost.cacheRead;
660
+ usage.cost.cacheWrite += messageUsage.cost.cacheWrite;
661
+ usage.cost.total += messageUsage.cost.total;
662
+ }
663
+ if (event.type === "tool_execution_start") {
664
+ toolCalls++;
665
+ const label = extractLabelFromArgs(event.args) || event.toolName;
666
+ emitUpdate(formatStatus(config.name, label));
667
+ if (toolCalls > config.maxToolCalls) {
668
+ failureReason = `Tool call budget exceeded (${config.maxToolCalls})`;
669
+ budgetExceeded = true;
670
+ emitUpdate(formatStatus(config.name, "tool budget reached"));
671
+ worker?.abort();
672
+ }
673
+ }
674
+ if (event.type === "turn_end" &&
675
+ isAssistantMessage(event.message) &&
676
+ event.toolResults.length > 0 &&
677
+ assistantTurns >= config.maxTurns) {
678
+ failureReason = `Turn budget exceeded (${config.maxTurns})`;
642
679
  budgetExceeded = true;
643
- emitUpdate(formatStatus(config.name, "tool budget reached"));
644
- worker.abort();
680
+ emitUpdate(formatStatus(config.name, "turn budget reached"));
681
+ worker?.abort();
645
682
  }
683
+ });
684
+ emitUpdate(formatStatus(config.name, "started"));
685
+ }
686
+ catch (error) {
687
+ unsubscribe?.();
688
+ if (wallClockTimer)
689
+ clearTimeout(wallClockTimer);
690
+ runManager.clearCancelHandle(runContext.runId);
691
+ try {
692
+ worker?.abort();
646
693
  }
647
- if (event.type === "turn_end" &&
648
- isAssistantMessage(event.message) &&
649
- event.toolResults.length > 0 &&
650
- assistantTurns >= config.maxTurns) {
651
- failureReason = `Turn budget exceeded (${config.maxTurns})`;
652
- budgetExceeded = true;
653
- emitUpdate(formatStatus(config.name, "turn budget reached"));
654
- worker.abort();
694
+ catch {
695
+ // Preserve the setup error; settlement below is the lifecycle authority.
655
696
  }
656
- });
657
- emitUpdate(formatStatus(config.name, "started"));
697
+ const setupError = error instanceof Error ? error : new Error(String(error));
698
+ await runManager.settle(runContext.runId, {
699
+ status: "failed",
700
+ failureReason: setupError.message,
701
+ usage,
702
+ usageKnown: true,
703
+ costKnown: true,
704
+ turns: assistantTurns,
705
+ toolCalls,
706
+ durationMs: Date.now() - startedAt,
707
+ outputText: "",
708
+ }, { announce: false });
709
+ throw setupError;
710
+ }
711
+ const activeWorker = worker;
712
+ const activeUnsubscribe = unsubscribe;
713
+ const activeWallClockTimer = wallClockTimer;
658
714
  /**
659
715
  * Runs the worker to completion, including the D6 convergence turn, and returns the
660
716
  * tool result plus the data `runs.ts` needs to settle. Rejects only for the single
@@ -664,24 +720,24 @@ export function createSubAgentTool(options) {
664
720
  async function runToCompletion() {
665
721
  try {
666
722
  const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel);
667
- await worker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext, returns));
668
- await worker.waitForIdle();
723
+ await activeWorker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext, returns));
724
+ await activeWorker.waitForIdle();
669
725
  // D6: a self-inflicted budget abort gets one tool-free turn to converge on a
670
726
  // conclusion instead of discarding the work outright. An explicit cancel skips
671
727
  // this — the model asked this run to stop now, not to wrap up.
672
728
  if (budgetExceeded && !externallyCancelled) {
673
- clearTimeout(wallClockTimer);
729
+ clearTimeout(activeWallClockTimer);
674
730
  emitUpdate(formatStatus(config.name, "converging on budget exhaustion"));
675
- const preConvergenceMessageCount = worker.state.messages.length;
676
- worker.state.tools = [];
731
+ const preConvergenceMessageCount = activeWorker.state.messages.length;
732
+ activeWorker.state.tools = [];
677
733
  let convergenceTimedOut = false;
678
734
  const convergenceTimer = setTimeout(() => {
679
735
  convergenceTimedOut = true;
680
- worker.abort();
736
+ activeWorker.abort();
681
737
  }, options.convergenceWallClockMs ?? CONVERGENCE_WALL_CLOCK_MS);
682
738
  try {
683
- await worker.prompt(CONVERGENCE_PROMPT);
684
- await worker.waitForIdle();
739
+ await activeWorker.prompt(CONVERGENCE_PROMPT);
740
+ await activeWorker.waitForIdle();
685
741
  }
686
742
  catch {
687
743
  // Best effort: fall through to whatever worker.state.messages holds.
@@ -692,15 +748,15 @@ export function createSubAgentTool(options) {
692
748
  if (convergenceTimedOut) {
693
749
  // Revert to the pre-D6 behavior: drop the (aborted, possibly partial)
694
750
  // convergence turn and fall back to whatever came before it.
695
- worker.state.messages = worker.state.messages.slice(0, preConvergenceMessageCount);
751
+ activeWorker.state.messages = activeWorker.state.messages.slice(0, preConvergenceMessageCount);
696
752
  }
697
753
  }
698
754
  }
699
755
  finally {
700
- unsubscribe();
701
- clearTimeout(wallClockTimer);
756
+ activeUnsubscribe();
757
+ clearTimeout(activeWallClockTimer);
702
758
  }
703
- const lastAssistantMessage = getLastAssistantMessage(worker.state.messages);
759
+ const lastAssistantMessage = getLastAssistantMessage(activeWorker.state.messages);
704
760
  const durationMs = Date.now() - startedAt;
705
761
  if (!lastAssistantMessage) {
706
762
  failureReason = failureReason || "Sub-agent returned no assistant message";
@@ -35,6 +35,17 @@ export interface TaskProvenance {
35
35
  createdAt?: string;
36
36
  sourceMessageId?: string;
37
37
  }
38
+ /** Durable ownership marker for the interval between a structured completion wake activating a
39
+ * task and its transport accepting the corresponding turn. */
40
+ export interface TaskWakeHandoff {
41
+ kind: "subagent";
42
+ resourceId: string;
43
+ dispatchId: string;
44
+ generation: number;
45
+ previousLastOutcome: TaskOutcome;
46
+ previousBlockedReason?: string;
47
+ previousLastStartedAt?: string;
48
+ }
38
49
  /** The v2 persisted control block. Execution authority comes from capability and scope. */
39
50
  export interface TaskControl {
40
51
  version: 2;
@@ -55,6 +66,7 @@ export interface TaskControl {
55
66
  /** Present only while the task is disabled. */
56
67
  stop?: TaskStop;
57
68
  provenance?: TaskProvenance;
69
+ wakeHandoff?: TaskWakeHandoff;
58
70
  }
59
71
  export interface TaskControlPatch {
60
72
  priority?: TaskPriority;
@@ -88,6 +88,24 @@ function parseProvenance(value) {
88
88
  }
89
89
  return { createdBy, createdAt, sourceMessageId };
90
90
  }
91
+ function parseWakeHandoff(value) {
92
+ if (value === undefined)
93
+ return undefined;
94
+ if (!isRecord(value))
95
+ throw new Error("control.wakeHandoff must be an object");
96
+ if (value.kind !== "subagent" || typeof value.resourceId !== "string" || typeof value.dispatchId !== "string") {
97
+ throw new Error("control.wakeHandoff requires kind=subagent, resourceId, and dispatchId");
98
+ }
99
+ return {
100
+ kind: "subagent",
101
+ resourceId: value.resourceId,
102
+ dispatchId: value.dispatchId,
103
+ generation: nonNegativeInteger(value.generation),
104
+ previousLastOutcome: enumValue(normalizeLegacyOutcome(value.previousLastOutcome), OUTCOMES, "pending"),
105
+ previousBlockedReason: optionalString(value.previousBlockedReason),
106
+ previousLastStartedAt: optionalString(value.previousLastStartedAt),
107
+ };
108
+ }
91
109
  /**
92
110
  * Keys from the v1 control block that this version deliberately retires. They remain visible to
93
111
  * doctor until the next successful write, but they never enter the v2 control object.
@@ -202,6 +220,7 @@ export function parseTaskControl(raw) {
202
220
  cycleId: optionalString(value.cycleId),
203
221
  stop,
204
222
  provenance: parseProvenance(value.provenance),
223
+ wakeHandoff: parseWakeHandoff(value.wakeHandoff),
205
224
  };
206
225
  }
207
226
  function zeroUsage() {
@@ -224,6 +243,7 @@ export function resetTaskControlForCycle(control, cycleId) {
224
243
  lastFinishedAt: undefined,
225
244
  cycleId: normalizedCycleId,
226
245
  stop: undefined,
246
+ wakeHandoff: undefined,
227
247
  };
228
248
  }
229
249
  function patchOptionalString(current, value) {
@@ -51,6 +51,27 @@ export declare function finishTaskAttempt(channelDir: string, id: string, result
51
51
  export declare function escalateTask(channelDir: string, id: string, reason: string): Promise<boolean>;
52
52
  /** Atomically convert a due timed wait to active before any wake is dispatched. */
53
53
  export declare function activateWaitingTask(channelDir: string, id: string, expectedWaitingFor?: TaskWaitingFor): Promise<StoredTaskDocument | undefined>;
54
+ export interface WakeTaskTransitionHooks {
55
+ /** Test-only fault seam: both hooks run before the single atomic task-file write. */
56
+ beforeActivation?: () => void;
57
+ beforeAttemptClaim?: () => void;
58
+ }
59
+ export interface WakeTaskHandoffInput {
60
+ kind: "subagent";
61
+ resourceId: string;
62
+ dispatchId: string;
63
+ }
64
+ /** Activate a completion-woken task and claim its next attempt in one task-file mutation. Keeping
65
+ * these state changes in one atomic write means a transient failure cannot leave the task active
66
+ * but unclaimed, which would make a retry of the same durable wake look ineligible. */
67
+ export declare function activateWaitingTaskAndClaimAttempt(channelDir: string, id: string, expectedWaitingFor: TaskWaitingFor, now: Date, hooks?: WakeTaskTransitionHooks, handoff?: WakeTaskHandoffInput): Promise<{
68
+ document: StoredTaskDocument;
69
+ generation: number;
70
+ } | undefined>;
71
+ /** Return a transport-rejected structured wake to its exact pre-activation task state. */
72
+ export declare function rollbackWakeTaskActivation(channelDir: string, id: string, expected: WakeTaskHandoffInput): Promise<void>;
73
+ /** Clear the durable handoff after the transport has accepted the activated turn. */
74
+ export declare function finishWakeTaskActivation(channelDir: string, id: string, expected: WakeTaskHandoffInput): Promise<void>;
54
75
  /**
55
76
  * A stable cycle id for a runtime-opened recurring cycle: `cycle-YYYY-MM-DD`, disambiguated
56
77
  * with a `-N` suffix when the same task is reopened more than once on the same local day.
@@ -168,6 +168,86 @@ export async function activateWaitingTask(channelDir, id, expectedWaitingFor) {
168
168
  });
169
169
  return activated ? document : undefined;
170
170
  }
171
+ /** Activate a completion-woken task and claim its next attempt in one task-file mutation. Keeping
172
+ * these state changes in one atomic write means a transient failure cannot leave the task active
173
+ * but unclaimed, which would make a retry of the same durable wake look ineligible. */
174
+ export async function activateWaitingTaskAndClaimAttempt(channelDir, id, expectedWaitingFor, now, hooks, handoff) {
175
+ let generation;
176
+ const document = await updateStoredTask(channelDir, id, (task) => {
177
+ const status = normalizeStoredStatus(task.fields.status, Boolean(task.fields.schedule));
178
+ const existingHandoff = task.fields.control?.wakeHandoff;
179
+ if (handoff &&
180
+ status === "active" &&
181
+ existingHandoff?.kind === handoff.kind &&
182
+ existingHandoff.resourceId === handoff.resourceId &&
183
+ existingHandoff.dispatchId === handoff.dispatchId &&
184
+ task.fields.control?.attemptGeneration === existingHandoff.generation) {
185
+ generation = existingHandoff.generation;
186
+ return;
187
+ }
188
+ if (status !== "waiting" || task.fields.enabled === false)
189
+ return;
190
+ if (task.fields.control?.waitingFor !== expectedWaitingFor)
191
+ return;
192
+ hooks?.beforeActivation?.();
193
+ task.fields.control ??= createDefaultTaskControl();
194
+ task.fields.status = "active";
195
+ task.fields.wake = undefined;
196
+ task.fields.control.waitingFor = undefined;
197
+ task.fields.control.blockedReason = undefined;
198
+ hooks?.beforeAttemptClaim?.();
199
+ generation = task.fields.control.attemptGeneration + 1;
200
+ const previousLastOutcome = task.fields.control.lastOutcome;
201
+ const previousBlockedReason = task.fields.control.blockedReason;
202
+ const previousLastStartedAt = task.fields.control.lastStartedAt;
203
+ task.fields.control.usage.attempts++;
204
+ task.fields.control.attemptGeneration = generation;
205
+ task.fields.control.lastStartedAt = formatLocalTime(now);
206
+ task.fields.control.lastOutcome = "running";
207
+ if (handoff) {
208
+ task.fields.control.wakeHandoff = {
209
+ ...handoff,
210
+ generation,
211
+ previousLastOutcome,
212
+ previousBlockedReason,
213
+ previousLastStartedAt,
214
+ };
215
+ }
216
+ });
217
+ return document && generation !== undefined ? { document, generation } : undefined;
218
+ }
219
+ function isMatchingWakeHandoff(handoff, expected) {
220
+ return (handoff?.kind === expected.kind &&
221
+ handoff.resourceId === expected.resourceId &&
222
+ handoff.dispatchId === expected.dispatchId);
223
+ }
224
+ /** Return a transport-rejected structured wake to its exact pre-activation task state. */
225
+ export async function rollbackWakeTaskActivation(channelDir, id, expected) {
226
+ await updateStoredTask(channelDir, id, (task) => {
227
+ const control = task.fields.control;
228
+ const handoff = control?.wakeHandoff;
229
+ if (!control || !isMatchingWakeHandoff(handoff, expected) || control.attemptGeneration !== handoff.generation) {
230
+ return;
231
+ }
232
+ task.fields.status = "waiting";
233
+ task.fields.wake = undefined;
234
+ control.waitingFor = "external-signal";
235
+ control.usage.attempts = Math.max(0, control.usage.attempts - 1);
236
+ control.attemptGeneration = Math.max(0, handoff.generation - 1);
237
+ control.lastOutcome = handoff.previousLastOutcome;
238
+ control.blockedReason = handoff.previousBlockedReason;
239
+ control.lastStartedAt = handoff.previousLastStartedAt;
240
+ control.wakeHandoff = undefined;
241
+ });
242
+ }
243
+ /** Clear the durable handoff after the transport has accepted the activated turn. */
244
+ export async function finishWakeTaskActivation(channelDir, id, expected) {
245
+ await updateStoredTask(channelDir, id, (task) => {
246
+ if (isMatchingWakeHandoff(task.fields.control?.wakeHandoff, expected) && task.fields.control) {
247
+ task.fields.control.wakeHandoff = undefined;
248
+ }
249
+ });
250
+ }
171
251
  /**
172
252
  * A stable cycle id for a runtime-opened recurring cycle: `cycle-YYYY-MM-DD`, disambiguated
173
253
  * with a `-N` suffix when the same task is reopened more than once on the same local day.
@@ -66,6 +66,8 @@ export function createPipiclawTools(options) {
66
66
  channelId: options.channelId,
67
67
  channelDir: options.channelDir,
68
68
  getSubAgentDiscovery: options.getSubAgentDiscovery,
69
+ workspaceDir: options.workspaceDir,
70
+ securityConfig,
69
71
  }), "subagent_manage"),
70
72
  ];
71
73
  }
@@ -1,5 +1,6 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { Type } from "typebox";
3
+ import type { SecurityConfig } from "../security/types.js";
3
4
  import type { SubAgentDiscoveryResult } from "../subagents/discovery.js";
4
5
  declare const subagentManageSchema: Type.TObject<{
5
6
  label: Type.TString;
@@ -13,6 +14,10 @@ export interface SubAgentManageToolOptions {
13
14
  channelDir?: string;
14
15
  /** Needed only for `follow_up`: re-resolves the role's current config by name. */
15
16
  getSubAgentDiscovery?: () => SubAgentDiscoveryResult;
17
+ /** Needed only for `follow_up`, which dispatches a new external process and must audit it
18
+ * exactly like the initial dispatch (D8.1/T5). */
19
+ workspaceDir?: string;
20
+ securityConfig?: SecurityConfig;
16
21
  }
17
22
  export declare function createSubAgentManageTool(options: SubAgentManageToolOptions): AgentTool<typeof subagentManageSchema>;
18
23
  export {};
@@ -1,8 +1,9 @@
1
1
  import { Type } from "typebox";
2
+ import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
2
3
  import { RecoverableToolError } from "../shared/recoverable-error.js";
3
4
  import { launchExternalRun } from "../subagents/external/run.js";
4
5
  import { getSubAgentRunManager } from "../subagents/runs.js";
5
- import { acquireWorkspaceLease, formatWorkspaceLeaseConflict } from "../subagents/workspace-lease.js";
6
+ import { acquireWorkspaceLease, formatWorkspaceLeaseConflict, releaseWorkspaceLease, } from "../subagents/workspace-lease.js";
6
7
  const subagentManageSchema = Type.Object({
7
8
  label: Type.String({ description: "Brief description of what you're checking (shown to user)" }),
8
9
  op: Type.Union([Type.Literal("list"), Type.Literal("cancel"), Type.Literal("follow_up")], {
@@ -104,29 +105,41 @@ export function createSubAgentManageTool(options) {
104
105
  }
105
106
  leaseKey = lease.leaseKey;
106
107
  }
107
- await launchExternalRun({
108
- runId: toolCallId,
109
- channelId: options.channelId,
110
- channelDir: options.channelDir,
111
- label: `follow-up: ${task.slice(0, 80)}`,
112
- agent: role.name,
113
- source: role.source,
114
- harness,
115
- command: role.command ?? "",
116
- shell: role.shell,
117
- env: role.env,
118
- externalModelRef: role.externalModelRef,
119
- thinkingLevel: role.thinkingLevel,
120
- maxWallTimeSec: role.maxWallTimeSec,
121
- systemPrompt: role.systemPrompt,
122
- task,
123
- workingDirectory: record.workingDirectory,
124
- artifactDir: record.artifactDir.replace(/[^/\\]+$/, toolCallId),
125
- purpose: record.purpose,
126
- taskId: record.taskId,
127
- leaseKey,
128
- resumeSessionId: record.sessionId,
129
- });
108
+ try {
109
+ await launchExternalRun({
110
+ runId: toolCallId,
111
+ channelId: options.channelId,
112
+ channelDir: options.channelDir,
113
+ label: `follow-up: ${task.slice(0, 80)}`,
114
+ agent: role.name,
115
+ source: role.source,
116
+ harness,
117
+ command: role.command ?? "",
118
+ shell: role.shell,
119
+ env: role.env,
120
+ externalModelRef: role.externalModelRef,
121
+ thinkingLevel: role.thinkingLevel,
122
+ maxWallTimeSec: role.maxWallTimeSec,
123
+ systemPrompt: role.systemPrompt,
124
+ task,
125
+ workingDirectory: record.workingDirectory,
126
+ artifactDir: record.artifactDir.replace(/[^/\\]+$/, toolCallId),
127
+ purpose: record.purpose,
128
+ taskId: record.taskId,
129
+ leaseKey,
130
+ resumeSessionId: record.sessionId,
131
+ mutates: role.mutates,
132
+ workspaceDir: options.workspaceDir ?? "",
133
+ securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
134
+ });
135
+ }
136
+ catch (error) {
137
+ // Until launchExternalRun has durably registered the run, no settlement authority owns
138
+ // this lease. Releasing here mirrors the initial subagent dispatch path and covers prompt,
139
+ // artifact, audit, invocation, and pre-spawn failures in follow_up.
140
+ releaseWorkspaceLease(leaseKey);
141
+ throw error;
142
+ }
130
143
  return {
131
144
  content: [
132
145
  {
@@ -38,6 +38,13 @@ export interface UsageSummary {
38
38
  byKind: Record<string, number>;
39
39
  byModel: Record<string, number>;
40
40
  byChannel: Record<string, number>;
41
+ /** Entries with `usageKnown === false` (e.g. the `exec` harness never reports tokens at all).
42
+ * Their `usage.total` is always 0 and never contributes to `totalTokens` — display this count
43
+ * rather than let those runs silently read as "0 tokens used". */
44
+ unknownUsageCount: number;
45
+ /** Entries with `costKnown === false` (e.g. `codex-cli`/`exec`, which report no cost field).
46
+ * Their `cost.total` is always 0 and never contributes to `totalCost` — same rationale. */
47
+ unknownCostCount: number;
41
48
  }
42
49
  export interface UsageSummaryQuery {
43
50
  since: Date;
@@ -71,8 +71,13 @@ export function createUsageLedger(options = {}) {
71
71
  // Record anything that consumed tokens, even at zero cost: a local model, or one whose
72
72
  // pricing metadata is missing, still has to show up somewhere or `/usage` reports nothing
73
73
  // at all and any spend guard built on this ledger fails open. Only a genuinely empty
74
- // entry (no tokens, no cost) is dropped as noise.
75
- if (!(entry.cost.total > 0) && !(entry.usage.total > 0))
74
+ // entry (no tokens, no cost, and nothing unknown either) is dropped as noise — an entry
75
+ // with `usageKnown`/`costKnown` false always has zero numeric totals by construction (the
76
+ // harness has nothing to report), so without this exemption every such run would be
77
+ // silently dropped instead of showing up as "unknown" (spec 040, T7).
78
+ const hasKnownSignal = entry.cost.total > 0 || entry.usage.total > 0;
79
+ const hasUnknownSignal = entry.usageKnown === false || entry.costKnown === false;
80
+ if (!hasKnownSignal && !hasUnknownSignal)
76
81
  return;
77
82
  if (!entry.channelId) {
78
83
  log.logWarning("Usage ledger entry missing channelId; recording as untracked", `kind=${entry.kind}`);
@@ -97,6 +102,8 @@ export function createUsageLedger(options = {}) {
97
102
  byKind: {},
98
103
  byModel: {},
99
104
  byChannel: {},
105
+ unknownUsageCount: 0,
106
+ unknownCostCount: 0,
100
107
  };
101
108
  for (const key of monthKeysBetween(query.since, until)) {
102
109
  for (const entry of await loadMonth(join(baseDir, `usage-${key}.jsonl`))) {
@@ -112,6 +119,12 @@ export function createUsageLedger(options = {}) {
112
119
  summary.byKind[entry.kind] = (summary.byKind[entry.kind] ?? 0) + cost;
113
120
  summary.byModel[entry.model] = (summary.byModel[entry.model] ?? 0) + cost;
114
121
  summary.byChannel[entry.channelId] = (summary.byChannel[entry.channelId] ?? 0) + cost;
122
+ // `undefined` (every entry recorded before this field existed) counts as known —
123
+ // backward compatibility for a ledger that predates this distinction.
124
+ if (entry.usageKnown === false)
125
+ summary.unknownUsageCount += 1;
126
+ if (entry.costKnown === false)
127
+ summary.unknownCostCount += 1;
115
128
  }
116
129
  }
117
130
  return summary;