@oyasmi/pipiclaw 0.9.3 → 0.9.4-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.
- package/dist/agent/builtin-commands.d.ts +19 -0
- package/dist/agent/builtin-commands.js +80 -0
- package/dist/agent/channel-runner.d.ts +20 -208
- package/dist/agent/channel-runner.js +167 -1188
- package/dist/agent/maintenance-context.d.ts +1 -1
- package/dist/agent/maintenance-context.js +1 -1
- package/dist/agent/prompt/manifest.d.ts +6 -1
- package/dist/agent/prompt/manifest.js +45 -64
- package/dist/agent/prompt/resources.d.ts +3 -0
- package/dist/agent/prompt/resources.js +11 -2
- package/dist/agent/runner-factory.d.ts +1 -43
- package/dist/agent/{command-extension.d.ts → session/command-extension.d.ts} +4 -0
- package/dist/agent/{command-extension.js → session/command-extension.js} +48 -35
- package/dist/agent/{type-guards.d.ts → session/event-guards.d.ts} +2 -2
- package/dist/agent/{type-guards.js → session/event-guards.js} +5 -1
- package/dist/agent/session/model-selection.d.ts +47 -0
- package/dist/agent/session/model-selection.js +99 -0
- package/dist/agent/{session-adapter.d.ts → session/session-adapter.d.ts} +21 -1
- package/dist/agent/session/session-adapter.js +159 -0
- package/dist/agent/{session-events.d.ts → session/session-events.d.ts} +9 -5
- package/dist/agent/{session-events.js → session/session-events.js} +24 -13
- package/dist/agent/session/session-host.d.ts +200 -0
- package/dist/agent/session/session-host.js +621 -0
- package/dist/agent/{session-resource-gate.js → session/session-resource-gate.js} +5 -3
- package/dist/agent/status-render.d.ts +0 -1
- package/dist/agent/status-render.js +4 -16
- package/dist/agent/{context-budget.js → turn/context-budget.js} +5 -1
- package/dist/agent/{progress-formatter.d.ts → turn/progress-formatter.d.ts} +4 -1
- package/dist/agent/{run-queue.d.ts → turn/run-queue.d.ts} +1 -1
- package/dist/agent/{run-queue.js → turn/run-queue.js} +10 -5
- package/dist/{memory → agent/turn}/task-digest.js +4 -4
- package/dist/agent/turn/turn-context.d.ts +14 -0
- package/dist/agent/turn/turn-context.js +64 -0
- package/dist/agent/turn/turn-error.d.ts +31 -0
- package/dist/agent/turn/turn-error.js +68 -0
- package/dist/agent/turn/turn-finish.d.ts +50 -0
- package/dist/agent/turn/turn-finish.js +188 -0
- package/dist/agent/turn/turn-input.d.ts +43 -0
- package/dist/agent/turn/turn-input.js +79 -0
- package/dist/agent/turn/turn-pipeline.d.ts +68 -0
- package/dist/agent/turn/turn-pipeline.js +257 -0
- package/dist/agent/{turn-prompt.d.ts → turn/turn-prompt.d.ts} +2 -2
- package/dist/agent/{turn-prompt.js → turn/turn-prompt.js} +6 -2
- package/dist/agent/{turn-recovery.js → turn/turn-recovery.js} +1 -1
- package/dist/agent/{turn-state.d.ts → turn/turn-state.d.ts} +1 -1
- package/dist/agent/types.d.ts +43 -2
- package/dist/agent/types.js +1 -1
- package/dist/{models/auth-cli.d.ts → app/auth-command.d.ts} +1 -1
- package/dist/{models/auth-cli.js → app/auth-command.js} +14 -10
- package/dist/{runtime/app-home.d.ts → app/home.d.ts} +6 -2
- package/dist/{runtime/app-home.js → app/home.js} +22 -75
- package/dist/{runtime → app}/proxy.js +4 -2
- package/dist/{app-services.d.ts → app/services.d.ts} +5 -5
- package/dist/{app-services.js → app/services.js} +17 -14
- package/dist/channel/channel-context.d.ts +12 -2
- package/dist/channel/channel-context.js +29 -2
- package/dist/channel/channel-event.d.ts +10 -2
- package/dist/channel/channel-event.js +1 -1
- package/dist/channel/channel-index.js +4 -1
- package/dist/{runtime/project-commands.d.ts → channel/commands.d.ts} +1 -1
- package/dist/{runtime/project-commands.js → channel/commands.js} +17 -16
- package/dist/channel/project-scope-store.js +1 -1
- package/dist/channel/store.js +4 -0
- package/dist/commands/catalog.d.ts +24 -7
- package/dist/commands/catalog.js +91 -44
- package/dist/commands/reply-limits.d.ts +6 -0
- package/dist/commands/reply-limits.js +24 -0
- package/dist/{runtime/report-commands.d.ts → commands/router.d.ts} +10 -3
- package/dist/{runtime/report-commands.js → commands/router.js} +6 -6
- package/dist/{settings.d.ts → config/settings.d.ts} +10 -10
- package/dist/{settings.js → config/settings.js} +11 -11
- package/dist/{tools/config.d.ts → config/tools.d.ts} +1 -2
- package/dist/{tools/config.js → config/tools.js} +5 -2
- package/dist/dingtalk/access-token.d.ts +12 -0
- package/dist/dingtalk/access-token.js +51 -0
- package/dist/dingtalk/api.d.ts +19 -0
- package/dist/dingtalk/api.js +67 -0
- package/dist/dingtalk/bot.d.ts +97 -0
- package/dist/dingtalk/bot.js +389 -0
- package/dist/dingtalk/cards.d.ts +56 -0
- package/dist/dingtalk/cards.js +318 -0
- package/dist/{runtime → dingtalk}/channel-queue.js +4 -1
- package/dist/dingtalk/config.d.ts +19 -0
- package/dist/dingtalk/config.js +95 -0
- package/dist/dingtalk/connection.d.ts +57 -0
- package/dist/dingtalk/connection.js +356 -0
- package/dist/dingtalk/conversation-meta.d.ts +16 -0
- package/dist/dingtalk/conversation-meta.js +77 -0
- package/dist/{runtime → dingtalk}/delivery.d.ts +6 -2
- package/dist/{runtime → dingtalk}/delivery.js +29 -15
- package/dist/dingtalk/handler.d.ts +90 -0
- package/dist/dingtalk/handler.js +1 -0
- package/dist/dingtalk/inbound.d.ts +66 -0
- package/dist/dingtalk/inbound.js +137 -0
- package/dist/dingtalk/media.d.ts +66 -0
- package/dist/dingtalk/media.js +214 -0
- package/dist/events/{event-commands.js → commands.js} +99 -45
- package/dist/events/parse.d.ts +14 -0
- package/dist/events/parse.js +114 -0
- package/dist/events/types.d.ts +93 -0
- package/dist/events/types.js +1 -0
- package/dist/events/{event-validation.d.ts → validation.d.ts} +14 -3
- package/dist/events/{event-validation.js → validation.js} +17 -9
- package/dist/events/watcher.d.ts +67 -0
- package/dist/events/{events.js → watcher.js} +63 -121
- package/dist/executor.js +2 -2
- package/dist/index.d.ts +6 -4
- package/dist/index.js +2 -2
- package/dist/jobs/launch.d.ts +42 -0
- package/dist/jobs/launch.js +118 -0
- package/dist/{agent/job-manager.d.ts → jobs/manager.d.ts} +1 -67
- package/dist/{agent/job-manager.js → jobs/manager.js} +34 -157
- package/dist/jobs/record.d.ts +55 -0
- package/dist/jobs/record.js +36 -0
- package/dist/log.d.ts +12 -2
- package/dist/log.js +26 -34
- package/dist/main.js +3 -3
- package/dist/memory/commands.js +29 -23
- package/dist/memory/lifecycle.js +26 -5
- package/dist/memory/maintenance-gates.d.ts +2 -2
- package/dist/memory/maintenance-state.js +4 -1
- package/dist/memory/maintenance-tuning.d.ts +15 -0
- package/dist/memory/maintenance-tuning.js +3 -0
- package/dist/memory/reflect-job.d.ts +2 -2
- package/dist/memory/reflect-job.js +4 -2
- package/dist/memory/scheduler.d.ts +3 -3
- package/dist/memory/scheduler.js +5 -2
- package/dist/memory/sidecar-worker.js +1 -1
- package/dist/memory/transcript.js +1 -1
- package/dist/{agent/model-fallback.d.ts → models/fallback.d.ts} +6 -6
- package/dist/{agent/model-fallback.js → models/fallback.js} +15 -28
- package/dist/models/login-identity.d.ts +2 -0
- package/dist/models/login-identity.js +83 -0
- package/dist/models/provider-login.d.ts +3 -1
- package/dist/models/provider-login.js +8 -2
- package/dist/models/reference.d.ts +20 -0
- package/dist/models/{utils.js → reference.js} +0 -48
- package/dist/models/{utils.d.ts → runtime.d.ts} +1 -16
- package/dist/models/runtime.js +52 -0
- package/dist/paths.d.ts +2 -0
- package/dist/paths.js +9 -0
- package/dist/playbooks/agent-delegation.md +2 -2
- package/dist/playbooks/catalog.d.ts +6 -2
- package/dist/playbooks/catalog.js +9 -6
- package/dist/runtime/bootstrap.d.ts +7 -17
- package/dist/runtime/bootstrap.js +70 -659
- package/dist/runtime/durable-dispatch.d.ts +43 -4
- package/dist/runtime/durable-dispatch.js +153 -3
- package/dist/runtime/inbound-images.d.ts +18 -0
- package/dist/runtime/inbound-images.js +51 -0
- package/dist/runtime/shutdown.d.ts +39 -0
- package/dist/runtime/shutdown.js +120 -0
- package/dist/runtime/stop-watchdog.d.ts +16 -0
- package/dist/runtime/stop-watchdog.js +32 -0
- package/dist/runtime/task-driver.d.ts +6 -4
- package/dist/runtime/task-driver.js +58 -23
- package/dist/runtime/task-migration.js +25 -8
- package/dist/runtime/task-spawn.d.ts +1 -1
- package/dist/runtime/task-spawn.js +13 -6
- package/dist/runtime/turn-handler.d.ts +47 -0
- package/dist/runtime/turn-handler.js +318 -0
- package/dist/runtime/turn-run.d.ts +52 -0
- package/dist/runtime/turn-run.js +318 -0
- package/dist/runtime/wake-coalescing.d.ts +18 -0
- package/dist/runtime/wake-coalescing.js +29 -0
- package/dist/security/block-message.d.ts +22 -1
- package/dist/security/block-message.js +66 -1
- package/dist/security/command-guard.js +4 -0
- package/dist/security/network.d.ts +2 -1
- package/dist/security/network.js +7 -2
- package/dist/security/path-guard-check.js +2 -2
- package/dist/security/path-guard.js +4 -0
- package/dist/security/types.d.ts +1 -2
- package/dist/security/types.js +1 -2
- package/dist/shared/exact-keys.d.ts +1 -1
- package/dist/shared/format.d.ts +12 -0
- package/dist/shared/format.js +37 -0
- package/dist/shared/host-process.js +16 -4
- package/dist/shared/wake-claim.d.ts +1 -1
- package/dist/shared/with-timeout.d.ts +3 -2
- package/dist/shared/with-timeout.js +14 -3
- package/dist/{runtime/skill-commands.d.ts → skills/commands.d.ts} +2 -2
- package/dist/{runtime/skill-commands.js → skills/commands.js} +18 -11
- package/dist/{agent/workspace-resources.js → skills/loader.js} +1 -1
- package/dist/{tools/skill-security.js → skills/validation.js} +4 -0
- package/dist/skills/workspace.d.ts +33 -0
- package/dist/skills/workspace.js +116 -0
- package/dist/{runtime/subagent-commands.d.ts → subagents/commands.d.ts} +9 -7
- package/dist/{runtime/subagent-commands.js → subagents/commands.js} +116 -77
- package/dist/subagents/completion-wake.d.ts +17 -0
- package/dist/subagents/completion-wake.js +76 -0
- package/dist/subagents/detached-discovery.js +1 -1
- package/dist/subagents/discovery.d.ts +1 -1
- package/dist/subagents/discovery.js +2 -2
- package/dist/subagents/dispatch.d.ts +33 -0
- package/dist/subagents/dispatch.js +190 -0
- package/dist/subagents/external/claude-code.js +23 -1
- package/dist/subagents/external/dispatch.d.ts +25 -0
- package/dist/subagents/external/dispatch.js +90 -0
- package/dist/subagents/external/harness.d.ts +1 -1
- package/dist/subagents/external/progress-tail.d.ts +18 -1
- package/dist/subagents/external/progress-tail.js +64 -17
- package/dist/subagents/external/run.d.ts +5 -1
- package/dist/subagents/external/run.js +23 -9
- package/dist/subagents/external/settlement.d.ts +4 -1
- package/dist/subagents/external/settlement.js +1 -1
- package/dist/subagents/format.d.ts +1 -1
- package/dist/subagents/grace.d.ts +24 -0
- package/dist/subagents/grace.js +57 -0
- package/dist/subagents/internal/outcome.d.ts +24 -0
- package/dist/subagents/internal/outcome.js +149 -0
- package/dist/subagents/internal/provider-retry.d.ts +19 -0
- package/dist/subagents/internal/provider-retry.js +83 -0
- package/dist/subagents/internal/run.d.ts +31 -0
- package/dist/subagents/internal/run.js +240 -0
- package/dist/subagents/internal/state.d.ts +43 -0
- package/dist/subagents/internal/state.js +48 -0
- package/dist/subagents/internal/worker.d.ts +51 -0
- package/dist/subagents/internal/worker.js +167 -0
- package/dist/subagents/result.d.ts +62 -0
- package/dist/subagents/result.js +103 -0
- package/dist/subagents/run-record.d.ts +222 -0
- package/dist/subagents/run-record.js +101 -0
- package/dist/subagents/run-registry.d.ts +9 -0
- package/dist/subagents/run-registry.js +125 -0
- package/dist/subagents/runs.d.ts +16 -232
- package/dist/subagents/runs.js +132 -310
- package/dist/subagents/task-envelope.d.ts +36 -0
- package/dist/subagents/task-envelope.js +168 -0
- package/dist/subagents/types.d.ts +154 -0
- package/dist/subagents/types.js +1 -0
- package/dist/subagents/verification-outcome.d.ts +1 -1
- package/dist/subagents/workspace-summary.d.ts +16 -4
- package/dist/subagents/workspace-summary.js +74 -18
- package/dist/tasks/board.d.ts +10 -3
- package/dist/tasks/board.js +38 -3
- package/dist/tasks/{work-log.d.ts → bound-work.d.ts} +1 -1
- package/dist/tasks/{work-log.js → bound-work.js} +1 -1
- package/dist/tasks/brief.js +1 -1
- package/dist/{runtime/task-commands.d.ts → tasks/commands.d.ts} +1 -1
- package/dist/{runtime/task-commands.js → tasks/commands.js} +117 -67
- package/dist/tasks/contract-input.d.ts +1 -1
- package/dist/tasks/contract-input.js +1 -1
- package/dist/tasks/create.js +1 -1
- package/dist/tasks/frontmatter.d.ts +5 -0
- package/dist/tasks/frontmatter.js +8 -0
- package/dist/tasks/{log.d.ts → loop-log.d.ts} +11 -1
- package/dist/tasks/{log.js → loop-log.js} +59 -3
- package/dist/tasks/mutation-lock.js +1 -1
- package/dist/tasks/session-path.js +1 -1
- package/dist/tasks/steer.js +1 -1
- package/dist/tasks/store.js +6 -4
- package/dist/tasks/ticket.d.ts +3 -1
- package/dist/tasks/ticket.js +19 -1
- package/dist/tools/bash.d.ts +1 -1
- package/dist/tools/bash.js +2 -2
- package/dist/tools/{tool-details.d.ts → contract/details.d.ts} +11 -3
- package/dist/tools/{tool-details.js → contract/details.js} +42 -5
- package/dist/tools/{presentation.js → contract/presentation.js} +3 -3
- package/dist/tools/event-manage.d.ts +1 -1
- package/dist/tools/event-manage.js +4 -4
- package/dist/tools/index.d.ts +5 -3
- package/dist/tools/index.js +8 -6
- package/dist/tools/job.d.ts +1 -1
- package/dist/tools/memory-manage.js +4 -1
- package/dist/tools/registry.d.ts +7 -7
- package/dist/tools/registry.js +6 -6
- package/dist/tools/session-search.d.ts +1 -1
- package/dist/tools/skill.d.ts +2 -34
- package/dist/tools/skill.js +8 -116
- package/dist/tools/subagent-manage.d.ts +1 -1
- package/dist/tools/subagent-manage.js +19 -13
- package/dist/tools/subagent.d.ts +46 -0
- package/dist/tools/subagent.js +127 -0
- package/dist/tools/{task-manage.d.ts → task-manage/factory.d.ts} +7 -3
- package/dist/tools/{task-manage.js → task-manage/factory.js} +7 -7
- package/dist/tools/task-manage/lifecycle.js +2 -2
- package/dist/tools/task-manage/log-view.js +2 -2
- package/dist/tools/task-manage/shared.js +3 -3
- package/dist/tools/task-manage/step-end.js +7 -4
- package/dist/tools/task-manage/types.d.ts +1 -1
- package/dist/tools/web-fetch.d.ts +1 -1
- package/dist/tools/web-search.d.ts +1 -1
- package/dist/tui/app.d.ts +1 -1
- package/dist/tui/app.js +6 -6
- package/dist/tui/cli.d.ts +1 -1
- package/dist/tui/cli.js +3 -3
- package/dist/tui/commands.js +4 -4
- package/dist/tui/frontend.d.ts +44 -0
- package/dist/tui/frontend.js +13 -0
- package/dist/tui/pitui-frontend.d.ts +1 -1
- package/dist/tui/pitui-frontend.js +1 -1
- package/dist/tui/plain-frontend.d.ts +1 -1
- package/dist/tui/renderer.d.ts +3 -42
- package/dist/tui/renderer.js +3 -2
- package/dist/tui/terminal-context.d.ts +2 -2
- package/dist/tui/terminal-media-sender.d.ts +1 -1
- package/dist/tui/turn-controller.d.ts +3 -1
- package/dist/tui/turn-controller.js +36 -21
- package/dist/usage/ledger.js +7 -1
- package/dist/usage/render.js +3 -1
- package/dist/{shared/types.d.ts → usage/totals.d.ts} +3 -0
- package/dist/web/client.d.ts +5 -1
- package/dist/web/client.js +4 -0
- package/dist/web/config.d.ts +1 -1
- package/dist/web/fetch.d.ts +1 -1
- package/dist/web/search-providers.d.ts +1 -1
- package/dist/web/search.d.ts +1 -1
- package/package.json +9 -7
- package/dist/agent/session-adapter.js +0 -77
- package/dist/events/events.d.ts +0 -159
- package/dist/runtime/dingtalk.d.ts +0 -272
- package/dist/runtime/dingtalk.js +0 -1416
- package/dist/subagents/tool.d.ts +0 -206
- package/dist/subagents/tool.js +0 -1088
- /package/dist/{runtime → agent/prompt}/workspace-templates.d.ts +0 -0
- /package/dist/{runtime → agent/prompt}/workspace-templates.js +0 -0
- /package/dist/agent/{session-resource-gate.d.ts → session/session-resource-gate.d.ts} +0 -0
- /package/dist/agent/{context-budget.d.ts → turn/context-budget.d.ts} +0 -0
- /package/dist/agent/{progress-formatter.js → turn/progress-formatter.js} +0 -0
- /package/dist/{memory → agent/turn}/task-digest.d.ts +0 -0
- /package/dist/agent/{turn-recovery.d.ts → turn/turn-recovery.d.ts} +0 -0
- /package/dist/agent/{turn-state.js → turn/turn-state.js} +0 -0
- /package/dist/{runtime → app}/proxy.d.ts +0 -0
- /package/dist/{runtime → dingtalk}/channel-queue.d.ts +0 -0
- /package/dist/{runtime → dingtalk}/inbound-media.d.ts +0 -0
- /package/dist/{runtime → dingtalk}/inbound-media.js +0 -0
- /package/dist/events/{event-commands.d.ts → commands.d.ts} +0 -0
- /package/dist/{agent/workspace-resources.d.ts → skills/loader.d.ts} +0 -0
- /package/dist/{tools/skill-security.d.ts → skills/validation.d.ts} +0 -0
- /package/dist/tasks/{ledger.d.ts → contract.d.ts} +0 -0
- /package/dist/tasks/{ledger.js → contract.js} +0 -0
- /package/dist/tools/{subagent-tool-names.d.ts → contract/names.d.ts} +0 -0
- /package/dist/tools/{subagent-tool-names.js → contract/names.js} +0 -0
- /package/dist/tools/{presentation.d.ts → contract/presentation.d.ts} +0 -0
- /package/dist/{shared/types.js → usage/totals.js} +0 -0
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Delegation dispatch, shared by `subagent` and `subagent_inline` (spec 046 D2.5): prepare the run
|
|
3
|
+
* (working directory, project boundary, artifact directory), admit it (verify rules, workspace write
|
|
4
|
+
* lease), then fork to the internal or external runtime.
|
|
5
|
+
*/
|
|
6
|
+
import { realpathSync, statSync } from "node:fs";
|
|
7
|
+
import { mkdir } from "node:fs/promises";
|
|
8
|
+
import { join, resolve } from "node:path";
|
|
9
|
+
import { RecoverableToolError } from "../shared/recoverable-error.js";
|
|
10
|
+
import { findTaskItem, parseTaskItems } from "../tasks/contract.js";
|
|
11
|
+
import { readStoredTask } from "../tasks/store.js";
|
|
12
|
+
import { dispatchExternalRun } from "./external/dispatch.js";
|
|
13
|
+
import { dispatchInternalRun } from "./internal/run.js";
|
|
14
|
+
import { assertVerifyAdmissible } from "./task-envelope.js";
|
|
15
|
+
import { acquireWorkspaceLease, formatWorkspaceLeaseConflict } from "./workspace-lease.js";
|
|
16
|
+
import { snapshotWorkspace } from "./workspace-summary.js";
|
|
17
|
+
const TASK_ID_PATTERN = /^[A-Za-z0-9._-]+$/;
|
|
18
|
+
function safeRunSegment(value) {
|
|
19
|
+
return value.replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 48) || "run";
|
|
20
|
+
}
|
|
21
|
+
function getSubAgentArtifactsRoot(channelDir) {
|
|
22
|
+
return join(channelDir, "subagent-artifacts");
|
|
23
|
+
}
|
|
24
|
+
/** Every run gets its own artifact directory (spec 032 D4), independent of `returns` mode. */
|
|
25
|
+
async function prepareArtifactDir(channelDir, runId) {
|
|
26
|
+
const artifactDir = join(getSubAgentArtifactsRoot(channelDir), safeRunSegment(runId));
|
|
27
|
+
await mkdir(artifactDir, { recursive: true });
|
|
28
|
+
return artifactDir;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Resolve the checkout a run works in (spec 036, D3).
|
|
32
|
+
*
|
|
33
|
+
* Spec 036 removed task-owned worktrees on the premise that a caller needing a separate checkout
|
|
34
|
+
* would `git worktree add` on the host and "pass it in as an ordinary working directory" — but no
|
|
35
|
+
* parameter for that ever existed, so every run was pinned to the daemon's own cwd. This is that
|
|
36
|
+
* parameter. Path guards are unaffected: they judge the *resolved absolute* target, so a cwd
|
|
37
|
+
* outside the allowed roots makes relative paths fail exactly as an absolute one there would.
|
|
38
|
+
*/
|
|
39
|
+
function realpathOrSelf(path) {
|
|
40
|
+
try {
|
|
41
|
+
return realpathSync(path);
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return path;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* D6.2's boundary check, hardened against symlinks (review 2026-08-23 §2.3): a plain
|
|
49
|
+
* `resolve()` + string-prefix comparison only judges the *requested* path, so `<projectRoot
|
|
50
|
+
* >/link -> /somewhere/else` passes the check and then everything downstream — the internal
|
|
51
|
+
* agent's own `securityContext.projectRoot`, an external process's `cwd` (which bypasses the
|
|
52
|
+
* path guard entirely) — trusts that escaped target. Comparing realpaths closes it, matching
|
|
53
|
+
* `project-scope.ts` and `workspaceLeaseKey`, the two other places in the tree that already do
|
|
54
|
+
* this.
|
|
55
|
+
*/
|
|
56
|
+
export function assertWithinProjectBoundary(target, base, requested) {
|
|
57
|
+
const realBase = realpathOrSelf(base);
|
|
58
|
+
const realTarget = realpathOrSelf(target);
|
|
59
|
+
if (realTarget !== realBase && !realTarget.startsWith(`${realBase}/`)) {
|
|
60
|
+
throw new RecoverableToolError(`workingDirectory "${requested}" must be inside the project root (${base}).`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function resolveRunWorkingDirectory(requested, options) {
|
|
64
|
+
const base = resolve(options.workingDirectory ?? process.cwd());
|
|
65
|
+
const trimmed = requested?.trim();
|
|
66
|
+
// Resolve the project root once as well. Returning an alias here would leave the later lease,
|
|
67
|
+
// executor, subject hash, and external cwd exposed to a symlink swap after admission.
|
|
68
|
+
const canonicalBase = realpathOrSelf(base);
|
|
69
|
+
if (!trimmed)
|
|
70
|
+
return canonicalBase;
|
|
71
|
+
const target = resolve(canonicalBase, trimmed);
|
|
72
|
+
let canonicalTarget;
|
|
73
|
+
try {
|
|
74
|
+
canonicalTarget = realpathSync(target);
|
|
75
|
+
if (!statSync(canonicalTarget).isDirectory())
|
|
76
|
+
throw new Error("not a directory");
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
throw new RecoverableToolError(`workingDirectory "${requested}" is not an existing directory.`);
|
|
80
|
+
}
|
|
81
|
+
if (options.projectBoundary === "project") {
|
|
82
|
+
assertWithinProjectBoundary(canonicalTarget, canonicalBase, requested ?? trimmed);
|
|
83
|
+
}
|
|
84
|
+
return canonicalTarget;
|
|
85
|
+
}
|
|
86
|
+
async function prepareRunContext(runId, params, options) {
|
|
87
|
+
const purpose = params.purpose ?? "work";
|
|
88
|
+
let taskId = params.taskId?.trim() || undefined;
|
|
89
|
+
// Inside a task session the binding is automatic, like `bash`'s: a delegation from a task step
|
|
90
|
+
// belongs to that task, so the leader never has to remember to pass it (spec 052, D4).
|
|
91
|
+
if (options.boundTaskId) {
|
|
92
|
+
if (taskId && taskId !== options.boundTaskId) {
|
|
93
|
+
throw new RecoverableToolError(`This is task ${options.boundTaskId}'s session — drop taskId (it is bound automatically); "${taskId}" does not belong here.`);
|
|
94
|
+
}
|
|
95
|
+
taskId = options.boundTaskId;
|
|
96
|
+
}
|
|
97
|
+
const item = params.item?.trim() || undefined;
|
|
98
|
+
if (item && !taskId)
|
|
99
|
+
throw new RecoverableToolError("item names a Work Item of a task; pass taskId too.");
|
|
100
|
+
if (taskId && !TASK_ID_PATTERN.test(taskId))
|
|
101
|
+
throw new RecoverableToolError(`Invalid taskId: ${taskId}`);
|
|
102
|
+
if (taskId) {
|
|
103
|
+
const task = await readStoredTask(options.channelDir, taskId);
|
|
104
|
+
if (!task) {
|
|
105
|
+
throw new RecoverableToolError(`Task ${taskId} does not exist. Create it with task_create before delegating task-owned work.`);
|
|
106
|
+
}
|
|
107
|
+
if (item && !findTaskItem(task.body, item)) {
|
|
108
|
+
const known = parseTaskItems(task.body)
|
|
109
|
+
?.items.map((entry) => entry.id)
|
|
110
|
+
.join(", ");
|
|
111
|
+
throw new RecoverableToolError(`Task ${taskId} has no Work Item "${item}"${known ? ` (known: ${known})` : " (it has no Work Items yet — add one with task_update first)"}.`);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
const artifactDir = await prepareArtifactDir(options.channelDir, runId);
|
|
115
|
+
const workingDirectory = resolveRunWorkingDirectory(params.workingDirectory, options);
|
|
116
|
+
return { runId, purpose, taskId, item, workingDirectory, artifactDir };
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* A run's lifecycle is deliberately unlinked from the tool call's `AbortSignal` (spec 040, D2):
|
|
120
|
+
* `/stop` ends the current turn but no longer kills an in-flight delegation, matching background
|
|
121
|
+
* jobs. Stopping a run is now an explicit decision (`subagent_run op=cancel`), not a side
|
|
122
|
+
* effect of stopping something else.
|
|
123
|
+
*/
|
|
124
|
+
/**
|
|
125
|
+
* Shared dispatch path for both `subagent` and `subagent_inline` (spec 046, D2.5): everything
|
|
126
|
+
* after a role has been resolved into a `ResolvedSubAgentConfig` — workspace lease admission,
|
|
127
|
+
* the internal/external fork, budget/turn/tool-call enforcement, the verification verdict, and
|
|
128
|
+
* the sync-grace/detached-placeholder split — is identical regardless of which schema the model
|
|
129
|
+
* called through.
|
|
130
|
+
*/
|
|
131
|
+
export async function dispatchSubAgentRun(options, currentModel, config, warning, params, signal, onUpdate) {
|
|
132
|
+
// Derived rather than model-supplied (spec 045): `${agent}: ${task's first line}`, the
|
|
133
|
+
// same shape `subagent_run op=follow_up` already builds by hand.
|
|
134
|
+
const runLabel = `${config.name}: ${params.task.split("\n")[0]?.slice(0, 80) ?? ""}`;
|
|
135
|
+
// Only ever set for an inline (internal) delegation with `bash` in `tools` and no explicit
|
|
136
|
+
// `mutates` — surfaced to the model, not just a log, since it has no role file to fix.
|
|
137
|
+
const mutatesNote = warning ? `Note: ${warning}\n\n` : "";
|
|
138
|
+
const runManager = options.getRunManager(options.runtimeContext.channelId);
|
|
139
|
+
// A short, human-typeable id (spec 041) — never the dispatching tool call's own id, which
|
|
140
|
+
// on some providers is a long `call_<id>|fc_<id>` composite unreadable in a chat UI.
|
|
141
|
+
const runContext = await prepareRunContext(runManager.mintRunId(), params, options);
|
|
142
|
+
// D9: an independent verifier checks against a target that isn't moving under it — shared
|
|
143
|
+
// with `subagent_run op=follow_up` (spec 042 D7) so a verify run's admission rules
|
|
144
|
+
// cannot drift between the two dispatch paths.
|
|
145
|
+
assertVerifyAdmissible(config, runContext.purpose, runContext.workingDirectory);
|
|
146
|
+
// Admission: every write-mutating run, including a write-capable verifier, takes an exclusive
|
|
147
|
+
// workspace lease before it is even registered (spec 040, D10.1). A rejected delegation should
|
|
148
|
+
// never count as "started"; the lease is handed to SubAgentRunManager as the settlement owner.
|
|
149
|
+
let leaseKey;
|
|
150
|
+
if (config.mutates === "write") {
|
|
151
|
+
const lease = acquireWorkspaceLease({
|
|
152
|
+
runId: runContext.runId,
|
|
153
|
+
channelId: options.runtimeContext.channelId,
|
|
154
|
+
workingDirectory: runContext.workingDirectory,
|
|
155
|
+
});
|
|
156
|
+
if (!lease.ok) {
|
|
157
|
+
throw new RecoverableToolError(formatWorkspaceLeaseConflict(lease.heldBy));
|
|
158
|
+
}
|
|
159
|
+
leaseKey = lease.leaseKey;
|
|
160
|
+
}
|
|
161
|
+
// Taken under the lease, before the run can write: what "already dirty" means for this run.
|
|
162
|
+
const workspaceBaseline = config.mutates === "write" ? await snapshotWorkspace(runContext.workingDirectory) : undefined;
|
|
163
|
+
if (config.runtime === "external") {
|
|
164
|
+
return dispatchExternalRun({
|
|
165
|
+
options,
|
|
166
|
+
currentModel,
|
|
167
|
+
config,
|
|
168
|
+
runLabel,
|
|
169
|
+
runContext,
|
|
170
|
+
leaseKey,
|
|
171
|
+
params,
|
|
172
|
+
runManager,
|
|
173
|
+
workspaceBaseline,
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
return dispatchInternalRun({
|
|
177
|
+
options,
|
|
178
|
+
currentModel,
|
|
179
|
+
config,
|
|
180
|
+
runLabel,
|
|
181
|
+
mutatesNote,
|
|
182
|
+
runContext,
|
|
183
|
+
leaseKey,
|
|
184
|
+
params,
|
|
185
|
+
signal,
|
|
186
|
+
onUpdate,
|
|
187
|
+
runManager,
|
|
188
|
+
workspaceBaseline,
|
|
189
|
+
});
|
|
190
|
+
}
|
|
@@ -210,9 +210,31 @@ export const claudeCodeHarness = {
|
|
|
210
210
|
const parts = Array.isArray(event.message.content) ? event.message.content : [];
|
|
211
211
|
for (const part of parts) {
|
|
212
212
|
if (isRecord(part) && part.type === "tool_use" && typeof part.name === "string") {
|
|
213
|
-
return part.name;
|
|
213
|
+
return describeClaudeToolUse(part.name, isRecord(part.input) ? part.input : {});
|
|
214
214
|
}
|
|
215
215
|
}
|
|
216
216
|
return undefined;
|
|
217
217
|
},
|
|
218
218
|
};
|
|
219
|
+
const PROGRESS_LABEL_MAX_CHARS = 80;
|
|
220
|
+
/** The one input field that says what a claude-code tool call is acting on, in priority order. */
|
|
221
|
+
const TOOL_SUBJECT_FIELDS = ["command", "file_path", "notebook_path", "path", "pattern", "url", "query", "description"];
|
|
222
|
+
/**
|
|
223
|
+
* A bare tool name (`Bash`, `Edit`) says nothing about where a run is; the command or path it is
|
|
224
|
+
* acting on does. The todo list gets the same "done/total" shape codex-cli's progress uses.
|
|
225
|
+
*/
|
|
226
|
+
function describeClaudeToolUse(name, input) {
|
|
227
|
+
if (Array.isArray(input.todos) && input.todos.length > 0) {
|
|
228
|
+
const done = input.todos.filter((todo) => isRecord(todo) && todo.status === "completed").length;
|
|
229
|
+
return `待办 ${done}/${input.todos.length}`;
|
|
230
|
+
}
|
|
231
|
+
for (const field of TOOL_SUBJECT_FIELDS) {
|
|
232
|
+
const value = input[field];
|
|
233
|
+
if (typeof value !== "string")
|
|
234
|
+
continue;
|
|
235
|
+
const subject = value.split("\n")[0]?.trim();
|
|
236
|
+
if (subject)
|
|
237
|
+
return `${name} ${subject}`.slice(0, PROGRESS_LABEL_MAX_CHARS);
|
|
238
|
+
}
|
|
239
|
+
return name;
|
|
240
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `runtime: external` half of delegation dispatch: launches the harness process through
|
|
3
|
+
* `external/run.ts`. Always returns the "[Dispatched]" placeholder.
|
|
4
|
+
*/
|
|
5
|
+
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
6
|
+
import { type ExternalSubAgentConfig } from "../discovery.js";
|
|
7
|
+
import type { SubAgentRunManager } from "../runs.js";
|
|
8
|
+
import type { DelegationParams, DelegationResult, SubAgentRunContext, SubAgentToolOptions } from "../types.js";
|
|
9
|
+
import type { WorkspaceBaseline } from "../workspace-summary.js";
|
|
10
|
+
/**
|
|
11
|
+
* The `runtime: external` half of `dispatchSubAgentRun` (spec 046, D2.5): launches the harness
|
|
12
|
+
* process and always returns the "[Dispatched]" placeholder — external's sync grace window is
|
|
13
|
+
* always 0, so there is no inline-wait branch to share with the internal path.
|
|
14
|
+
*/
|
|
15
|
+
export declare function dispatchExternalRun(input: {
|
|
16
|
+
runManager: SubAgentRunManager;
|
|
17
|
+
options: SubAgentToolOptions;
|
|
18
|
+
currentModel: Model<Api>;
|
|
19
|
+
config: ExternalSubAgentConfig;
|
|
20
|
+
runLabel: string;
|
|
21
|
+
runContext: SubAgentRunContext;
|
|
22
|
+
leaseKey: string | undefined;
|
|
23
|
+
params: DelegationParams;
|
|
24
|
+
workspaceBaseline: WorkspaceBaseline | undefined;
|
|
25
|
+
}): Promise<DelegationResult>;
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { DEFAULT_SECURITY_CONFIG } from "../../security/config.js";
|
|
2
|
+
import { RecoverableToolError } from "../../shared/recoverable-error.js";
|
|
3
|
+
import { createEmptyUsageTotals } from "../../usage/totals.js";
|
|
4
|
+
import { externalRoleFingerprint } from "../discovery.js";
|
|
5
|
+
import { buildDispatchedText, createDetails } from "../result.js";
|
|
6
|
+
import { buildSubAgentTask, resolveContextualBlocks } from "../task-envelope.js";
|
|
7
|
+
import { releaseWorkspaceLease } from "../workspace-lease.js";
|
|
8
|
+
import { launchExternalRun } from "./run.js";
|
|
9
|
+
/**
|
|
10
|
+
* The `runtime: external` half of `dispatchSubAgentRun` (spec 046, D2.5): launches the harness
|
|
11
|
+
* process and always returns the "[Dispatched]" placeholder — external's sync grace window is
|
|
12
|
+
* always 0, so there is no inline-wait branch to share with the internal path.
|
|
13
|
+
*/
|
|
14
|
+
export async function dispatchExternalRun(input) {
|
|
15
|
+
const { options, config, runLabel, runContext, leaseKey, params } = input;
|
|
16
|
+
let launchResult;
|
|
17
|
+
try {
|
|
18
|
+
// D9/T5: external roles get the same task envelope internal workers do — runtime
|
|
19
|
+
// paths, injected context blocks, and (for purpose=verify) the verification
|
|
20
|
+
// protocol — rather than the raw task text (spec 040 gap closed post-review).
|
|
21
|
+
const contextualBlocks = await resolveContextualBlocks(config, options);
|
|
22
|
+
const envelopedTask = buildSubAgentTask(params.task, config, options.runtimeContext, contextualBlocks, runContext);
|
|
23
|
+
launchResult = await launchExternalRun({
|
|
24
|
+
runManager: input.runManager,
|
|
25
|
+
runId: runContext.runId,
|
|
26
|
+
channelId: options.runtimeContext.channelId,
|
|
27
|
+
channelDir: options.channelDir,
|
|
28
|
+
label: runLabel,
|
|
29
|
+
agent: config.name,
|
|
30
|
+
source: config.source,
|
|
31
|
+
harness: config.harness,
|
|
32
|
+
command: config.command,
|
|
33
|
+
shell: config.shell,
|
|
34
|
+
env: config.env,
|
|
35
|
+
externalModelRef: config.externalModelRef,
|
|
36
|
+
thinkingLevel: config.thinkingLevel,
|
|
37
|
+
maxWallTimeSec: config.maxWallTimeSec,
|
|
38
|
+
systemPrompt: config.systemPrompt,
|
|
39
|
+
task: envelopedTask,
|
|
40
|
+
workingDirectory: runContext.workingDirectory,
|
|
41
|
+
artifactDir: runContext.artifactDir,
|
|
42
|
+
purpose: runContext.purpose,
|
|
43
|
+
taskId: runContext.taskId,
|
|
44
|
+
item: runContext.item,
|
|
45
|
+
leaseKey,
|
|
46
|
+
mutates: config.mutates,
|
|
47
|
+
workspaceBaseline: input.workspaceBaseline,
|
|
48
|
+
roleFingerprint: externalRoleFingerprint(config),
|
|
49
|
+
workspaceDir: options.workspaceDir,
|
|
50
|
+
securityConfig: options.securityConfig ?? DEFAULT_SECURITY_CONFIG,
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
// Only a pre-register() throw (unknown harness, shell-mode misuse) reaches here —
|
|
55
|
+
// every failure past that point settles the run itself and already released this
|
|
56
|
+
// lease (spec 042 D2/D5), so this catch must not release it a second time.
|
|
57
|
+
releaseWorkspaceLease(leaseKey, runContext.runId);
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
// Spec 042 D2: a pre-spawn failure is reported in this same turn instead of a
|
|
61
|
+
// "[Dispatched]" placeholder the model would wait on forever — two of the three
|
|
62
|
+
// failure kinds never used to announce at all. `settle()` already released the lease.
|
|
63
|
+
if (!launchResult.ok) {
|
|
64
|
+
if (launchResult.kind === "missing-binary") {
|
|
65
|
+
throw new Error(`Sub-agent "${config.name}" failed to launch: ${launchResult.reason} Install the CLI or fix "command" in its role file; the run was not dispatched.`);
|
|
66
|
+
}
|
|
67
|
+
throw new RecoverableToolError(`Sub-agent "${config.name}" failed to launch: ${launchResult.reason} The run was not dispatched.`);
|
|
68
|
+
}
|
|
69
|
+
// D2: external's sync grace window is always 0 — always the dispatched placeholder,
|
|
70
|
+
// never an inline wait. The run keeps going in the background and wakes the channel.
|
|
71
|
+
return {
|
|
72
|
+
content: [
|
|
73
|
+
{
|
|
74
|
+
type: "text",
|
|
75
|
+
text: buildDispatchedText(runContext.runId, config.name, `external, ${config.harness}`, runContext.workingDirectory),
|
|
76
|
+
},
|
|
77
|
+
],
|
|
78
|
+
details: createDetails({
|
|
79
|
+
config,
|
|
80
|
+
runContext,
|
|
81
|
+
usage: createEmptyUsageTotals(),
|
|
82
|
+
turns: 0,
|
|
83
|
+
toolCalls: 0,
|
|
84
|
+
durationMs: 0,
|
|
85
|
+
dispatched: true,
|
|
86
|
+
modelOverride: config.externalModelRef ?? "unknown",
|
|
87
|
+
toolsOverride: [],
|
|
88
|
+
}),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { UsageTotals } from "../../
|
|
1
|
+
import type { UsageTotals } from "../../usage/totals.js";
|
|
2
2
|
import type { SubAgentThinkingLevel } from "../discovery.js";
|
|
3
3
|
/**
|
|
4
4
|
* The harness adapter seam (spec 040, D4). Every external run is reduced to the same process
|
|
@@ -1,4 +1,19 @@
|
|
|
1
|
-
import type { RunHarness } from "../
|
|
1
|
+
import type { RunHarness } from "../run-record.js";
|
|
2
|
+
/** No output to either artifact file for this long reads as "possibly stuck". */
|
|
3
|
+
export declare const STALL_THRESHOLD_MS: number;
|
|
4
|
+
/**
|
|
5
|
+
* The pacing rules above, shared by the external tail and an internal run that has gone async
|
|
6
|
+
* (its worker reports steps in-process, so it has labels but no file to poll).
|
|
7
|
+
*/
|
|
8
|
+
export interface ProgressPacer {
|
|
9
|
+
/** Whether a label offered now could be reported — lets a caller skip the work of finding one. */
|
|
10
|
+
ready(now?: number): boolean;
|
|
11
|
+
/** Report `label` if pacing allows and it differs from the last one reported. */
|
|
12
|
+
offer(label: string, now?: number): void;
|
|
13
|
+
}
|
|
14
|
+
export declare function createProgressPacer(startedAt: number, emit: (label: string) => void): ProgressPacer;
|
|
15
|
+
/** When the run last wrote anything to its output files, or `undefined` if neither exists yet. */
|
|
16
|
+
export declare function readLastOutputAt(artifactDir: string): Promise<number | undefined>;
|
|
2
17
|
export interface ExternalProgressTailInput {
|
|
3
18
|
artifactDir: string;
|
|
4
19
|
harnessId: RunHarness;
|
|
@@ -6,6 +21,8 @@ export interface ExternalProgressTailInput {
|
|
|
6
21
|
* run actually started producing output, not from registration. */
|
|
7
22
|
startedAt: number;
|
|
8
23
|
onProgress: (label: string) => void;
|
|
24
|
+
/** Called once per stall (re-armed when output resumes) with how long the run has been silent. */
|
|
25
|
+
onStall?: (silentMs: number) => void;
|
|
9
26
|
}
|
|
10
27
|
export interface ExternalProgressTail {
|
|
11
28
|
stop(): void;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { readFile } from "node:fs/promises";
|
|
1
|
+
import { readFile, stat } from "node:fs/promises";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { getExternalHarness } from "./registry.js";
|
|
4
4
|
/**
|
|
@@ -12,6 +12,10 @@ import { getExternalHarness } from "./registry.js";
|
|
|
12
12
|
* has to handle a half-written trailing line, this doesn't, and a run's artifact file is small
|
|
13
13
|
* enough (single-digit MB even for a long run) that re-reading it every `POLL_MS` costs nothing a
|
|
14
14
|
* background process needs to care about.
|
|
15
|
+
*
|
|
16
|
+
* The same poll also watches for a stall: a process that is alive but has written nothing to
|
|
17
|
+
* either output file for `STALL_THRESHOLD_MS` gets one "needs attention" signal — it is not killed,
|
|
18
|
+
* since a long silent build or test run is legitimate; only its wall-time budget ends it.
|
|
15
19
|
*/
|
|
16
20
|
const POLL_MS = 15_000;
|
|
17
21
|
/** A run that finishes inside this window never gets a progress notice — the settled notice
|
|
@@ -22,25 +26,64 @@ const FIRST_NOTICE_DELAY_MS = 45_000;
|
|
|
22
26
|
const MIN_NOTICE_GAP_MS = 180_000;
|
|
23
27
|
/** Ceiling on notices for a single run — even a multi-hour run stops narrating after this many. */
|
|
24
28
|
const MAX_NOTICES = 6;
|
|
25
|
-
|
|
29
|
+
/** No output to either artifact file for this long reads as "possibly stuck". */
|
|
30
|
+
export const STALL_THRESHOLD_MS = 10 * 60_000;
|
|
31
|
+
/** A run that keeps stalling and recovering stops being reported after this many stall notices. */
|
|
32
|
+
const MAX_STALL_NOTICES = 3;
|
|
33
|
+
const OUTPUT_FILENAMES = ["events.jsonl", "stderr.log"];
|
|
34
|
+
export function createProgressPacer(startedAt, emit) {
|
|
35
|
+
let lastLabel;
|
|
36
|
+
let lastNoticeAt = 0;
|
|
37
|
+
let noticeCount = 0;
|
|
38
|
+
const ready = (now = Date.now()) => noticeCount < MAX_NOTICES &&
|
|
39
|
+
now - startedAt >= FIRST_NOTICE_DELAY_MS &&
|
|
40
|
+
(!lastNoticeAt || now - lastNoticeAt >= MIN_NOTICE_GAP_MS);
|
|
41
|
+
return {
|
|
42
|
+
ready,
|
|
43
|
+
offer(label, now = Date.now()) {
|
|
44
|
+
if (!label || label === lastLabel || !ready(now))
|
|
45
|
+
return;
|
|
46
|
+
lastLabel = label;
|
|
47
|
+
lastNoticeAt = now;
|
|
48
|
+
noticeCount++;
|
|
49
|
+
emit(label);
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/** When the run last wrote anything to its output files, or `undefined` if neither exists yet. */
|
|
54
|
+
export async function readLastOutputAt(artifactDir) {
|
|
55
|
+
const times = await Promise.all(OUTPUT_FILENAMES.map((name) => stat(join(artifactDir, name)).then((info) => (info.size > 0 ? info.mtimeMs : undefined), () => undefined)));
|
|
56
|
+
const known = times.filter((time) => time !== undefined);
|
|
57
|
+
return known.length > 0 ? Math.max(...known) : undefined;
|
|
58
|
+
}
|
|
26
59
|
/** Starts polling; returns a handle whose `stop()` is idempotent and always safe to call. */
|
|
27
60
|
export function startExternalProgressTail(input) {
|
|
28
61
|
const harness = getExternalHarness(input.harnessId);
|
|
62
|
+
// exec has no structured protocol to read mid-run, so it gets stall detection only.
|
|
29
63
|
const toProgressLabel = harness?.toProgressLabel;
|
|
30
|
-
if (!toProgressLabel)
|
|
31
|
-
return NOOP_TAIL; // exec, or a harness that hasn't implemented this.
|
|
32
64
|
const eventsPath = join(input.artifactDir, "events.jsonl");
|
|
33
|
-
|
|
34
|
-
let lastNoticeAt = 0;
|
|
35
|
-
let noticeCount = 0;
|
|
65
|
+
const pacer = createProgressPacer(input.startedAt, input.onProgress);
|
|
36
66
|
let stopped = false;
|
|
37
|
-
|
|
38
|
-
|
|
67
|
+
/** Output time the current stall was reported against; a newer write re-arms detection. */
|
|
68
|
+
let stalledSince;
|
|
69
|
+
let stallCount = 0;
|
|
70
|
+
const checkStall = async (now) => {
|
|
71
|
+
if (!input.onStall || stallCount >= MAX_STALL_NOTICES)
|
|
39
72
|
return;
|
|
40
|
-
const
|
|
41
|
-
if (
|
|
73
|
+
const lastOutputAt = (await readLastOutputAt(input.artifactDir)) ?? input.startedAt;
|
|
74
|
+
if (stalledSince !== undefined && lastOutputAt > stalledSince)
|
|
75
|
+
stalledSince = undefined;
|
|
76
|
+
if (stalledSince !== undefined || stopped)
|
|
77
|
+
return;
|
|
78
|
+
const silentMs = now - lastOutputAt;
|
|
79
|
+
if (silentMs < STALL_THRESHOLD_MS)
|
|
42
80
|
return;
|
|
43
|
-
|
|
81
|
+
stalledSince = lastOutputAt;
|
|
82
|
+
stallCount++;
|
|
83
|
+
input.onStall(silentMs);
|
|
84
|
+
};
|
|
85
|
+
const checkProgress = async (now) => {
|
|
86
|
+
if (!toProgressLabel || !pacer.ready(now))
|
|
44
87
|
return;
|
|
45
88
|
let text;
|
|
46
89
|
try {
|
|
@@ -66,12 +109,16 @@ export function startExternalProgressTail(input) {
|
|
|
66
109
|
if (label)
|
|
67
110
|
break;
|
|
68
111
|
}
|
|
69
|
-
if (!label ||
|
|
112
|
+
if (!label || stopped)
|
|
70
113
|
return;
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
114
|
+
pacer.offer(label, now);
|
|
115
|
+
};
|
|
116
|
+
const tick = async () => {
|
|
117
|
+
if (stopped)
|
|
118
|
+
return;
|
|
119
|
+
const now = Date.now();
|
|
120
|
+
await checkStall(now);
|
|
121
|
+
await checkProgress(now);
|
|
75
122
|
};
|
|
76
123
|
// `tick` is async and its result is discarded: a rejection here (a throwing `onProgress`
|
|
77
124
|
// callback, say) would otherwise surface as an unhandled rejection and reach the process-level
|
|
@@ -2,7 +2,9 @@ import { spawn as nodeSpawn } from "node:child_process";
|
|
|
2
2
|
import type { SecurityConfig } from "../../security/types.js";
|
|
3
3
|
import { probeCliVersion, readProcessStartTime } from "../../shared/host-process.js";
|
|
4
4
|
import type { SubAgentThinkingLevel } from "../discovery.js";
|
|
5
|
-
import type { RunMutates
|
|
5
|
+
import type { RunMutates } from "../run-record.js";
|
|
6
|
+
import type { SubAgentRunManager } from "../runs.js";
|
|
7
|
+
import type { WorkspaceBaseline } from "../workspace-summary.js";
|
|
6
8
|
/**
|
|
7
9
|
* The external-run orchestrator (spec 040, D1/D3/D4). One prompt, one short-lived, argv-direct,
|
|
8
10
|
* detached process. The launch order matters (D1): admission and the lease are the caller's job
|
|
@@ -44,6 +46,8 @@ export interface LaunchExternalRunInput {
|
|
|
44
46
|
resumeSessionId?: string;
|
|
45
47
|
/** The role's own `mutates` declaration, carried through to the dispatch audit event (D8.1). */
|
|
46
48
|
mutates?: RunMutates;
|
|
49
|
+
/** A write run's dispatch-time dirty-path snapshot (see `workspace-summary.ts`). */
|
|
50
|
+
workspaceBaseline?: WorkspaceBaseline;
|
|
47
51
|
/** Spec 042 D7: fingerprint of the role's `command`/`externalModelRef`/`shell`, persisted so a
|
|
48
52
|
* later `follow_up` can detect a hot-edited role before resuming under it. */
|
|
49
53
|
roleFingerprint?: string;
|
|
@@ -7,7 +7,7 @@ import { logSecurityEvent } from "../../security/logger.js";
|
|
|
7
7
|
import { killProcessGroup, probeCliVersion, readProcessStartTime, reapProcessGroup, } from "../../shared/host-process.js";
|
|
8
8
|
import { splitShellWords } from "../../shared/shell-words.js";
|
|
9
9
|
import { errorMessage } from "../../shared/text-utils.js";
|
|
10
|
-
import { createEmptyUsageTotals } from "../../
|
|
10
|
+
import { createEmptyUsageTotals } from "../../usage/totals.js";
|
|
11
11
|
import { getExternalHarness } from "./registry.js";
|
|
12
12
|
import { finalizeExternalRun } from "./settlement.js";
|
|
13
13
|
/**
|
|
@@ -119,7 +119,7 @@ export async function launchExternalRun(input) {
|
|
|
119
119
|
if (input.shell && harness.id !== "exec") {
|
|
120
120
|
throw new Error(`External harness "${harness.id}" cannot use shell mode because it would bypass protocol argv assembly. Use a wrapper script as command, or use harness: exec.`);
|
|
121
121
|
}
|
|
122
|
-
// `
|
|
122
|
+
// `dispatch.ts` already creates the artifact dir for a fresh run; `follow_up` (subagent-manage.ts)
|
|
123
123
|
// mints a new runId/artifactDir on the spot, so this is the one place that must be reliable
|
|
124
124
|
// either way.
|
|
125
125
|
await mkdir(input.artifactDir, { recursive: true });
|
|
@@ -169,6 +169,7 @@ export async function launchExternalRun(input) {
|
|
|
169
169
|
channelDir: input.channelDir,
|
|
170
170
|
leaseKey: input.leaseKey,
|
|
171
171
|
mutates: input.mutates,
|
|
172
|
+
workspaceBaseline: input.workspaceBaseline,
|
|
172
173
|
});
|
|
173
174
|
// The final executable/argv/cwd/capability record must be durable before a process can exist.
|
|
174
175
|
// `external-agent` uses the strict appender path and rejects on queue or I/O failure; a failure
|
|
@@ -305,7 +306,10 @@ export async function launchExternalRun(input) {
|
|
|
305
306
|
await closePromise;
|
|
306
307
|
const reason = `Failed to persist external launch state: ${errorMessage(error)}`;
|
|
307
308
|
await runManager.settle(input.runId, failedSettleInput(reason), { announce: false }).catch((settleError) => {
|
|
308
|
-
log.
|
|
309
|
+
log.logWarn("subagent.settle.failed", "External run settlement after launch-persistence failure failed", {
|
|
310
|
+
reason: errorMessage(settleError),
|
|
311
|
+
fields: { runId: input.runId },
|
|
312
|
+
});
|
|
309
313
|
});
|
|
310
314
|
throw error;
|
|
311
315
|
}
|
|
@@ -346,15 +350,19 @@ export async function launchExternalRun(input) {
|
|
|
346
350
|
Promise.resolve().then(() => (input.probeCliVersionFn ?? probeCliVersion)(invocation.executable)),
|
|
347
351
|
])
|
|
348
352
|
.then(async ([pidStartedAt, cliVersion]) => {
|
|
349
|
-
await runManager
|
|
350
|
-
|
|
351
|
-
|
|
353
|
+
await runManager.updateLaunchMetadata(input.runId, { pidStartedAt, cliVersion }).catch((error) => log.logWarn("subagent.launch_probes.persist_failed", "Launch probe persist failed", {
|
|
354
|
+
reason: errorMessage(error),
|
|
355
|
+
fields: { runId: input.runId },
|
|
356
|
+
}));
|
|
352
357
|
})
|
|
353
358
|
.catch((error) => {
|
|
354
359
|
// The production probes are already best-effort; keep the same property for test seams or
|
|
355
360
|
// a future host implementation and never leave a spawned child unobserved because metadata
|
|
356
361
|
// collection failed.
|
|
357
|
-
log.
|
|
362
|
+
log.logWarn("subagent.launch_probes.collect_failed", "Launch probe collection failed", {
|
|
363
|
+
reason: errorMessage(error),
|
|
364
|
+
fields: { runId: input.runId },
|
|
365
|
+
});
|
|
358
366
|
});
|
|
359
367
|
// Deliberately attach the close watcher before waiting for probe metadata. A fast child can exit
|
|
360
368
|
// during that wait; the promise is already listening, and finalization waits for the launch
|
|
@@ -384,17 +392,23 @@ export async function launchExternalRun(input) {
|
|
|
384
392
|
terminationReason,
|
|
385
393
|
maxWallTimeSec: input.maxWallTimeSec,
|
|
386
394
|
mutates: input.mutates,
|
|
395
|
+
workspaceBaseline: input.workspaceBaseline,
|
|
387
396
|
}, (settleInput, options) => runManager.settle(input.runId, settleInput, options), { announce: terminationReason !== "cancelled" }).catch((error) => {
|
|
388
|
-
log.
|
|
397
|
+
log.logWarn("subagent.settle.failed", "External run settlement failed", {
|
|
398
|
+
reason: errorMessage(error),
|
|
399
|
+
fields: { runId: input.runId },
|
|
400
|
+
});
|
|
389
401
|
});
|
|
390
402
|
});
|
|
391
|
-
await launchMetadataPromise;
|
|
392
403
|
// The narrow window between the pre-spawn placeholder handle (claimExternalLaunch) and the
|
|
393
404
|
// real one just above: a cancel arriving there durably marked `terminationReason` (P1-1) but
|
|
394
405
|
// had no live process to kill yet. Act on it now.
|
|
395
406
|
if (runManager.get(input.runId)?.terminationReason === "cancelled") {
|
|
396
407
|
void killProcessGroup(pid);
|
|
397
408
|
}
|
|
409
|
+
// The dispatching tool call does not wait for the probes: the pid is already durable and the
|
|
410
|
+
// cancel handle installed, so they are diagnostics only. Settlement still waits for them (the
|
|
411
|
+
// close watcher above) so a run's terminal record carries them.
|
|
398
412
|
return { ok: true };
|
|
399
413
|
function failedSettleInput(reason) {
|
|
400
414
|
return {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type { RunHarness, RunMutates, SettleInput } from "../
|
|
1
|
+
import type { RunHarness, RunMutates, SettleInput } from "../run-record.js";
|
|
2
|
+
import { type WorkspaceBaseline } from "../workspace-summary.js";
|
|
2
3
|
import { type ExternalOutcome } from "./harness.js";
|
|
3
4
|
export interface BuildExternalSettleInputInput {
|
|
4
5
|
harnessId: RunHarness;
|
|
@@ -30,6 +31,8 @@ export interface FinalizeExternalRunInput {
|
|
|
30
31
|
/** P2-2: only a `write` run's completion pays for a `git status` summary — a `read` run cannot
|
|
31
32
|
* have changed anything, and this must never become a hidden cost on the common read-only path. */
|
|
32
33
|
mutates?: RunMutates;
|
|
34
|
+
/** The run's dispatch-time snapshot, so the summary leaves out paths that were already dirty. */
|
|
35
|
+
workspaceBaseline?: WorkspaceBaseline;
|
|
33
36
|
}
|
|
34
37
|
/**
|
|
35
38
|
* Read this run's artifact files, parse them through its harness, decide its verdict (for a
|
|
@@ -83,7 +83,7 @@ export async function finalizeExternalRun(input, settle, options) {
|
|
|
83
83
|
// P2-2: only for a run that actually could have changed the working directory, and only once it
|
|
84
84
|
// is known to have finished cleanly — best-effort, never blocks or fails settlement.
|
|
85
85
|
if (input.mutates === "write" && settleInput.status === "completed") {
|
|
86
|
-
const workspaceSummary = await changedPathsSummary(input.workingDirectory).catch(() => undefined);
|
|
86
|
+
const workspaceSummary = await changedPathsSummary(input.workingDirectory, input.workspaceBaseline).catch(() => undefined);
|
|
87
87
|
if (workspaceSummary)
|
|
88
88
|
settleInput = { ...settleInput, workspaceSummary };
|
|
89
89
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { formatDuration } from "../shared/format.js";
|
|
2
|
-
import type { RunRecord } from "./
|
|
2
|
+
import type { RunRecord } from "./run-record.js";
|
|
3
3
|
/**
|
|
4
4
|
* Shared display primitives for delegation runs (spec 041), used by both the model-facing
|
|
5
5
|
* `subagent_list`/`subagent_run` tools and the human-facing `/subagents` runtime command. Only the pieces that
|