@oyasmi/pipiclaw 0.8.11 → 0.9.0-beta.1
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.
- package/dist/agent/channel-runner.d.ts +3 -0
- package/dist/agent/channel-runner.js +9 -0
- package/dist/agent/commands.d.ts +1 -1
- package/dist/agent/commands.js +9 -0
- package/dist/agent/job-manager.d.ts +5 -3
- package/dist/agent/job-manager.js +8 -5
- package/dist/agent/prompt/sections.js +46 -7
- package/dist/agent/prompt/types.d.ts +9 -0
- package/dist/agent/session-events.js +7 -42
- package/dist/agent/types.d.ts +4 -0
- package/dist/playbooks/agent-delegation.md +46 -21
- package/dist/playbooks/runtime-orientation.md +2 -2
- package/dist/runtime/bootstrap.js +45 -1
- package/dist/runtime/dingtalk.d.ts +1 -0
- package/dist/runtime/dingtalk.js +3 -0
- package/dist/runtime/store.d.ts +7 -0
- package/dist/runtime/subagent-commands.d.ts +15 -0
- package/dist/runtime/subagent-commands.js +122 -0
- package/dist/runtime/task-commands.js +5 -1
- package/dist/security/logger.js +3 -1
- package/dist/security/types.d.ts +17 -1
- package/dist/shared/host-process.d.ts +15 -0
- package/dist/shared/host-process.js +40 -0
- package/dist/shared/shell-words.d.ts +9 -0
- package/dist/shared/shell-words.js +52 -0
- package/dist/subagents/discovery.d.ts +42 -1
- package/dist/subagents/discovery.js +302 -69
- package/dist/subagents/external/claude-code.d.ts +2 -0
- package/dist/subagents/external/claude-code.js +152 -0
- package/dist/subagents/external/codex-cli.d.ts +2 -0
- package/dist/subagents/external/codex-cli.js +133 -0
- package/dist/subagents/external/exec.d.ts +2 -0
- package/dist/subagents/external/exec.js +38 -0
- package/dist/subagents/external/harness.d.ts +102 -0
- package/dist/subagents/external/harness.js +76 -0
- package/dist/subagents/external/registry.d.ts +2 -0
- package/dist/subagents/external/registry.js +11 -0
- package/dist/subagents/external/run.d.ts +39 -0
- package/dist/subagents/external/run.js +220 -0
- package/dist/subagents/runs.d.ts +216 -0
- package/dist/subagents/runs.js +522 -0
- package/dist/subagents/tool.d.ts +8 -0
- package/dist/subagents/tool.js +350 -124
- package/dist/subagents/workspace-lease.d.ts +36 -0
- package/dist/subagents/workspace-lease.js +48 -0
- package/dist/tasks/artifact-subject.js +50 -2
- package/dist/tasks/verification.d.ts +8 -0
- package/dist/tasks/verification.js +10 -2
- package/dist/tools/index.d.ts +1 -1
- package/dist/tools/index.js +10 -1
- package/dist/tools/registry.js +1 -0
- package/dist/tools/subagent-manage.d.ts +18 -0
- package/dist/tools/subagent-manage.js +141 -0
- package/dist/tools/tool-details.d.ts +1 -1
- package/dist/tui/app.js +2 -0
- package/dist/tui/commands.d.ts +1 -0
- package/dist/tui/commands.js +2 -0
- package/dist/tui/turn-controller.d.ts +1 -0
- package/dist/tui/turn-controller.js +1 -0
- package/dist/usage/ledger.d.ts +6 -0
- package/examples/sub-agents/README.md +59 -12
- package/examples/sub-agents/builder-hard.md +45 -0
- package/examples/sub-agents/builder.md +41 -0
- package/examples/sub-agents/documenter.md +53 -0
- package/examples/sub-agents/log-sifter.md +43 -0
- package/examples/sub-agents/planner.md +42 -0
- package/examples/sub-agents/reviewer.md +33 -39
- package/examples/sub-agents/scout.md +31 -0
- package/examples/sub-agents/verifier.md +29 -36
- package/examples/sub-agents/worker.md +36 -0
- package/package.json +1 -1
- package/examples/sub-agents/researcher.md +0 -41
package/dist/subagents/tool.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { existsSync, statSync } from "node:fs";
|
|
2
|
-
import { mkdir
|
|
2
|
+
import { mkdir } from "node:fs/promises";
|
|
3
3
|
import { isAbsolute, join, relative, resolve } from "node:path";
|
|
4
4
|
import { Agent } from "@earendil-works/pi-agent-core";
|
|
5
5
|
import { streamSimple } from "@earendil-works/pi-ai/compat";
|
|
6
6
|
import { convertToLlm } from "@earendil-works/pi-coding-agent";
|
|
7
7
|
import { Type } from "typebox";
|
|
8
|
+
import * as log from "../log.js";
|
|
8
9
|
import { getChannelHistoryPath, getChannelMemoryPath, getChannelSessionPath, readChannelSession, } from "../memory/files.js";
|
|
9
10
|
import { recallRelevantMemory } from "../memory/recall.js";
|
|
10
11
|
import { formatModelReference } from "../models/utils.js";
|
|
@@ -12,12 +13,15 @@ import { DEFAULT_SECURITY_CONFIG } from "../security/config.js";
|
|
|
12
13
|
import { formatLocalTime } from "../shared/local-time.js";
|
|
13
14
|
import { splitH1Sections } from "../shared/markdown-sections.js";
|
|
14
15
|
import { clipTextByPromptUnits, countPromptUnits } from "../shared/prompt-units.js";
|
|
15
|
-
import { clipText, extractAssistantText, extractLabelFromArgs } from "../shared/text-utils.js";
|
|
16
|
+
import { clipText, errorMessage, extractAssistantText, extractLabelFromArgs } from "../shared/text-utils.js";
|
|
16
17
|
import { workspaceSubjectHash } from "../tasks/artifact-subject.js";
|
|
17
18
|
import { readStoredTask } from "../tasks/store.js";
|
|
18
19
|
import { parseVerificationVerdict, writeVerificationAttestation } from "../tasks/verification.js";
|
|
19
20
|
import { buildToolSet } from "../tools/registry.js";
|
|
20
|
-
import { formatSubAgentList, resolveSubAgentConfig, validateSubAgentTask, } from "./discovery.js";
|
|
21
|
+
import { formatSubAgentList, resolveSubAgentConfig, validateSubAgentTask, withSubAgentsDirWriteDeny, } from "./discovery.js";
|
|
22
|
+
import { launchExternalRun } from "./external/run.js";
|
|
23
|
+
import { getSubAgentRunManager, SYNC_GRACE_MS } from "./runs.js";
|
|
24
|
+
import { acquireWorkspaceLease, findWorkspaceLeaseHolder, formatWorkspaceLeaseConflict, releaseWorkspaceLease, } from "./workspace-lease.js";
|
|
21
25
|
const subagentSchema = Type.Object({
|
|
22
26
|
label: Type.String({ description: "Brief description of what this sub-agent task does (shown to user)" }),
|
|
23
27
|
agent: Type.Optional(Type.String({ description: "Name of a configured sub-agent from workspaceDir/sub-agents/" })),
|
|
@@ -198,13 +202,14 @@ function parseArtifactMarker(output) {
|
|
|
198
202
|
* whether it fits the reply budget. What comes back to the parent is capped at
|
|
199
203
|
* MAX_SUBAGENT_RESULT_UNITS; a reply over budget is truncated with a pointer to the file
|
|
200
204
|
* a chatty sub-agent can no longer blow out the parent's context.
|
|
205
|
+
*
|
|
206
|
+
* The file itself is written by `SubAgentRunManager.settle()` — the one settlement point both
|
|
207
|
+
* runtimes share (spec 040 D1) — which always runs before this call's reply reaches the parent.
|
|
208
|
+
* This function only needs the path, to point at it.
|
|
201
209
|
*/
|
|
202
|
-
|
|
210
|
+
function finalizeSubAgentOutput(runContext, finalText, returns) {
|
|
203
211
|
const trimmed = finalText.trim();
|
|
204
212
|
const outputPath = join(runContext.artifactDir, "output.md");
|
|
205
|
-
if (trimmed) {
|
|
206
|
-
await writeFile(outputPath, finalText, "utf-8");
|
|
207
|
-
}
|
|
208
213
|
let artifactPath;
|
|
209
214
|
if (returns === "artifact" && trimmed) {
|
|
210
215
|
const filename = parseArtifactMarker(trimmed);
|
|
@@ -234,19 +239,22 @@ async function finalizeSubAgentOutput(runContext, finalText, returns) {
|
|
|
234
239
|
* received — a stray write/edit here would race the shared memory serial queue
|
|
235
240
|
* (channel-maintenance-queue) and silently corrupt durable memory.
|
|
236
241
|
*/
|
|
237
|
-
function withSubagentMemoryWriteDeny(securityConfig, channelDir) {
|
|
242
|
+
function withSubagentMemoryWriteDeny(securityConfig, channelDir, workspaceDir) {
|
|
238
243
|
const protectedPaths = [
|
|
239
244
|
getChannelMemoryPath(channelDir),
|
|
240
245
|
getChannelHistoryPath(channelDir),
|
|
241
246
|
getChannelSessionPath(channelDir),
|
|
242
247
|
];
|
|
243
|
-
|
|
248
|
+
// The role directory gets the same structural denial (spec 040, D8.1): a sub-agent's write/edit
|
|
249
|
+
// tools are exactly as capable of writing a self-authorizing `runtime: external` role file as
|
|
250
|
+
// the main agent's are.
|
|
251
|
+
return withSubAgentsDirWriteDeny({
|
|
244
252
|
...securityConfig,
|
|
245
253
|
pathGuard: {
|
|
246
254
|
...securityConfig.pathGuard,
|
|
247
255
|
writeDeny: [...securityConfig.pathGuard.writeDeny, ...protectedPaths],
|
|
248
256
|
},
|
|
249
|
-
};
|
|
257
|
+
}, workspaceDir);
|
|
250
258
|
}
|
|
251
259
|
/**
|
|
252
260
|
* Build a sub-agent's tool set from the shared tool registry, filtered to tools flagged
|
|
@@ -254,7 +262,7 @@ function withSubagentMemoryWriteDeny(securityConfig, channelDir) {
|
|
|
254
262
|
* (rooted at the sub-agent workspace) and their own per-invocation bash timeout.
|
|
255
263
|
*/
|
|
256
264
|
function buildSubagentTools(executor, bashTimeoutSec, options, runContext) {
|
|
257
|
-
const securityConfig = withSubagentMemoryWriteDeny(options.securityConfig ?? DEFAULT_SECURITY_CONFIG, options.channelDir);
|
|
265
|
+
const securityConfig = withSubagentMemoryWriteDeny(options.securityConfig ?? DEFAULT_SECURITY_CONFIG, options.channelDir, options.workspaceDir);
|
|
258
266
|
return buildToolSet({
|
|
259
267
|
executor,
|
|
260
268
|
securityConfig,
|
|
@@ -401,17 +409,17 @@ function createDetails(config, runContext, usage, turns, toolCalls, durationMs,
|
|
|
401
409
|
resultTruncated: extras?.resultTruncated ?? false,
|
|
402
410
|
};
|
|
403
411
|
}
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
412
|
+
/**
|
|
413
|
+
* A run's lifecycle is deliberately unlinked from the tool call's `AbortSignal` (spec 040, D2):
|
|
414
|
+
* `/stop` ends the current turn but no longer kills an in-flight delegation, matching background
|
|
415
|
+
* jobs. Stopping a run is now an explicit decision (`subagent_manage op=cancel`), not a side
|
|
416
|
+
* effect of stopping something else.
|
|
417
|
+
*/
|
|
418
|
+
function sleep(ms) {
|
|
419
|
+
return new Promise((resolve) => {
|
|
420
|
+
const timer = setTimeout(resolve, ms);
|
|
421
|
+
timer.unref?.();
|
|
422
|
+
});
|
|
415
423
|
}
|
|
416
424
|
export function createSubAgentTool(options) {
|
|
417
425
|
return {
|
|
@@ -420,6 +428,9 @@ export function createSubAgentTool(options) {
|
|
|
420
428
|
description: "Delegate a task to a sub-agent with an isolated context. Default path: pass an inline systemPrompt (plus optional tools/model) to define a temporary sub-agent — no configured agent is required. You may instead name a configured sub-agent via `agent`; workspaceDir/sub-agents/ may be empty on a given install, which does not block inline delegation. Execution budgets come from `effort` presets and context injection from `context`; both have safe defaults, so state the task well and leave them alone unless you have a reason. Sub-agents never receive the subagent tool, so they cannot create nested agents.",
|
|
421
429
|
parameters: subagentSchema,
|
|
422
430
|
execute: async (_toolCallId, params, signal, onUpdate) => {
|
|
431
|
+
if (signal?.aborted) {
|
|
432
|
+
throw new Error("Sub-agent aborted");
|
|
433
|
+
}
|
|
423
434
|
const availableModels = options.getAvailableModels();
|
|
424
435
|
const discovery = options.getSubAgentDiscovery?.() ?? {
|
|
425
436
|
directory: `${options.workspaceDir}/sub-agents`,
|
|
@@ -438,6 +449,102 @@ export function createSubAgentTool(options) {
|
|
|
438
449
|
const config = invocation.config;
|
|
439
450
|
const returns = params.returns ?? "text";
|
|
440
451
|
const runContext = await prepareRunContext(_toolCallId, params, options);
|
|
452
|
+
// D9: an independent verifier checks against a target that isn't moving under it. It
|
|
453
|
+
// never takes a lease itself, but a target with an active write lease is refused up
|
|
454
|
+
// front — cheaper than explaining afterward why the attestation is worthless.
|
|
455
|
+
if (runContext.purpose === "verify") {
|
|
456
|
+
// A role that admits it writes cannot also be the checker, and `exec` has no protocol
|
|
457
|
+
// terminal to prove it even ran to completion — both are hard "no"s, not advisories.
|
|
458
|
+
if (config.mutates === "write") {
|
|
459
|
+
throw new Error(`Sub-agent "${config.name}" declares mutates: write and cannot be used for purpose=verify.`);
|
|
460
|
+
}
|
|
461
|
+
if (config.runtime === "external" && config.harness === "exec") {
|
|
462
|
+
throw new Error(`Sub-agent "${config.name}" uses the exec harness, which has no protocol terminal and cannot be used for purpose=verify.`);
|
|
463
|
+
}
|
|
464
|
+
const holder = findWorkspaceLeaseHolder(runContext.workingDirectory);
|
|
465
|
+
if (holder) {
|
|
466
|
+
throw new Error(`Cannot verify "${runContext.workingDirectory}": ${formatWorkspaceLeaseConflict(holder)}`);
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
// Admission: a write-mutating run takes an exclusive workspace lease before it is even
|
|
470
|
+
// registered (spec 040, D10.1) — a rejected delegation should never count as "started".
|
|
471
|
+
// Read runs and purpose=verify never take one. Shared by both runtimes.
|
|
472
|
+
let leaseKey;
|
|
473
|
+
if (config.mutates === "write" && runContext.purpose !== "verify") {
|
|
474
|
+
const lease = acquireWorkspaceLease({
|
|
475
|
+
runId: runContext.runId,
|
|
476
|
+
channelId: options.runtimeContext.channelId,
|
|
477
|
+
workingDirectory: runContext.workingDirectory,
|
|
478
|
+
});
|
|
479
|
+
if (!lease.ok) {
|
|
480
|
+
throw new Error(formatWorkspaceLeaseConflict(lease.heldBy));
|
|
481
|
+
}
|
|
482
|
+
leaseKey = lease.leaseKey;
|
|
483
|
+
}
|
|
484
|
+
if (config.runtime === "external") {
|
|
485
|
+
if (!config.harness) {
|
|
486
|
+
releaseWorkspaceLease(leaseKey);
|
|
487
|
+
throw new Error(`Sub-agent "${config.name}" has runtime: external but no harness configured.`);
|
|
488
|
+
}
|
|
489
|
+
try {
|
|
490
|
+
await launchExternalRun({
|
|
491
|
+
runId: runContext.runId,
|
|
492
|
+
channelId: options.runtimeContext.channelId,
|
|
493
|
+
channelDir: options.channelDir,
|
|
494
|
+
label: params.label,
|
|
495
|
+
agent: config.name,
|
|
496
|
+
source: config.source,
|
|
497
|
+
harness: config.harness,
|
|
498
|
+
command: config.command ?? "",
|
|
499
|
+
shell: config.shell,
|
|
500
|
+
env: config.env,
|
|
501
|
+
externalModelRef: config.externalModelRef,
|
|
502
|
+
thinkingLevel: config.thinkingLevel,
|
|
503
|
+
maxWallTimeSec: config.maxWallTimeSec,
|
|
504
|
+
systemPrompt: config.systemPrompt,
|
|
505
|
+
task: params.task,
|
|
506
|
+
workingDirectory: runContext.workingDirectory,
|
|
507
|
+
artifactDir: runContext.artifactDir,
|
|
508
|
+
purpose: runContext.purpose,
|
|
509
|
+
taskId: runContext.taskId,
|
|
510
|
+
leaseKey,
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
catch (error) {
|
|
514
|
+
releaseWorkspaceLease(leaseKey);
|
|
515
|
+
throw error;
|
|
516
|
+
}
|
|
517
|
+
// D2: external's sync grace window is always 0 — always the dispatched placeholder,
|
|
518
|
+
// never an inline wait. The run keeps going in the background and wakes the channel.
|
|
519
|
+
return {
|
|
520
|
+
content: [
|
|
521
|
+
{
|
|
522
|
+
type: "text",
|
|
523
|
+
text: `[Dispatched] runId=${runContext.runId}, agent ${config.name} (external, ${config.harness}), working directory ${runContext.workingDirectory}.\n` +
|
|
524
|
+
"Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
|
|
525
|
+
"Do not dispatch it again or poll for it now -- end this turn. If it belongs to a task, mark it waiting with task_manage.",
|
|
526
|
+
},
|
|
527
|
+
],
|
|
528
|
+
details: {
|
|
529
|
+
kind: "subagent",
|
|
530
|
+
agent: config.name,
|
|
531
|
+
source: config.source,
|
|
532
|
+
model: config.externalModelRef ?? "unknown",
|
|
533
|
+
tools: [],
|
|
534
|
+
turns: 0,
|
|
535
|
+
toolCalls: 0,
|
|
536
|
+
durationMs: 0,
|
|
537
|
+
failed: false,
|
|
538
|
+
usage: createEmptyUsageTotals(),
|
|
539
|
+
runId: runContext.runId,
|
|
540
|
+
purpose: runContext.purpose,
|
|
541
|
+
taskId: runContext.taskId,
|
|
542
|
+
artifactDir: runContext.artifactDir,
|
|
543
|
+
resultTruncated: false,
|
|
544
|
+
dispatched: true,
|
|
545
|
+
},
|
|
546
|
+
};
|
|
547
|
+
}
|
|
441
548
|
const scopedExecutor = new DirectoryExecutor(options.executor, runContext.workingDirectory);
|
|
442
549
|
const apiKey = await options.resolveApiKey(config.model);
|
|
443
550
|
const startedAt = Date.now();
|
|
@@ -445,10 +552,34 @@ export function createSubAgentTool(options) {
|
|
|
445
552
|
let assistantTurns = 0;
|
|
446
553
|
let toolCalls = 0;
|
|
447
554
|
let failureReason;
|
|
448
|
-
/** Set alongside failureReason only for the three self-inflicted budget aborts,
|
|
555
|
+
/** Set alongside failureReason only for the three self-inflicted budget aborts, distinct from an explicit cancel. */
|
|
449
556
|
let budgetExceeded = false;
|
|
557
|
+
/** Set only by the `subagent_manage op=cancel` handle registered below — a real stop, unlike a budget abort. */
|
|
558
|
+
let externallyCancelled = false;
|
|
559
|
+
/** True once the sync grace window has elapsed and a "still running" placeholder has been returned. */
|
|
560
|
+
let detached = false;
|
|
450
561
|
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
|
+
});
|
|
451
578
|
const emitUpdate = (text) => {
|
|
579
|
+
// Once detached, execute() has already returned to the SDK; nothing is listening
|
|
580
|
+
// for further progress on this (from its view, finished) tool call.
|
|
581
|
+
if (detached)
|
|
582
|
+
return;
|
|
452
583
|
const nextText = text.trim();
|
|
453
584
|
if (!nextText || nextText === lastUpdateText) {
|
|
454
585
|
return;
|
|
@@ -478,8 +609,10 @@ export function createSubAgentTool(options) {
|
|
|
478
609
|
getApiKey: async () => apiKey,
|
|
479
610
|
streamFn: streamSimple,
|
|
480
611
|
});
|
|
481
|
-
|
|
482
|
-
|
|
612
|
+
runManager.registerCancelHandle(runContext.runId, () => {
|
|
613
|
+
externallyCancelled = true;
|
|
614
|
+
worker.abort();
|
|
615
|
+
});
|
|
483
616
|
const wallClockTimer = setTimeout(() => {
|
|
484
617
|
failureReason = `Wall time budget exceeded (${config.maxWallTimeSec}s)`;
|
|
485
618
|
budgetExceeded = true;
|
|
@@ -522,124 +655,217 @@ export function createSubAgentTool(options) {
|
|
|
522
655
|
}
|
|
523
656
|
});
|
|
524
657
|
emitUpdate(formatStatus(config.name, "started"));
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
658
|
+
/**
|
|
659
|
+
* Runs the worker to completion, including the D6 convergence turn, and returns the
|
|
660
|
+
* tool result plus the data `runs.ts` needs to settle. Rejects only for the single
|
|
661
|
+
* fatal case (no assistant message at all) — every other outcome, including a budget
|
|
662
|
+
* abort or explicit cancel, is a normal (if failed) result.
|
|
663
|
+
*/
|
|
664
|
+
async function runToCompletion() {
|
|
531
665
|
try {
|
|
532
666
|
const contextualBlocks = await buildContextualBlocks(params.task, config, options, currentModel);
|
|
533
667
|
await worker.prompt(buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext, returns));
|
|
534
668
|
await worker.waitForIdle();
|
|
669
|
+
// D6: a self-inflicted budget abort gets one tool-free turn to converge on a
|
|
670
|
+
// conclusion instead of discarding the work outright. An explicit cancel skips
|
|
671
|
+
// this — the model asked this run to stop now, not to wrap up.
|
|
672
|
+
if (budgetExceeded && !externallyCancelled) {
|
|
673
|
+
clearTimeout(wallClockTimer);
|
|
674
|
+
emitUpdate(formatStatus(config.name, "converging on budget exhaustion"));
|
|
675
|
+
const preConvergenceMessageCount = worker.state.messages.length;
|
|
676
|
+
worker.state.tools = [];
|
|
677
|
+
let convergenceTimedOut = false;
|
|
678
|
+
const convergenceTimer = setTimeout(() => {
|
|
679
|
+
convergenceTimedOut = true;
|
|
680
|
+
worker.abort();
|
|
681
|
+
}, options.convergenceWallClockMs ?? CONVERGENCE_WALL_CLOCK_MS);
|
|
682
|
+
try {
|
|
683
|
+
await worker.prompt(CONVERGENCE_PROMPT);
|
|
684
|
+
await worker.waitForIdle();
|
|
685
|
+
}
|
|
686
|
+
catch {
|
|
687
|
+
// Best effort: fall through to whatever worker.state.messages holds.
|
|
688
|
+
}
|
|
689
|
+
finally {
|
|
690
|
+
clearTimeout(convergenceTimer);
|
|
691
|
+
}
|
|
692
|
+
if (convergenceTimedOut) {
|
|
693
|
+
// Revert to the pre-D6 behavior: drop the (aborted, possibly partial)
|
|
694
|
+
// convergence turn and fall back to whatever came before it.
|
|
695
|
+
worker.state.messages = worker.state.messages.slice(0, preConvergenceMessageCount);
|
|
696
|
+
}
|
|
697
|
+
}
|
|
535
698
|
}
|
|
536
699
|
finally {
|
|
537
|
-
|
|
538
|
-
}
|
|
539
|
-
// D6: a self-inflicted budget abort gets one tool-free turn to converge on a
|
|
540
|
-
// conclusion instead of discarding the work outright. A parent-driven /stop
|
|
541
|
-
// (childController already aborted) skips this — the user asked to stop now.
|
|
542
|
-
if (budgetExceeded && !childController.signal.aborted) {
|
|
700
|
+
unsubscribe();
|
|
543
701
|
clearTimeout(wallClockTimer);
|
|
544
|
-
emitUpdate(formatStatus(config.name, "converging on budget exhaustion"));
|
|
545
|
-
const preConvergenceMessageCount = worker.state.messages.length;
|
|
546
|
-
worker.state.tools = [];
|
|
547
|
-
let convergenceTimedOut = false;
|
|
548
|
-
const convergenceTimer = setTimeout(() => {
|
|
549
|
-
convergenceTimedOut = true;
|
|
550
|
-
worker.abort();
|
|
551
|
-
}, options.convergenceWallClockMs ?? CONVERGENCE_WALL_CLOCK_MS);
|
|
552
|
-
childController.signal.addEventListener("abort", abortWorker, { once: true });
|
|
553
|
-
try {
|
|
554
|
-
await worker.prompt(CONVERGENCE_PROMPT);
|
|
555
|
-
await worker.waitForIdle();
|
|
556
|
-
}
|
|
557
|
-
catch {
|
|
558
|
-
// Best effort: fall through to whatever worker.state.messages holds.
|
|
559
|
-
}
|
|
560
|
-
finally {
|
|
561
|
-
childController.signal.removeEventListener("abort", abortWorker);
|
|
562
|
-
clearTimeout(convergenceTimer);
|
|
563
|
-
}
|
|
564
|
-
if (convergenceTimedOut) {
|
|
565
|
-
// Revert to the pre-D6 behavior: drop the (aborted, possibly partial)
|
|
566
|
-
// convergence turn and fall back to whatever came before it.
|
|
567
|
-
worker.state.messages = worker.state.messages.slice(0, preConvergenceMessageCount);
|
|
568
|
-
}
|
|
569
702
|
}
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
clearTimeout(wallClockTimer);
|
|
575
|
-
}
|
|
576
|
-
if (signal?.aborted) {
|
|
577
|
-
throw new Error("Sub-agent aborted");
|
|
578
|
-
}
|
|
579
|
-
const lastAssistantMessage = getLastAssistantMessage(worker.state.messages);
|
|
580
|
-
const durationMs = Date.now() - startedAt;
|
|
581
|
-
if (!lastAssistantMessage) {
|
|
582
|
-
failureReason = failureReason || "Sub-agent returned no assistant message";
|
|
583
|
-
emitUpdate(formatStatus(config.name, "failed"));
|
|
584
|
-
throw new Error(`Sub-agent ${config.name} failed: ${failureReason}`);
|
|
585
|
-
}
|
|
586
|
-
const finalText = extractAssistantText(lastAssistantMessage);
|
|
587
|
-
const effectiveFailureReason = failureReason ||
|
|
588
|
-
(lastAssistantMessage.stopReason === "error" || lastAssistantMessage.stopReason === "aborted"
|
|
589
|
-
? lastAssistantMessage.errorMessage || `Sub-agent stopped with ${lastAssistantMessage.stopReason}`
|
|
590
|
-
: undefined);
|
|
591
|
-
const verifierGitStateAfter = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
|
|
592
|
-
const verifierSubjectAfter = runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
|
|
593
|
-
const workspaceChanged = runContext.purpose === "verify" &&
|
|
594
|
-
(verifierSubjectBefore !== undefined && verifierSubjectAfter !== undefined
|
|
595
|
-
? verifierSubjectBefore !== verifierSubjectAfter
|
|
596
|
-
: verifierGitStateBefore !== undefined &&
|
|
597
|
-
verifierGitStateAfter !== undefined &&
|
|
598
|
-
verifierGitStateBefore !== verifierGitStateAfter);
|
|
599
|
-
const declaredVerdict = runContext.purpose === "verify" ? parseVerificationVerdict(finalText) : undefined;
|
|
600
|
-
const verificationVerdict = runContext.purpose === "verify"
|
|
601
|
-
? declaredVerdict === "pass" && !effectiveFailureReason && !workspaceChanged
|
|
602
|
-
? "pass"
|
|
603
|
-
: "fail"
|
|
604
|
-
: undefined;
|
|
605
|
-
if (runContext.purpose === "verify" && runContext.taskId && verificationVerdict) {
|
|
606
|
-
const evidence = workspaceChanged
|
|
607
|
-
? "Verifier changed tracked workspace files; the attestation is invalid."
|
|
608
|
-
: !declaredVerdict
|
|
609
|
-
? "Verifier did not emit the required final VERDICT marker."
|
|
610
|
-
: finalText.trim().slice(0, 8_000);
|
|
611
|
-
await writeVerificationAttestation(options.channelDir, {
|
|
612
|
-
runId: runContext.runId,
|
|
613
|
-
taskId: runContext.taskId,
|
|
614
|
-
verdict: verificationVerdict,
|
|
615
|
-
checkedAt: formatLocalTime(),
|
|
616
|
-
evidence,
|
|
617
|
-
workspaceChanged: Boolean(workspaceChanged),
|
|
618
|
-
subjectHash: workspaceChanged ? undefined : verifierSubjectAfter,
|
|
619
|
-
subjectDir: runContext.workingDirectory,
|
|
620
|
-
});
|
|
621
|
-
}
|
|
622
|
-
if (effectiveFailureReason) {
|
|
623
|
-
if (!finalText.trim()) {
|
|
703
|
+
const lastAssistantMessage = getLastAssistantMessage(worker.state.messages);
|
|
704
|
+
const durationMs = Date.now() - startedAt;
|
|
705
|
+
if (!lastAssistantMessage) {
|
|
706
|
+
failureReason = failureReason || "Sub-agent returned no assistant message";
|
|
624
707
|
emitUpdate(formatStatus(config.name, "failed"));
|
|
625
|
-
throw new Error(
|
|
708
|
+
throw new Error(`Sub-agent ${config.name} failed: ${failureReason}`);
|
|
709
|
+
}
|
|
710
|
+
const finalText = extractAssistantText(lastAssistantMessage);
|
|
711
|
+
const effectiveFailureReason = failureReason ||
|
|
712
|
+
(lastAssistantMessage.stopReason === "error" || lastAssistantMessage.stopReason === "aborted"
|
|
713
|
+
? lastAssistantMessage.errorMessage || `Sub-agent stopped with ${lastAssistantMessage.stopReason}`
|
|
714
|
+
: undefined);
|
|
715
|
+
const verifierGitStateAfter = runContext.purpose === "verify" ? await gitWorkspaceState(scopedExecutor) : undefined;
|
|
716
|
+
const verifierSubjectAfter = runContext.purpose === "verify" ? await workspaceSubjectHash(runContext.workingDirectory) : undefined;
|
|
717
|
+
const workspaceChanged = runContext.purpose === "verify" &&
|
|
718
|
+
(verifierSubjectBefore !== undefined && verifierSubjectAfter !== undefined
|
|
719
|
+
? verifierSubjectBefore !== verifierSubjectAfter
|
|
720
|
+
: verifierGitStateBefore !== undefined &&
|
|
721
|
+
verifierGitStateAfter !== undefined &&
|
|
722
|
+
verifierGitStateBefore !== verifierGitStateAfter);
|
|
723
|
+
const declaredVerdict = runContext.purpose === "verify" ? parseVerificationVerdict(finalText) : undefined;
|
|
724
|
+
const verificationVerdict = runContext.purpose === "verify"
|
|
725
|
+
? declaredVerdict === "pass" && !effectiveFailureReason && !workspaceChanged
|
|
726
|
+
? "pass"
|
|
727
|
+
: "fail"
|
|
728
|
+
: undefined;
|
|
729
|
+
if (runContext.purpose === "verify" && runContext.taskId && verificationVerdict) {
|
|
730
|
+
const evidence = workspaceChanged
|
|
731
|
+
? "Verifier changed tracked workspace files; the attestation is invalid."
|
|
732
|
+
: !declaredVerdict
|
|
733
|
+
? "Verifier did not emit the required final VERDICT marker."
|
|
734
|
+
: finalText.trim().slice(0, 8_000);
|
|
735
|
+
await writeVerificationAttestation(options.channelDir, {
|
|
736
|
+
runId: runContext.runId,
|
|
737
|
+
taskId: runContext.taskId,
|
|
738
|
+
verdict: verificationVerdict,
|
|
739
|
+
checkedAt: formatLocalTime(),
|
|
740
|
+
evidence,
|
|
741
|
+
workspaceChanged: Boolean(workspaceChanged),
|
|
742
|
+
subjectHash: workspaceChanged ? undefined : verifierSubjectAfter,
|
|
743
|
+
subjectDir: runContext.workingDirectory,
|
|
744
|
+
// Internal verify always keeps write/edit structurally removed from the
|
|
745
|
+
// verifier's tool set (buildSubagentTools above) — a real, enforced gate.
|
|
746
|
+
verificationStrength: "enforced",
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
// Internal runs always report full usage; cost is "unknown" only for the shape a
|
|
750
|
+
// free/local model produces (tokens spent, nothing billed) — external harnesses
|
|
751
|
+
// override both explicitly once they land (D4/D9).
|
|
752
|
+
const costKnown = usage.cost.total > 0 || usage.total === 0;
|
|
753
|
+
const baseSettleInput = {
|
|
754
|
+
usage,
|
|
755
|
+
usageKnown: true,
|
|
756
|
+
costKnown,
|
|
757
|
+
turns: assistantTurns,
|
|
758
|
+
toolCalls,
|
|
759
|
+
durationMs,
|
|
760
|
+
verificationVerdict,
|
|
761
|
+
verificationStrength: runContext.purpose === "verify" ? "enforced" : undefined,
|
|
762
|
+
};
|
|
763
|
+
if (effectiveFailureReason) {
|
|
764
|
+
if (!finalText.trim()) {
|
|
765
|
+
emitUpdate(formatStatus(config.name, "failed"));
|
|
766
|
+
throw new Error(buildFailureText(config, effectiveFailureReason, finalText));
|
|
767
|
+
}
|
|
768
|
+
emitUpdate(formatStatus(config.name, "stopped"));
|
|
769
|
+
const finalized = finalizeSubAgentOutput(runContext, finalText, returns);
|
|
770
|
+
return {
|
|
771
|
+
toolResult: {
|
|
772
|
+
content: [
|
|
773
|
+
{ type: "text", text: buildStoppedText(config, effectiveFailureReason, finalized.replyText) },
|
|
774
|
+
],
|
|
775
|
+
details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, true, effectiveFailureReason, verificationVerdict, { artifactPath: finalized.artifactPath, resultTruncated: finalized.truncated }),
|
|
776
|
+
},
|
|
777
|
+
settleInput: {
|
|
778
|
+
...baseSettleInput,
|
|
779
|
+
status: "failed",
|
|
780
|
+
failureReason: effectiveFailureReason,
|
|
781
|
+
outputText: finalText,
|
|
782
|
+
},
|
|
783
|
+
};
|
|
626
784
|
}
|
|
627
|
-
|
|
628
|
-
|
|
785
|
+
const finalized = finalizeSubAgentOutput(runContext, finalText, returns);
|
|
786
|
+
return {
|
|
787
|
+
toolResult: {
|
|
788
|
+
content: [
|
|
789
|
+
{
|
|
790
|
+
type: "text",
|
|
791
|
+
text: finalized.replyText || `(Sub-agent ${config.name} completed with no text output)`,
|
|
792
|
+
},
|
|
793
|
+
],
|
|
794
|
+
details: createDetails(config, runContext, usage, assistantTurns, toolCalls, durationMs, false, undefined, verificationVerdict, { artifactPath: finalized.artifactPath, resultTruncated: finalized.truncated }),
|
|
795
|
+
},
|
|
796
|
+
settleInput: { ...baseSettleInput, status: "completed", outputText: finalText },
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
/** Best-effort settle input for the one fatal path that rejects instead of resolving. */
|
|
800
|
+
function fatalSettleInput(error) {
|
|
629
801
|
return {
|
|
630
|
-
|
|
631
|
-
|
|
802
|
+
status: "failed",
|
|
803
|
+
failureReason: failureReason || error.message,
|
|
804
|
+
usage,
|
|
805
|
+
usageKnown: true,
|
|
806
|
+
costKnown: usage.cost.total > 0 || usage.total === 0,
|
|
807
|
+
turns: assistantTurns,
|
|
808
|
+
toolCalls,
|
|
809
|
+
durationMs: Date.now() - startedAt,
|
|
810
|
+
outputText: "",
|
|
632
811
|
};
|
|
633
812
|
}
|
|
634
|
-
|
|
813
|
+
// D2: the tool call waits at most SYNC_GRACE_MS (never longer than the run's own wall
|
|
814
|
+
// clock budget) before degrading to a "still running" placeholder. The run itself keeps
|
|
815
|
+
// executing either way — only the *return* differs.
|
|
816
|
+
const graceMs = Math.min(config.maxWallTimeSec * 1000, options.syncGraceMs ?? SYNC_GRACE_MS);
|
|
817
|
+
const outcomePromise = runToCompletion().then((value) => ({ ok: true, value }), (error) => ({
|
|
818
|
+
ok: false,
|
|
819
|
+
error: error instanceof Error ? error : new Error(String(error)),
|
|
820
|
+
}));
|
|
821
|
+
const raceResult = await Promise.race([outcomePromise, sleep(graceMs).then(() => "timed-out")]);
|
|
822
|
+
if (raceResult !== "timed-out") {
|
|
823
|
+
runManager.clearCancelHandle(runContext.runId);
|
|
824
|
+
if (!raceResult.ok) {
|
|
825
|
+
await runManager.settle(runContext.runId, fatalSettleInput(raceResult.error), { announce: false });
|
|
826
|
+
throw raceResult.error;
|
|
827
|
+
}
|
|
828
|
+
await runManager.settle(runContext.runId, raceResult.value.settleInput, { announce: false });
|
|
829
|
+
return raceResult.value.toolResult;
|
|
830
|
+
}
|
|
831
|
+
// Grace window elapsed: hand back a placeholder now and let the run keep going in the
|
|
832
|
+
// background. It settles and, this time, announces itself with a completion wake (D2/D7)
|
|
833
|
+
// — the same "runtime guarantees completion" contract background jobs already keep.
|
|
834
|
+
detached = true;
|
|
835
|
+
void outcomePromise.then(async (outcome) => {
|
|
836
|
+
runManager.clearCancelHandle(runContext.runId);
|
|
837
|
+
const settleInput = outcome.ok ? outcome.value.settleInput : fatalSettleInput(outcome.error);
|
|
838
|
+
await runManager.settle(runContext.runId, settleInput, { announce: true }).catch((error) => {
|
|
839
|
+
log.logWarning(`Failed to settle detached sub-agent run ${runContext.runId}`, errorMessage(error));
|
|
840
|
+
});
|
|
841
|
+
});
|
|
635
842
|
return {
|
|
636
843
|
content: [
|
|
637
844
|
{
|
|
638
845
|
type: "text",
|
|
639
|
-
text:
|
|
846
|
+
text: `[Dispatched] runId=${runContext.runId}, agent ${config.name} (internal, async), working directory ${runContext.workingDirectory}.\n` +
|
|
847
|
+
"Status: running. This channel will be woken with the result and artifact path once it finishes.\n" +
|
|
848
|
+
"Do not dispatch it again or poll for it now -- end this turn. If it belongs to a task, mark it waiting with task_manage.",
|
|
640
849
|
},
|
|
641
850
|
],
|
|
642
|
-
details:
|
|
851
|
+
details: {
|
|
852
|
+
kind: "subagent",
|
|
853
|
+
agent: config.name,
|
|
854
|
+
source: config.source,
|
|
855
|
+
model: formatModelReference(config.model),
|
|
856
|
+
tools: [...config.tools],
|
|
857
|
+
turns: assistantTurns,
|
|
858
|
+
toolCalls,
|
|
859
|
+
durationMs: Date.now() - startedAt,
|
|
860
|
+
failed: false,
|
|
861
|
+
usage: { ...usage, cost: { ...usage.cost } },
|
|
862
|
+
runId: runContext.runId,
|
|
863
|
+
purpose: runContext.purpose,
|
|
864
|
+
taskId: runContext.taskId,
|
|
865
|
+
artifactDir: runContext.artifactDir,
|
|
866
|
+
resultTruncated: false,
|
|
867
|
+
dispatched: true,
|
|
868
|
+
},
|
|
643
869
|
};
|
|
644
870
|
},
|
|
645
871
|
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A process-wide, exclusive *write* lease on a checkout (spec 040, D10.1).
|
|
3
|
+
*
|
|
4
|
+
* Only `mutates: write` runs take a lease; read runs never do. The key is the delegation's
|
|
5
|
+
* working directory realpath, and a conflict is a prefix relationship in either direction
|
|
6
|
+
* (`/repo` and `/repo/pkg` are the same resource, not two). This is deliberately the whole
|
|
7
|
+
* mechanism: no read/write distinction, no counting, no upgrade/downgrade. What actually produces
|
|
8
|
+
* a wrong result is two writers touching the same tree at once; a reviewer reading a diff that
|
|
9
|
+
* moves under it is a quality problem, not a correctness one, and is left to `agent-delegation.md`
|
|
10
|
+
* plus the parked-review's own judgement rather than a second locking dimension.
|
|
11
|
+
*
|
|
12
|
+
* Global, not per-channel: two channels pointed at the same checkout must still exclude each
|
|
13
|
+
* other. The main agent's own write/edit/bash calls deliberately do **not** participate — see
|
|
14
|
+
* the design doc D10.1 for why (it would deadlock a run against the very turn that dispatched
|
|
15
|
+
* it, and turns this into a runtime-wide concurrency redesign this spec does not attempt).
|
|
16
|
+
*/
|
|
17
|
+
export interface WorkspaceLeaseHolder {
|
|
18
|
+
runId: string;
|
|
19
|
+
channelId: string;
|
|
20
|
+
workingDirectory: string;
|
|
21
|
+
}
|
|
22
|
+
/** The stable lease key for a working directory: its realpath, so a symlink or `..` cannot dodge a conflict. */
|
|
23
|
+
export declare function workspaceLeaseKey(workingDirectory: string): string;
|
|
24
|
+
export type AcquireWorkspaceLeaseResult = {
|
|
25
|
+
ok: true;
|
|
26
|
+
leaseKey: string;
|
|
27
|
+
} | {
|
|
28
|
+
ok: false;
|
|
29
|
+
leaseKey: string;
|
|
30
|
+
heldBy: WorkspaceLeaseHolder;
|
|
31
|
+
};
|
|
32
|
+
export declare function acquireWorkspaceLease(holder: WorkspaceLeaseHolder): AcquireWorkspaceLeaseResult;
|
|
33
|
+
export declare function releaseWorkspaceLease(leaseKey: string | undefined): void;
|
|
34
|
+
/** Read-only check for a pre-flight gate (e.g. `purpose=verify`, D9) that must not itself take a lease. */
|
|
35
|
+
export declare function findWorkspaceLeaseHolder(workingDirectory: string): WorkspaceLeaseHolder | undefined;
|
|
36
|
+
export declare function formatWorkspaceLeaseConflict(heldBy: WorkspaceLeaseHolder): string;
|