@oyasmi/pipiclaw 0.9.0-beta.1 → 0.9.0-beta.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 (54) hide show
  1. package/dist/agent/channel-runner.d.ts +9 -0
  2. package/dist/agent/channel-runner.js +58 -4
  3. package/dist/agent/commands.js +11 -3
  4. package/dist/agent/job-manager.d.ts +6 -0
  5. package/dist/agent/job-manager.js +55 -1
  6. package/dist/agent/progress-formatter.js +3 -3
  7. package/dist/agent/run-queue.d.ts +10 -1
  8. package/dist/agent/run-queue.js +19 -2
  9. package/dist/agent/session-resource-gate.d.ts +17 -0
  10. package/dist/agent/session-resource-gate.js +33 -2
  11. package/dist/agent/status-render.js +1 -3
  12. package/dist/agent/types.d.ts +8 -0
  13. package/dist/runtime/bootstrap.d.ts +52 -0
  14. package/dist/runtime/bootstrap.js +192 -25
  15. package/dist/runtime/delivery.js +5 -5
  16. package/dist/runtime/dingtalk.d.ts +8 -0
  17. package/dist/runtime/durable-dispatch.d.ts +4 -0
  18. package/dist/runtime/durable-dispatch.js +16 -0
  19. package/dist/runtime/subagent-commands.d.ts +8 -6
  20. package/dist/runtime/subagent-commands.js +264 -64
  21. package/dist/security/logger.js +7 -0
  22. package/dist/shared/host-process.d.ts +7 -1
  23. package/dist/shared/host-process.js +7 -3
  24. package/dist/shared/jsonl-appender.d.ts +2 -0
  25. package/dist/shared/jsonl-appender.js +25 -13
  26. package/dist/shared/with-timeout.d.ts +14 -0
  27. package/dist/shared/with-timeout.js +38 -0
  28. package/dist/subagents/detached-discovery.d.ts +13 -0
  29. package/dist/subagents/detached-discovery.js +17 -0
  30. package/dist/subagents/external/run.d.ts +10 -0
  31. package/dist/subagents/external/run.js +47 -1
  32. package/dist/subagents/format.d.ts +12 -0
  33. package/dist/subagents/format.js +24 -0
  34. package/dist/subagents/runs.d.ts +38 -0
  35. package/dist/subagents/runs.js +171 -24
  36. package/dist/subagents/tool.d.ts +18 -0
  37. package/dist/subagents/tool.js +147 -89
  38. package/dist/tasks/control.d.ts +12 -0
  39. package/dist/tasks/control.js +20 -0
  40. package/dist/tasks/store.d.ts +21 -0
  41. package/dist/tasks/store.js +80 -0
  42. package/dist/tools/index.js +2 -0
  43. package/dist/tools/subagent-manage.d.ts +5 -0
  44. package/dist/tools/subagent-manage.js +68 -51
  45. package/dist/usage/ledger.d.ts +7 -0
  46. package/dist/usage/ledger.js +15 -2
  47. package/dist/usage/render.js +22 -0
  48. package/examples/sub-agents/README.md +12 -7
  49. package/examples/sub-agents/documenter.md +3 -3
  50. package/examples/sub-agents/git-committer.md +1 -1
  51. package/examples/sub-agents/reviewer.md +12 -6
  52. package/examples/sub-agents/verifier.md +5 -2
  53. package/examples/sub-agents/worker.md +1 -1
  54. package/package.json +1 -1
@@ -448,7 +448,10 @@ export function createSubAgentTool(options) {
448
448
  }
449
449
  const config = invocation.config;
450
450
  const returns = params.returns ?? "text";
451
- const runContext = await prepareRunContext(_toolCallId, params, options);
451
+ const runManager = (options.getRunManager ?? getSubAgentRunManager)(options.runtimeContext.channelId);
452
+ // A short, human-typeable id (spec 041) — never the dispatching tool call's own id, which
453
+ // on some providers is a long `call_<id>|fc_<id>` composite unreadable in a chat UI.
454
+ const runContext = await prepareRunContext(runManager.mintRunId(), params, options);
452
455
  // D9: an independent verifier checks against a target that isn't moving under it. It
453
456
  // never takes a lease itself, but a target with an active write lease is refused up
454
457
  // front — cheaper than explaining afterward why the attestation is worthless.
@@ -508,6 +511,9 @@ export function createSubAgentTool(options) {
508
511
  purpose: runContext.purpose,
509
512
  taskId: runContext.taskId,
510
513
  leaseKey,
514
+ mutates: config.mutates,
515
+ workspaceDir: options.workspaceDir,
516
+ securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
511
517
  });
512
518
  }
513
519
  catch (error) {
@@ -546,7 +552,14 @@ export function createSubAgentTool(options) {
546
552
  };
547
553
  }
548
554
  const scopedExecutor = new DirectoryExecutor(options.executor, runContext.workingDirectory);
549
- const apiKey = await options.resolveApiKey(config.model);
555
+ let apiKey;
556
+ try {
557
+ apiKey = await options.resolveApiKey(config.model);
558
+ }
559
+ catch (error) {
560
+ releaseWorkspaceLease(leaseKey);
561
+ throw error;
562
+ }
550
563
  const startedAt = Date.now();
551
564
  const usage = createEmptyUsageTotals();
552
565
  let assistantTurns = 0;
@@ -559,22 +572,29 @@ export function createSubAgentTool(options) {
559
572
  /** True once the sync grace window has elapsed and a "still running" placeholder has been returned. */
560
573
  let detached = false;
561
574
  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
- });
575
+ try {
576
+ await runManager.register({
577
+ runId: runContext.runId,
578
+ channelId: options.runtimeContext.channelId,
579
+ runtime: "internal",
580
+ agent: config.name,
581
+ label: params.label,
582
+ source: config.source,
583
+ tools: [...config.tools],
584
+ model: formatModelReference(config.model),
585
+ purpose: runContext.purpose,
586
+ taskId: runContext.taskId,
587
+ workingDirectory: runContext.workingDirectory,
588
+ artifactDir: runContext.artifactDir,
589
+ leaseKey,
590
+ });
591
+ }
592
+ catch (error) {
593
+ // Until the durable running record exists, setup still owns the lease. A channel/host
594
+ // admission rejection or required persist failure must leave no invisible writer lock.
595
+ releaseWorkspaceLease(leaseKey);
596
+ throw error;
597
+ }
578
598
  const emitUpdate = (text) => {
579
599
  // Once detached, execute() has already returned to the SDK; nothing is listening
580
600
  // for further progress on this (from its view, finished) tool call.
@@ -590,71 +610,109 @@ export function createSubAgentTool(options) {
590
610
  details: createDetails(config, runContext, usage, assistantTurns, toolCalls, Date.now() - startedAt, Boolean(failureReason), failureReason),
591
611
  });
592
612
  };
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,
613
+ let worker;
614
+ let wallClockTimer;
615
+ let unsubscribe;
616
+ let verifierGitStateBefore;
617
+ let verifierSubjectBefore;
618
+ try {
619
+ const availableTools = (options.buildTools ?? buildSubagentTools)(scopedExecutor, config.bashTimeoutSec, options, runContext);
620
+ verifierGitStateBefore =
621
+ runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
622
+ verifierSubjectBefore =
623
+ runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
624
+ worker =
625
+ options.createWorker?.({
626
+ subAgent: config,
627
+ apiKey,
606
628
  tools: filterToolsByName(availableTools, config.tools),
607
- },
608
- convertToLlm,
609
- getApiKey: async () => apiKey,
610
- streamFn: streamSimple,
629
+ }) ??
630
+ new Agent({
631
+ initialState: {
632
+ systemPrompt: config.systemPrompt,
633
+ model: config.model,
634
+ thinkingLevel: config.thinkingLevel,
635
+ tools: filterToolsByName(availableTools, config.tools),
636
+ },
637
+ convertToLlm,
638
+ getApiKey: async () => apiKey,
639
+ streamFn: streamSimple,
640
+ });
641
+ runManager.registerCancelHandle(runContext.runId, () => {
642
+ externallyCancelled = true;
643
+ worker?.abort();
611
644
  });
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})`;
645
+ wallClockTimer = setTimeout(() => {
646
+ failureReason = `Wall time budget exceeded (${config.maxWallTimeSec}s)`;
647
+ budgetExceeded = true;
648
+ worker?.abort();
649
+ }, config.maxWallTimeSec * 1000);
650
+ unsubscribe = worker.subscribe((event) => {
651
+ if (event.type === "message_end" && isAssistantMessage(event.message)) {
652
+ assistantTurns++;
653
+ const messageUsage = event.message.usage;
654
+ usage.input += messageUsage.input;
655
+ usage.output += messageUsage.output;
656
+ usage.cacheRead += messageUsage.cacheRead;
657
+ usage.cacheWrite += messageUsage.cacheWrite;
658
+ usage.total += messageUsage.totalTokens;
659
+ usage.cost.input += messageUsage.cost.input;
660
+ usage.cost.output += messageUsage.cost.output;
661
+ usage.cost.cacheRead += messageUsage.cost.cacheRead;
662
+ usage.cost.cacheWrite += messageUsage.cost.cacheWrite;
663
+ usage.cost.total += messageUsage.cost.total;
664
+ }
665
+ if (event.type === "tool_execution_start") {
666
+ toolCalls++;
667
+ const label = extractLabelFromArgs(event.args) || event.toolName;
668
+ emitUpdate(formatStatus(config.name, label));
669
+ if (toolCalls > config.maxToolCalls) {
670
+ failureReason = `Tool call budget exceeded (${config.maxToolCalls})`;
671
+ budgetExceeded = true;
672
+ emitUpdate(formatStatus(config.name, "tool budget reached"));
673
+ worker?.abort();
674
+ }
675
+ }
676
+ if (event.type === "turn_end" &&
677
+ isAssistantMessage(event.message) &&
678
+ event.toolResults.length > 0 &&
679
+ assistantTurns >= config.maxTurns) {
680
+ failureReason = `Turn budget exceeded (${config.maxTurns})`;
642
681
  budgetExceeded = true;
643
- emitUpdate(formatStatus(config.name, "tool budget reached"));
644
- worker.abort();
682
+ emitUpdate(formatStatus(config.name, "turn budget reached"));
683
+ worker?.abort();
645
684
  }
685
+ });
686
+ emitUpdate(formatStatus(config.name, "started"));
687
+ }
688
+ catch (error) {
689
+ unsubscribe?.();
690
+ if (wallClockTimer)
691
+ clearTimeout(wallClockTimer);
692
+ runManager.clearCancelHandle(runContext.runId);
693
+ try {
694
+ worker?.abort();
646
695
  }
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();
696
+ catch {
697
+ // Preserve the setup error; settlement below is the lifecycle authority.
655
698
  }
656
- });
657
- emitUpdate(formatStatus(config.name, "started"));
699
+ const setupError = error instanceof Error ? error : new Error(String(error));
700
+ await runManager.settle(runContext.runId, {
701
+ status: "failed",
702
+ failureReason: setupError.message,
703
+ usage,
704
+ usageKnown: true,
705
+ costKnown: true,
706
+ turns: assistantTurns,
707
+ toolCalls,
708
+ durationMs: Date.now() - startedAt,
709
+ outputText: "",
710
+ }, { announce: false });
711
+ throw setupError;
712
+ }
713
+ const activeWorker = worker;
714
+ const activeUnsubscribe = unsubscribe;
715
+ const activeWallClockTimer = wallClockTimer;
658
716
  /**
659
717
  * Runs the worker to completion, including the D6 convergence turn, and returns the
660
718
  * tool result plus the data `runs.ts` needs to settle. Rejects only for the single
@@ -664,24 +722,24 @@ export function createSubAgentTool(options) {
664
722
  async function runToCompletion() {
665
723
  try {
666
724
  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();
725
+ await activeWorker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext, returns));
726
+ await activeWorker.waitForIdle();
669
727
  // D6: a self-inflicted budget abort gets one tool-free turn to converge on a
670
728
  // conclusion instead of discarding the work outright. An explicit cancel skips
671
729
  // this — the model asked this run to stop now, not to wrap up.
672
730
  if (budgetExceeded && !externallyCancelled) {
673
- clearTimeout(wallClockTimer);
731
+ clearTimeout(activeWallClockTimer);
674
732
  emitUpdate(formatStatus(config.name, "converging on budget exhaustion"));
675
- const preConvergenceMessageCount = worker.state.messages.length;
676
- worker.state.tools = [];
733
+ const preConvergenceMessageCount = activeWorker.state.messages.length;
734
+ activeWorker.state.tools = [];
677
735
  let convergenceTimedOut = false;
678
736
  const convergenceTimer = setTimeout(() => {
679
737
  convergenceTimedOut = true;
680
- worker.abort();
738
+ activeWorker.abort();
681
739
  }, options.convergenceWallClockMs ?? CONVERGENCE_WALL_CLOCK_MS);
682
740
  try {
683
- await worker.prompt(CONVERGENCE_PROMPT);
684
- await worker.waitForIdle();
741
+ await activeWorker.prompt(CONVERGENCE_PROMPT);
742
+ await activeWorker.waitForIdle();
685
743
  }
686
744
  catch {
687
745
  // Best effort: fall through to whatever worker.state.messages holds.
@@ -692,15 +750,15 @@ export function createSubAgentTool(options) {
692
750
  if (convergenceTimedOut) {
693
751
  // Revert to the pre-D6 behavior: drop the (aborted, possibly partial)
694
752
  // convergence turn and fall back to whatever came before it.
695
- worker.state.messages = worker.state.messages.slice(0, preConvergenceMessageCount);
753
+ activeWorker.state.messages = activeWorker.state.messages.slice(0, preConvergenceMessageCount);
696
754
  }
697
755
  }
698
756
  }
699
757
  finally {
700
- unsubscribe();
701
- clearTimeout(wallClockTimer);
758
+ activeUnsubscribe();
759
+ clearTimeout(activeWallClockTimer);
702
760
  }
703
- const lastAssistantMessage = getLastAssistantMessage(worker.state.messages);
761
+ const lastAssistantMessage = getLastAssistantMessage(activeWorker.state.messages);
704
762
  const durationMs = Date.now() - startedAt;
705
763
  if (!lastAssistantMessage) {
706
764
  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 {};