@caupulican/pi-adaptative 0.93.3 → 0.93.5
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/CHANGELOG.md +28 -0
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +15 -9
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomy/approval-gate.d.ts +1 -0
- package/dist/core/autonomy/approval-gate.d.ts.map +1 -1
- package/dist/core/autonomy/approval-gate.js +4 -1
- package/dist/core/autonomy/approval-gate.js.map +1 -1
- package/dist/core/autonomy/composite-tool-gate.d.ts +13 -0
- package/dist/core/autonomy/composite-tool-gate.d.ts.map +1 -0
- package/dist/core/autonomy/composite-tool-gate.js +44 -0
- package/dist/core/autonomy/composite-tool-gate.js.map +1 -0
- package/dist/core/autonomy/envelope-enforcement.d.ts +2 -0
- package/dist/core/autonomy/envelope-enforcement.d.ts.map +1 -1
- package/dist/core/autonomy/envelope-enforcement.js +48 -7
- package/dist/core/autonomy/envelope-enforcement.js.map +1 -1
- package/dist/core/autonomy/gates.d.ts.map +1 -1
- package/dist/core/autonomy/gates.js +48 -76
- package/dist/core/autonomy/gates.js.map +1 -1
- package/dist/core/autonomy/path-scope.d.ts.map +1 -1
- package/dist/core/autonomy/path-scope.js +7 -7
- package/dist/core/autonomy/path-scope.js.map +1 -1
- package/dist/core/background-tool-task-controller.d.ts +2 -0
- package/dist/core/background-tool-task-controller.d.ts.map +1 -1
- package/dist/core/background-tool-task-controller.js +13 -5
- package/dist/core/background-tool-task-controller.js.map +1 -1
- package/dist/core/compaction-controller.d.ts +3 -0
- package/dist/core/compaction-controller.d.ts.map +1 -1
- package/dist/core/compaction-controller.js +132 -97
- package/dist/core/compaction-controller.js.map +1 -1
- package/dist/core/delegation/session-root-mailbox.d.ts.map +1 -1
- package/dist/core/delegation/session-root-mailbox.js +14 -1
- package/dist/core/delegation/session-root-mailbox.js.map +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.d.ts.map +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.js +6 -9
- package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
- package/dist/core/delegation/worker-authority-resolver.d.ts.map +1 -1
- package/dist/core/delegation/worker-authority-resolver.js +3 -2
- package/dist/core/delegation/worker-authority-resolver.js.map +1 -1
- package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -1
- package/dist/core/delegation/worker-execution-policy.js +10 -8
- package/dist/core/delegation/worker-execution-policy.js.map +1 -1
- package/dist/core/foreground-recovery-controller.d.ts +2 -0
- package/dist/core/foreground-recovery-controller.d.ts.map +1 -1
- package/dist/core/foreground-recovery-controller.js +18 -9
- package/dist/core/foreground-recovery-controller.js.map +1 -1
- package/dist/core/goal-loop-controller.d.ts.map +1 -1
- package/dist/core/goal-loop-controller.js +3 -5
- package/dist/core/goal-loop-controller.js.map +1 -1
- package/dist/core/goals/goal-auto-continue-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-auto-continue-controller.js +6 -0
- package/dist/core/goals/goal-auto-continue-controller.js.map +1 -1
- package/dist/core/goals/goal-state.d.ts.map +1 -1
- package/dist/core/goals/goal-state.js +1 -0
- package/dist/core/goals/goal-state.js.map +1 -1
- package/dist/core/goals/goal-tool-core.d.ts +2 -0
- package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
- package/dist/core/goals/goal-tool-core.js +1 -1
- package/dist/core/goals/goal-tool-core.js.map +1 -1
- package/dist/core/orchestration/capability-gateway.d.ts.map +1 -1
- package/dist/core/orchestration/capability-gateway.js +32 -9
- package/dist/core/orchestration/capability-gateway.js.map +1 -1
- package/dist/core/orchestration/lane-tool-manifests.js +5 -5
- package/dist/core/orchestration/lane-tool-manifests.js.map +1 -1
- package/dist/core/orchestration/policy-compiler.d.ts.map +1 -1
- package/dist/core/orchestration/policy-compiler.js +7 -0
- package/dist/core/orchestration/policy-compiler.js.map +1 -1
- package/dist/core/orchestration/profile-registry.js +2 -2
- package/dist/core/orchestration/profile-registry.js.map +1 -1
- package/dist/core/pipelines/active-context.d.ts +16 -0
- package/dist/core/pipelines/active-context.d.ts.map +1 -0
- package/dist/core/pipelines/active-context.js +29 -0
- package/dist/core/pipelines/active-context.js.map +1 -0
- package/dist/core/pipelines/context.d.ts +1 -1
- package/dist/core/pipelines/context.d.ts.map +1 -1
- package/dist/core/pipelines/context.js +40 -31
- package/dist/core/pipelines/context.js.map +1 -1
- package/dist/core/pipelines/discover.d.ts +5 -1
- package/dist/core/pipelines/discover.d.ts.map +1 -1
- package/dist/core/pipelines/discover.js +91 -33
- package/dist/core/pipelines/discover.js.map +1 -1
- package/dist/core/pipelines/increment.d.ts +0 -2
- package/dist/core/pipelines/increment.d.ts.map +1 -1
- package/dist/core/pipelines/increment.js +35 -13
- package/dist/core/pipelines/increment.js.map +1 -1
- package/dist/core/pipelines/index.d.ts +4 -3
- package/dist/core/pipelines/index.d.ts.map +1 -1
- package/dist/core/pipelines/index.js +4 -3
- package/dist/core/pipelines/index.js.map +1 -1
- package/dist/core/pipelines/run-state.d.ts +8 -0
- package/dist/core/pipelines/run-state.d.ts.map +1 -1
- package/dist/core/pipelines/run-state.js +172 -38
- package/dist/core/pipelines/run-state.js.map +1 -1
- package/dist/core/pipelines/types.d.ts +2 -0
- package/dist/core/pipelines/types.d.ts.map +1 -1
- package/dist/core/pipelines/types.js +21 -4
- package/dist/core/pipelines/types.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +2 -1
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +46 -10
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/skill-vault.d.ts +18 -14
- package/dist/core/skill-vault.d.ts.map +1 -1
- package/dist/core/skill-vault.js +140 -81
- package/dist/core/skill-vault.js.map +1 -1
- package/dist/core/system-prompt-builder.d.ts +1 -0
- package/dist/core/system-prompt-builder.d.ts.map +1 -1
- package/dist/core/system-prompt-builder.js +25 -1
- package/dist/core/system-prompt-builder.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +6 -1
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tasks/task-projection.d.ts +2 -0
- package/dist/core/tasks/task-projection.d.ts.map +1 -1
- package/dist/core/tasks/task-projection.js +2 -0
- package/dist/core/tasks/task-projection.js.map +1 -1
- package/dist/core/tasks/task-state.d.ts +10 -0
- package/dist/core/tasks/task-state.d.ts.map +1 -1
- package/dist/core/tasks/task-state.js +43 -2
- package/dist/core/tasks/task-state.js.map +1 -1
- package/dist/core/tool-capability-policy.d.ts +13 -3
- package/dist/core/tool-capability-policy.d.ts.map +1 -1
- package/dist/core/tool-capability-policy.js +136 -28
- package/dist/core/tool-capability-policy.js.map +1 -1
- package/dist/core/tools/bash.d.ts +3 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +13 -4
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit-diff.d.ts.map +1 -1
- package/dist/core/tools/edit-diff.js +45 -7
- package/dist/core/tools/edit-diff.js.map +1 -1
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +4 -0
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/goal.d.ts.map +1 -1
- package/dist/core/tools/goal.js +17 -1
- package/dist/core/tools/goal.js.map +1 -1
- package/dist/core/tools/orchestration-panel.d.ts.map +1 -1
- package/dist/core/tools/orchestration-panel.js +1 -0
- package/dist/core/tools/orchestration-panel.js.map +1 -1
- package/dist/core/tools/persistent-process-coordinator.d.ts.map +1 -1
- package/dist/core/tools/persistent-process-coordinator.js +12 -7
- package/dist/core/tools/persistent-process-coordinator.js.map +1 -1
- package/dist/core/tools/pipeline.d.ts +1 -0
- package/dist/core/tools/pipeline.d.ts.map +1 -1
- package/dist/core/tools/pipeline.js +95 -44
- package/dist/core/tools/pipeline.js.map +1 -1
- package/dist/core/tools/secret-store.d.ts.map +1 -1
- package/dist/core/tools/secret-store.js +2 -1
- package/dist/core/tools/secret-store.js.map +1 -1
- package/dist/core/tools/shell-session.d.ts +3 -1
- package/dist/core/tools/shell-session.d.ts.map +1 -1
- package/dist/core/tools/shell-session.js +96 -16
- package/dist/core/tools/shell-session.js.map +1 -1
- package/dist/core/tools/skill.d.ts +1 -1
- package/dist/core/tools/skill.d.ts.map +1 -1
- package/dist/core/tools/skill.js +20 -11
- package/dist/core/tools/skill.js.map +1 -1
- package/dist/core/tools/task-steps.d.ts +10 -0
- package/dist/core/tools/task-steps.d.ts.map +1 -1
- package/dist/core/tools/task-steps.js +70 -29
- package/dist/core/tools/task-steps.js.map +1 -1
- package/dist/core/tools/windows-shell-engine.d.ts.map +1 -1
- package/dist/core/tools/windows-shell-engine.js +6 -1
- package/dist/core/tools/windows-shell-engine.js.map +1 -1
- package/dist/core/util/bounded-file.d.ts +8 -0
- package/dist/core/util/bounded-file.d.ts.map +1 -1
- package/dist/core/util/bounded-file.js +81 -16
- package/dist/core/util/bounded-file.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-authority-resolver.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-authority-resolver.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAGpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;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CAAgC,EAAE,MAAM,gCAAgC,CAAC;AAEvF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,8BAA8B,CAAC;AAE1E;;;;;;;GAOG;AACH,eAAO,MAAM,8BAA8B,OAAQ,CAAC;AAyBpD,MAAM,WAAW,8BAA8B;IAC9C,SAAS,CAAC,EAAE,gCAAgC,CAAC;IAC7C,IAAI,CAAC,EAAE,qBAAqB,CAAC;IAC7B,QAAQ,CAAC,EAAE,yBAAyB,CAAC;IACrC,eAAe,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IAC7B,aAAa,EAAE,aAAa,CAAC;IAC7B,gBAAgB,CAAC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC;CAC7C;AAED,MAAM,MAAM,yBAAyB,GAClC;IACA,EAAE,EAAE,IAAI,CAAC;IACT,QAAQ,EAAE,qBAAqB,CAAC;IAChC,kBAAkB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACvC,mBAAmB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACvC,GACD;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAqCjC,8FAA8F;AAC9F,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,8BAA8B,GAAG,yBAAyB,CA6HvG"}
|
|
@@ -4,7 +4,7 @@ import { mapToolNamesForPlatform, STABLE_SHELL_TOOL_NAME } from "../default-tool
|
|
|
4
4
|
import { ORCHESTRATION_SCHEMA_VERSION, } from "../orchestration/contracts.js";
|
|
5
5
|
import { CLASSIFIED_LANE_TOOL_NAMES } from "../orchestration/lane-tool-manifests.js";
|
|
6
6
|
import { resolvePinnedOrchestrationModel } from "../orchestration/model-binding.js";
|
|
7
|
-
import { getToolCapabilityPolicy } from "../tool-capability-policy.js";
|
|
7
|
+
import { envelopeHasToolCapability, getToolCapabilityPolicy } from "../tool-capability-policy.js";
|
|
8
8
|
import { LEAN_WORKER_DELEGATION_LIMITS } from "./worker-fleet-limits.js";
|
|
9
9
|
/**
|
|
10
10
|
* Smallest token grant a worker can survive on. A worker's first response pays the full
|
|
@@ -111,12 +111,13 @@ export function resolveWorkerAuthority(input) {
|
|
|
111
111
|
if (uniqueToolNames.includes("delegate") && inheritsDelegation) {
|
|
112
112
|
capabilities.add("workflow.delegate");
|
|
113
113
|
}
|
|
114
|
+
const capabilityList = [...capabilities];
|
|
114
115
|
const toolNames = [];
|
|
115
116
|
for (const toolName of uniqueToolNames) {
|
|
116
117
|
const policy = getToolCapabilityPolicy(toolName);
|
|
117
118
|
if (!policy)
|
|
118
119
|
return { ok: false, reason: `orchestration_tool_unclassified:${toolName}` };
|
|
119
|
-
if (
|
|
120
|
+
if (envelopeHasToolCapability(capabilityList, toolName)) {
|
|
120
121
|
toolNames.push(toolName);
|
|
121
122
|
continue;
|
|
122
123
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-authority-resolver.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-authority-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAE7F,OAAO,EAEN,4BAA4B,GAG5B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,0BAA0B,EAAE,MAAM,yCAAyC,CAAC;AACrF,OAAO,EAAE,+BAA+B,EAAE,MAAM,mCAAmC,CAAC;AACpF,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAEvE,OAAO,EAAE,6BAA6B,EAAE,MAAM,0BAA0B,CAAC;AAGzE;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,KAAK,CAAC;AAEpD,MAAM,kBAAkB,GAAG;IAC1B,MAAM;IACN,MAAM;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AC,8BAA8B,IAAI,KAAK;QAC3F,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,OAAO,CAAC,qBAAqB;YAC5C,CAAC,CAAC,EAAE,qBAAqB,EAAE,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,qBAAqB,EAAE;YACrE,CAAC,CAAC,EAAE,CAAC;QACN,SAAS,EAAE,GAAG;QACd,SAAS,EAAE,GAAG;KACd,CAAC;IACF,OAAO;QACN,EAAE,EAAE,IAAI;QACR,QAAQ,EAAE;YACT,KAAK,EAAE,aAAa,CAAC,KAAK;YAC1B,YAAY,EAAE,aAAa,CAAC,OAAO;YACnC,OAAO;YACP,gBAAgB,EAAE,eAAe,CAAC,KAAK,CAAC,IAAI,EAAE,gBAAgB,IAAI,EAAE,CAAC;YACrE,GAAG,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACtD;QACD,GAAG,CAAC,KAAK,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC,CAAC,EAAE,kBAAkB,EAAE,CAAC,GAAG,KAAK,CAAC,SAAS,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7F,GAAG,CAAC,KAAK,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC,CAAC,EAAE,mBAAmB,EAAE,CAAC,GAAG,KAAK,CAAC,SAAS,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAChG,CAAC;AACH,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { Api, Model } from \"@caupulican/pi-ai\";\nimport { resolveModelThinkingLevel } from \"@caupulican/pi-ai/models\";\nimport { mapToolNamesForPlatform, STABLE_SHELL_TOOL_NAME } from \"../default-tool-surface.ts\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport {\n\ttype HarnessCapability,\n\tORCHESTRATION_SCHEMA_VERSION,\n\ttype OrchestrationModelBinding,\n\ttype OrchestrationProfile,\n} from \"../orchestration/contracts.ts\";\nimport { CLASSIFIED_LANE_TOOL_NAMES } from \"../orchestration/lane-tool-manifests.ts\";\nimport { resolvePinnedOrchestrationModel } from \"../orchestration/model-binding.ts\";\nimport { getToolCapabilityPolicy } from \"../tool-capability-policy.ts\";\nimport type { WorkerDelegationAuthorityRequest } from \"./worker-delegation-request.ts\";\nimport { LEAN_WORKER_DELEGATION_LIMITS } from \"./worker-fleet-limits.ts\";\nimport type { ResolvedWorkerProfile } from \"./worker-profile-resolver.ts\";\n\n/**\n * Smallest token grant a worker can survive on. A worker's first response pays the full\n * uncached system prompt (~3.3k budgeted tokens in the field), so grants below this floor\n * starve mid-flight with every tool call denied `token_budget_exhausted` — reject them at\n * admission with an explicit reason instead (field session 019fd4dc: 8-9k grants died in\n * 2-3 responses under face-value cache-read counting; the floor plus discounted counting\n * makes small grants viable again).\n */\nexport const MIN_VIABLE_WORKER_TOKEN_BUDGET = 5_000;\n\nconst DEFAULT_TOOL_NAMES = [\n\t\"read\",\n\t\"grep\",\n\t\"find\",\n\t\"ls\",\n\t\"write\",\n\t\"edit\",\n\t\"memory\",\n\tSTABLE_SHELL_TOOL_NAME,\n\t\"delegate\",\n] as const;\nconst AVAILABLE_TOOL_NAMES: ReadonlySet<string> = new Set([...CLASSIFIED_LANE_TOOL_NAMES, \"delegate\"]);\nconst DEFAULT_CAPABILITIES: readonly HarnessCapability[] = [\n\t\"filesystem.read\",\n\t\"filesystem.write\",\n\t\"worktree.read\",\n\t\"worktree.mutate\",\n\t\"process.exec\",\n\t\"network.http\",\n\t\"service.mcp\",\n\t\"memory.query\",\n];\n\nexport interface WorkerAuthorityResolutionInput {\n\tauthority?: WorkerDelegationAuthorityRequest;\n\tbase?: ResolvedWorkerProfile;\n\tmodelPin?: OrchestrationModelBinding;\n\tforegroundModel?: Model<Api>;\n\tmodelRegistry: ModelRegistry;\n\tisModelExhausted(model: Model<Api>): boolean;\n}\n\nexport type WorkerAuthorityResolution =\n\t| {\n\t\t\tok: true;\n\t\t\tshipment: ResolvedWorkerProfile;\n\t\t\trequestedReadPaths?: readonly string[];\n\t\t\trequestedWritePaths?: readonly string[];\n\t }\n\t| { ok: false; reason: string };\n\nfunction selectModelBinding(\n\tmodelPin: OrchestrationModelBinding | undefined,\n\tauthority: WorkerDelegationAuthorityRequest | undefined,\n\tbase: ResolvedWorkerProfile | undefined,\n\tforegroundModel: Model<Api> | undefined,\n\tmodelRegistry: ModelRegistry,\n): OrchestrationModelBinding | undefined {\n\tif (modelPin) return { ...modelPin };\n\tconst provider = authority?.model?.provider ?? base?.modelBinding.provider ?? foregroundModel?.provider;\n\tconst modelId = authority?.model?.modelId ?? base?.modelBinding.modelId ?? foregroundModel?.id;\n\tif (!provider || !modelId) return undefined;\n\tconst sameAsBase = provider === base?.modelBinding.provider && modelId === base.modelBinding.modelId;\n\tconst selectedModel = modelRegistry.find(provider, modelId);\n\tconst thinkingLevel =\n\t\tauthority?.thinkingLevel ??\n\t\t(sameAsBase\n\t\t\t? base.modelBinding.thinkingLevel\n\t\t\t: foregroundModel && provider === foregroundModel.provider && modelId === foregroundModel.id\n\t\t\t\t? resolveModelThinkingLevel(foregroundModel, undefined)\n\t\t\t\t: selectedModel\n\t\t\t\t\t? resolveModelThinkingLevel(selectedModel, undefined)\n\t\t\t\t\t: \"off\");\n\treturn { provider, modelId, thinkingLevel };\n}\n\nfunction adaptiveProfileId(value: object): string {\n\treturn `adaptive-${createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\").slice(0, 32)}`;\n}\n\nfunction tokenBudgetFloorFailure(maxTokens: number | undefined): string | undefined {\n\treturn maxTokens !== undefined && maxTokens < MIN_VIABLE_WORKER_TOKEN_BUDGET\n\t\t? `token_budget_below_floor:requested=${maxTokens},min=${MIN_VIABLE_WORKER_TOKEN_BUDGET}`\n\t\t: undefined;\n}\n\n/** Materialize free-form model choices as one immutable profile-shaped execution snapshot. */\nexport function resolveWorkerAuthority(input: WorkerAuthorityResolutionInput): WorkerAuthorityResolution {\n\tif (!input.authority && input.base) {\n\t\tconst floorFailure = tokenBudgetFloorFailure(input.base.profile.budget.maxTokens);\n\t\tif (floorFailure) return { ok: false, reason: floorFailure };\n\t\tif (!input.modelPin) return { ok: true, shipment: input.base };\n\t\tconst resolvedModel = resolvePinnedOrchestrationModel(\n\t\t\tinput.modelPin,\n\t\t\tinput.modelRegistry,\n\t\t\tinput.isModelExhausted,\n\t\t);\n\t\tif (!resolvedModel) return { ok: false, reason: \"orchestration_model_unavailable\" };\n\t\treturn {\n\t\t\tok: true,\n\t\t\tshipment: {\n\t\t\t\t...input.base,\n\t\t\t\tmodel: resolvedModel.model,\n\t\t\t\tmodelBinding: resolvedModel.binding,\n\t\t\t\tprofile: {\n\t\t\t\t\t...input.base.profile,\n\t\t\t\t\tmodelPolicy: { mode: \"fixed\", candidates: [resolvedModel.binding] },\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\tconst binding = selectModelBinding(\n\t\tinput.modelPin,\n\t\tinput.authority,\n\t\tinput.base,\n\t\tinput.foregroundModel,\n\t\tinput.modelRegistry,\n\t);\n\tif (!binding) return { ok: false, reason: \"orchestration_model_required\" };\n\tconst resolvedModel = resolvePinnedOrchestrationModel(binding, input.modelRegistry, input.isModelExhausted);\n\tif (!resolvedModel) return { ok: false, reason: \"orchestration_model_unavailable\" };\n\n\tconst configuredToolNames = mapToolNamesForPlatform(\n\t\tinput.authority?.toolNames ?? input.base?.profile.toolNames ?? DEFAULT_TOOL_NAMES,\n\t);\n\tconst inheritsDelegation =\n\t\tinput.authority?.capabilities === undefined &&\n\t\t(input.base === undefined ||\n\t\t\t(input.base.profile.toolNames.includes(\"delegate\") &&\n\t\t\t\tinput.base.profile.capabilityCeiling.includes(\"workflow.delegate\")));\n\tconst requestedToolNames =\n\t\tinheritsDelegation && !configuredToolNames.includes(\"delegate\")\n\t\t\t? [...configuredToolNames, \"delegate\"]\n\t\t\t: configuredToolNames;\n\tconst uniqueToolNames = [...new Set(requestedToolNames)];\n\tconst unavailableTools = uniqueToolNames.filter((toolName) => !AVAILABLE_TOOL_NAMES.has(toolName));\n\tif (unavailableTools.length > 0) {\n\t\treturn { ok: false, reason: `orchestration_tool_unavailable:${unavailableTools.join(\",\")}` };\n\t}\n\tconst capabilities = new Set<HarnessCapability>(\n\t\tinput.authority?.capabilities ?? input.base?.profile.capabilityCeiling ?? DEFAULT_CAPABILITIES,\n\t);\n\tif (uniqueToolNames.includes(\"delegate\") && inheritsDelegation) {\n\t\tcapabilities.add(\"workflow.delegate\");\n\t}\n\tconst toolNames: string[] = [];\n\tfor (const toolName of uniqueToolNames) {\n\t\tconst policy = getToolCapabilityPolicy(toolName);\n\t\tif (!policy) return { ok: false, reason: `orchestration_tool_unclassified:${toolName}` };\n\t\tif (policy.capabilityCandidates.some((capability) => capabilities.has(capability))) {\n\t\t\ttoolNames.push(toolName);\n\t\t\tcontinue;\n\t\t}\n\t\tif (input.authority?.toolNames !== undefined) {\n\t\t\treturn { ok: false, reason: `orchestration_tool_capability_missing:${toolName}` };\n\t\t}\n\t}\n\tconst budget = structuredClone(input.authority?.budget ?? input.base?.profile.budget ?? {});\n\tconst floorFailure = tokenBudgetFloorFailure(budget.maxTokens);\n\tif (floorFailure) return { ok: false, reason: floorFailure };\n\tconst role = input.authority?.role ?? input.base?.profile.role ?? \"orchestrator\";\n\tconst delegationLimits = input.base\n\t\t? input.base.profile.delegationLimits\n\t\t: structuredClone(LEAN_WORKER_DELEGATION_LIMITS);\n\tconst now = new Date().toISOString();\n\tconst descriptor = {\n\t\trole,\n\t\tbinding: resolvedModel.binding,\n\t\tcapabilities: [...capabilities],\n\t\ttoolNames,\n\t\tbudget,\n\t\tdelegationLimits: delegationLimits ?? null,\n\t\tresourceProfileNames: input.base?.profile.resourceProfileNames ?? [],\n\t};\n\tconst maxWallClockMs = budget.maxWallClockMs ?? 0;\n\tconst wallClockLeaseTtlMs =\n\t\tmaxWallClockMs > Number.MAX_SAFE_INTEGER - 30_000 ? Number.MAX_SAFE_INTEGER : maxWallClockMs + 30_000;\n\tconst profile: OrchestrationProfile = {\n\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\tprofileId: adaptiveProfileId(descriptor),\n\t\tdescription: \"Admission-time adaptive agent authority\",\n\t\trole,\n\t\tmodelPolicy: { mode: \"fixed\", candidates: [resolvedModel.binding] },\n\t\tcapabilityCeiling: [...capabilities],\n\t\ttoolNames,\n\t\tresourceProfileNames: [...(input.base?.profile.resourceProfileNames ?? [])],\n\t\tdispatchProfileIds: [],\n\t\t...(input.base?.profile.executionPolicy ? { executionPolicy: input.base.profile.executionPolicy } : {}),\n\t\t...(delegationLimits ? { delegationLimits: structuredClone(delegationLimits) } : {}),\n\t\tbudget,\n\t\tmaxConcurrent: Number.MAX_SAFE_INTEGER,\n\t\tleaseTtlMs: Math.max(input.base?.profile.leaseTtlMs ?? 0, wallClockLeaseTtlMs, 90_000),\n\t\trequireIndependentVerification: input.base?.profile.requireIndependentVerification ?? false,\n\t\t...(input.base?.profile.verificationProfileId\n\t\t\t? { verificationProfileId: input.base.profile.verificationProfileId }\n\t\t\t: {}),\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t};\n\treturn {\n\t\tok: true,\n\t\tshipment: {\n\t\t\tmodel: resolvedModel.model,\n\t\t\tmodelBinding: resolvedModel.binding,\n\t\t\tprofile,\n\t\t\tresourcePointers: structuredClone(input.base?.resourcePointers ?? []),\n\t\t\t...(input.base?.soul ? { soul: input.base.soul } : {}),\n\t\t},\n\t\t...(input.authority?.readPaths ? { requestedReadPaths: [...input.authority.readPaths] } : {}),\n\t\t...(input.authority?.writePaths ? { requestedWritePaths: [...input.authority.writePaths] } : {}),\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"worker-authority-resolver.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-authority-resolver.ts"],"names":[],"mappings":"AAAA,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AS,CAAC,CAAC,CAAC,EAAE,kBAAkB,EAAE,CAAC,GAAG,KAAK,CAAC,SAAS,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7F,GAAG,CAAC,KAAK,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC,CAAC,EAAE,mBAAmB,EAAE,CAAC,GAAG,KAAK,CAAC,SAAS,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KAChG,CAAC;AACH,CAAC","sourcesContent":["import { createHash } from \"node:crypto\";\nimport type { Api, Model } from \"@caupulican/pi-ai\";\nimport { resolveModelThinkingLevel } from \"@caupulican/pi-ai/models\";\nimport { mapToolNamesForPlatform, STABLE_SHELL_TOOL_NAME } from \"../default-tool-surface.ts\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport {\n\ttype HarnessCapability,\n\tORCHESTRATION_SCHEMA_VERSION,\n\ttype OrchestrationModelBinding,\n\ttype OrchestrationProfile,\n} from \"../orchestration/contracts.ts\";\nimport { CLASSIFIED_LANE_TOOL_NAMES } from \"../orchestration/lane-tool-manifests.ts\";\nimport { resolvePinnedOrchestrationModel } from \"../orchestration/model-binding.ts\";\nimport { envelopeHasToolCapability, getToolCapabilityPolicy } from \"../tool-capability-policy.ts\";\nimport type { WorkerDelegationAuthorityRequest } from \"./worker-delegation-request.ts\";\nimport { LEAN_WORKER_DELEGATION_LIMITS } from \"./worker-fleet-limits.ts\";\nimport type { ResolvedWorkerProfile } from \"./worker-profile-resolver.ts\";\n\n/**\n * Smallest token grant a worker can survive on. A worker's first response pays the full\n * uncached system prompt (~3.3k budgeted tokens in the field), so grants below this floor\n * starve mid-flight with every tool call denied `token_budget_exhausted` — reject them at\n * admission with an explicit reason instead (field session 019fd4dc: 8-9k grants died in\n * 2-3 responses under face-value cache-read counting; the floor plus discounted counting\n * makes small grants viable again).\n */\nexport const MIN_VIABLE_WORKER_TOKEN_BUDGET = 5_000;\n\nconst DEFAULT_TOOL_NAMES = [\n\t\"read\",\n\t\"grep\",\n\t\"find\",\n\t\"ls\",\n\t\"write\",\n\t\"edit\",\n\t\"memory\",\n\tSTABLE_SHELL_TOOL_NAME,\n\t\"delegate\",\n] as const;\nconst AVAILABLE_TOOL_NAMES: ReadonlySet<string> = new Set([...CLASSIFIED_LANE_TOOL_NAMES, \"delegate\"]);\nconst DEFAULT_CAPABILITIES: readonly HarnessCapability[] = [\n\t\"filesystem.read\",\n\t\"filesystem.write\",\n\t\"worktree.read\",\n\t\"worktree.mutate\",\n\t\"process.exec\",\n\t\"network.http\",\n\t\"service.mcp\",\n\t\"memory.query\",\n];\n\nexport interface WorkerAuthorityResolutionInput {\n\tauthority?: WorkerDelegationAuthorityRequest;\n\tbase?: ResolvedWorkerProfile;\n\tmodelPin?: OrchestrationModelBinding;\n\tforegroundModel?: Model<Api>;\n\tmodelRegistry: ModelRegistry;\n\tisModelExhausted(model: Model<Api>): boolean;\n}\n\nexport type WorkerAuthorityResolution =\n\t| {\n\t\t\tok: true;\n\t\t\tshipment: ResolvedWorkerProfile;\n\t\t\trequestedReadPaths?: readonly string[];\n\t\t\trequestedWritePaths?: readonly string[];\n\t }\n\t| { ok: false; reason: string };\n\nfunction selectModelBinding(\n\tmodelPin: OrchestrationModelBinding | undefined,\n\tauthority: WorkerDelegationAuthorityRequest | undefined,\n\tbase: ResolvedWorkerProfile | undefined,\n\tforegroundModel: Model<Api> | undefined,\n\tmodelRegistry: ModelRegistry,\n): OrchestrationModelBinding | undefined {\n\tif (modelPin) return { ...modelPin };\n\tconst provider = authority?.model?.provider ?? base?.modelBinding.provider ?? foregroundModel?.provider;\n\tconst modelId = authority?.model?.modelId ?? base?.modelBinding.modelId ?? foregroundModel?.id;\n\tif (!provider || !modelId) return undefined;\n\tconst sameAsBase = provider === base?.modelBinding.provider && modelId === base.modelBinding.modelId;\n\tconst selectedModel = modelRegistry.find(provider, modelId);\n\tconst thinkingLevel =\n\t\tauthority?.thinkingLevel ??\n\t\t(sameAsBase\n\t\t\t? base.modelBinding.thinkingLevel\n\t\t\t: foregroundModel && provider === foregroundModel.provider && modelId === foregroundModel.id\n\t\t\t\t? resolveModelThinkingLevel(foregroundModel, undefined)\n\t\t\t\t: selectedModel\n\t\t\t\t\t? resolveModelThinkingLevel(selectedModel, undefined)\n\t\t\t\t\t: \"off\");\n\treturn { provider, modelId, thinkingLevel };\n}\n\nfunction adaptiveProfileId(value: object): string {\n\treturn `adaptive-${createHash(\"sha256\").update(JSON.stringify(value)).digest(\"hex\").slice(0, 32)}`;\n}\n\nfunction tokenBudgetFloorFailure(maxTokens: number | undefined): string | undefined {\n\treturn maxTokens !== undefined && maxTokens < MIN_VIABLE_WORKER_TOKEN_BUDGET\n\t\t? `token_budget_below_floor:requested=${maxTokens},min=${MIN_VIABLE_WORKER_TOKEN_BUDGET}`\n\t\t: undefined;\n}\n\n/** Materialize free-form model choices as one immutable profile-shaped execution snapshot. */\nexport function resolveWorkerAuthority(input: WorkerAuthorityResolutionInput): WorkerAuthorityResolution {\n\tif (!input.authority && input.base) {\n\t\tconst floorFailure = tokenBudgetFloorFailure(input.base.profile.budget.maxTokens);\n\t\tif (floorFailure) return { ok: false, reason: floorFailure };\n\t\tif (!input.modelPin) return { ok: true, shipment: input.base };\n\t\tconst resolvedModel = resolvePinnedOrchestrationModel(\n\t\t\tinput.modelPin,\n\t\t\tinput.modelRegistry,\n\t\t\tinput.isModelExhausted,\n\t\t);\n\t\tif (!resolvedModel) return { ok: false, reason: \"orchestration_model_unavailable\" };\n\t\treturn {\n\t\t\tok: true,\n\t\t\tshipment: {\n\t\t\t\t...input.base,\n\t\t\t\tmodel: resolvedModel.model,\n\t\t\t\tmodelBinding: resolvedModel.binding,\n\t\t\t\tprofile: {\n\t\t\t\t\t...input.base.profile,\n\t\t\t\t\tmodelPolicy: { mode: \"fixed\", candidates: [resolvedModel.binding] },\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}\n\tconst binding = selectModelBinding(\n\t\tinput.modelPin,\n\t\tinput.authority,\n\t\tinput.base,\n\t\tinput.foregroundModel,\n\t\tinput.modelRegistry,\n\t);\n\tif (!binding) return { ok: false, reason: \"orchestration_model_required\" };\n\tconst resolvedModel = resolvePinnedOrchestrationModel(binding, input.modelRegistry, input.isModelExhausted);\n\tif (!resolvedModel) return { ok: false, reason: \"orchestration_model_unavailable\" };\n\n\tconst configuredToolNames = mapToolNamesForPlatform(\n\t\tinput.authority?.toolNames ?? input.base?.profile.toolNames ?? DEFAULT_TOOL_NAMES,\n\t);\n\tconst inheritsDelegation =\n\t\tinput.authority?.capabilities === undefined &&\n\t\t(input.base === undefined ||\n\t\t\t(input.base.profile.toolNames.includes(\"delegate\") &&\n\t\t\t\tinput.base.profile.capabilityCeiling.includes(\"workflow.delegate\")));\n\tconst requestedToolNames =\n\t\tinheritsDelegation && !configuredToolNames.includes(\"delegate\")\n\t\t\t? [...configuredToolNames, \"delegate\"]\n\t\t\t: configuredToolNames;\n\tconst uniqueToolNames = [...new Set(requestedToolNames)];\n\tconst unavailableTools = uniqueToolNames.filter((toolName) => !AVAILABLE_TOOL_NAMES.has(toolName));\n\tif (unavailableTools.length > 0) {\n\t\treturn { ok: false, reason: `orchestration_tool_unavailable:${unavailableTools.join(\",\")}` };\n\t}\n\tconst capabilities = new Set<HarnessCapability>(\n\t\tinput.authority?.capabilities ?? input.base?.profile.capabilityCeiling ?? DEFAULT_CAPABILITIES,\n\t);\n\tif (uniqueToolNames.includes(\"delegate\") && inheritsDelegation) {\n\t\tcapabilities.add(\"workflow.delegate\");\n\t}\n\tconst capabilityList = [...capabilities];\n\tconst toolNames: string[] = [];\n\tfor (const toolName of uniqueToolNames) {\n\t\tconst policy = getToolCapabilityPolicy(toolName);\n\t\tif (!policy) return { ok: false, reason: `orchestration_tool_unclassified:${toolName}` };\n\t\tif (envelopeHasToolCapability(capabilityList, toolName)) {\n\t\t\ttoolNames.push(toolName);\n\t\t\tcontinue;\n\t\t}\n\t\tif (input.authority?.toolNames !== undefined) {\n\t\t\treturn { ok: false, reason: `orchestration_tool_capability_missing:${toolName}` };\n\t\t}\n\t}\n\tconst budget = structuredClone(input.authority?.budget ?? input.base?.profile.budget ?? {});\n\tconst floorFailure = tokenBudgetFloorFailure(budget.maxTokens);\n\tif (floorFailure) return { ok: false, reason: floorFailure };\n\tconst role = input.authority?.role ?? input.base?.profile.role ?? \"orchestrator\";\n\tconst delegationLimits = input.base\n\t\t? input.base.profile.delegationLimits\n\t\t: structuredClone(LEAN_WORKER_DELEGATION_LIMITS);\n\tconst now = new Date().toISOString();\n\tconst descriptor = {\n\t\trole,\n\t\tbinding: resolvedModel.binding,\n\t\tcapabilities: [...capabilities],\n\t\ttoolNames,\n\t\tbudget,\n\t\tdelegationLimits: delegationLimits ?? null,\n\t\tresourceProfileNames: input.base?.profile.resourceProfileNames ?? [],\n\t};\n\tconst maxWallClockMs = budget.maxWallClockMs ?? 0;\n\tconst wallClockLeaseTtlMs =\n\t\tmaxWallClockMs > Number.MAX_SAFE_INTEGER - 30_000 ? Number.MAX_SAFE_INTEGER : maxWallClockMs + 30_000;\n\tconst profile: OrchestrationProfile = {\n\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\tprofileId: adaptiveProfileId(descriptor),\n\t\tdescription: \"Admission-time adaptive agent authority\",\n\t\trole,\n\t\tmodelPolicy: { mode: \"fixed\", candidates: [resolvedModel.binding] },\n\t\tcapabilityCeiling: [...capabilities],\n\t\ttoolNames,\n\t\tresourceProfileNames: [...(input.base?.profile.resourceProfileNames ?? [])],\n\t\tdispatchProfileIds: [],\n\t\t...(input.base?.profile.executionPolicy ? { executionPolicy: input.base.profile.executionPolicy } : {}),\n\t\t...(delegationLimits ? { delegationLimits: structuredClone(delegationLimits) } : {}),\n\t\tbudget,\n\t\tmaxConcurrent: Number.MAX_SAFE_INTEGER,\n\t\tleaseTtlMs: Math.max(input.base?.profile.leaseTtlMs ?? 0, wallClockLeaseTtlMs, 90_000),\n\t\trequireIndependentVerification: input.base?.profile.requireIndependentVerification ?? false,\n\t\t...(input.base?.profile.verificationProfileId\n\t\t\t? { verificationProfileId: input.base.profile.verificationProfileId }\n\t\t\t: {}),\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t};\n\treturn {\n\t\tok: true,\n\t\tshipment: {\n\t\t\tmodel: resolvedModel.model,\n\t\t\tmodelBinding: resolvedModel.binding,\n\t\t\tprofile,\n\t\t\tresourcePointers: structuredClone(input.base?.resourcePointers ?? []),\n\t\t\t...(input.base?.soul ? { soul: input.base.soul } : {}),\n\t\t},\n\t\t...(input.authority?.readPaths ? { requestedReadPaths: [...input.authority.readPaths] } : {}),\n\t\t...(input.authority?.writePaths ? { requestedWritePaths: [...input.authority.writePaths] } : {}),\n\t};\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-execution-policy.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-execution-policy.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACX,cAAc,EACd,iBAAiB,EACjB,oBAAoB,EACpB,eAAe,EACf,UAAU,EACV,sBAAsB,EACtB,gCAAgC,EAChC,UAAU,EACV,MAAM,+BAA+B,CAAC;AAIvC,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,wBAAwB,CAAC;
|
|
1
|
+
{"version":3,"file":"worker-execution-policy.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-execution-policy.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACX,cAAc,EACd,iBAAiB,EACjB,oBAAoB,EACpB,eAAe,EACf,UAAU,EACV,sBAAsB,EACtB,gCAAgC,EAChC,UAAU,EACV,MAAM,+BAA+B,CAAC;AAIvC,OAAO,KAAK,EAAE,gCAAgC,EAAE,MAAM,wBAAwB,CAAC;AAU/E,MAAM,WAAW,mBAAmB;IACnC,aAAa,EAAE,SAAS,sBAAsB,EAAE,CAAC;IACjD,oBAAoB,EAAE,SAAS,iBAAiB,EAAE,CAAC;IACnD,S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EAAE,CAAA;CAAE,CA0BtF;AAED,oGAAoG;AACpG,wBAAgB,mCAAmC,CAAC,IAAI,EAAE;IACzD,MAAM,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC;IACnE,MAAM,EAAE,MAAM,CAAC;IACf,eAAe,EAAE,MAAM,CAAC;IACxB,IAAI,EAAE,UAAU,CAAC;IACjB,YAAY,EAAE,SAAS,MAAM,EAAE,CAAC;IAChC,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9B,GAAG,EAAE,MAAM,CAAC;IACZ,WAAW,EAAE,SAAS,MAAM,EAAE,CAAC;IAC/B,MAAM,EAAE,UAAU,CAAC;CACnB,GAAG;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,KAAK,EAAE,cAAc,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,WAAW,EAAE,SAAS,MAAM,EAAE,CAAA;CAAE,CA2CtF"}
|
|
@@ -4,9 +4,12 @@ import { mapToolNamesForPlatform, STABLE_SHELL_TOOL_NAME } from "../default-tool
|
|
|
4
4
|
import { buildLaneToolManifests } from "../orchestration/lane-tool-manifests.js";
|
|
5
5
|
import { ExecutionPolicyCompiler } from "../orchestration/policy-compiler.js";
|
|
6
6
|
import { intersectRiskBudgets } from "../orchestration/risk-budget.js";
|
|
7
|
-
import { getToolCapabilityPolicy } from "../tool-capability-policy.js";
|
|
7
|
+
import { getToolCapabilityPolicy, requiredEnvelopeCapabilities } from "../tool-capability-policy.js";
|
|
8
8
|
const READ_TOOL_NAMES = ["read", "grep", "find", "ls"];
|
|
9
9
|
const WRITE_TOOL_NAMES = ["write", "edit"];
|
|
10
|
+
function delegatedToolCapabilities(toolName) {
|
|
11
|
+
return toolName === "memory" ? ["memory.query"] : requiredEnvelopeCapabilities(toolName);
|
|
12
|
+
}
|
|
10
13
|
function intersectPathScopes(admittedPaths, currentPaths) {
|
|
11
14
|
const intersections = admittedPaths.flatMap((admitted) => currentPaths.flatMap((current) => {
|
|
12
15
|
if (isPathWithinScope(current, admitted))
|
|
@@ -69,18 +72,17 @@ export function buildWorkerExecutionPlan(args) {
|
|
|
69
72
|
const enabledToolNames = [
|
|
70
73
|
...(grantsRead ? READ_TOOL_NAMES : []),
|
|
71
74
|
...(writeEligible ? WRITE_TOOL_NAMES : []),
|
|
72
|
-
...(memoryEligible ? ["memory"] : []),
|
|
73
75
|
...enabledProcessToolNames,
|
|
74
76
|
...(profileToolNames.has("delegate") && args.profile.capabilityCeiling.includes("workflow.delegate")
|
|
75
77
|
? ["delegate"]
|
|
76
78
|
: []),
|
|
77
79
|
];
|
|
78
80
|
const toolManifests = buildLaneToolManifests(args.profile, enabledToolNames);
|
|
79
|
-
if (memoryEligible
|
|
81
|
+
if (memoryEligible) {
|
|
80
82
|
toolManifests.push({
|
|
81
83
|
toolName: "memory",
|
|
82
84
|
moduleSpecifier: "../tools/memory.ts",
|
|
83
|
-
capabilities:
|
|
85
|
+
capabilities: delegatedToolCapabilities("memory"),
|
|
84
86
|
roles: [args.profile.role],
|
|
85
87
|
enforcements: ["memory-broker"],
|
|
86
88
|
});
|
|
@@ -140,17 +142,17 @@ export function compileManagedProcessExecutionGrant(args) {
|
|
|
140
142
|
const unknownTools = [];
|
|
141
143
|
for (const toolName of [...new Set(args.allowedTools)]) {
|
|
142
144
|
const policy = getToolCapabilityPolicy(toolName);
|
|
143
|
-
const
|
|
144
|
-
if (!policy ||
|
|
145
|
+
const capabilities = delegatedToolCapabilities(toolName);
|
|
146
|
+
if (!policy || capabilities.length === 0) {
|
|
145
147
|
unknownTools.push(toolName);
|
|
146
148
|
continue;
|
|
147
149
|
}
|
|
148
150
|
manifests.push({
|
|
149
151
|
toolName,
|
|
150
152
|
moduleSpecifier: `managed-process:${toolName}`,
|
|
151
|
-
capabilities
|
|
153
|
+
capabilities,
|
|
152
154
|
roles: [args.role],
|
|
153
|
-
enforcements:
|
|
155
|
+
enforcements: policy.enforcements,
|
|
154
156
|
});
|
|
155
157
|
}
|
|
156
158
|
if (unknownTools.length > 0)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-execution-policy.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-execution-policy.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAW7F,OAAO,EAAE,sBAAsB,EAAE,MAAM,yCAAyC,CAAC;AACjF,OAAO,EAAE,uBAAuB,EAAE,MAAM,qCAAqC,CAAC;AAC9E,OAAO,EAAE,oBAAoB,EAAE,MAAM,iCAAiC,CAAC;AAEvE,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAEvE,MAAM,eAAe,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,CAAU,CAAC;AAChE,MAAM,gBAAgB,GAAG,CAAC,OAAO,EAAE,MAAM,CAAU,CAAC;AAcpD,SAAS,mBAAmB,CAAC,aAAgC,EAAE,YAA+B;IAC7F,MAAM,aAAa,GAAG,aAAa,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE,CACxD,YAAY,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAChC,IAAI,iBAAiB,CAAC,OAAO,EAAE,QAAQ,CAAC;YAAE,OAAO,CAAC,OAAO,CAAC,CAAC;QAC3D,IAAI,iBAAiB,CAAC,QAAQ,EAAE,OAAO,CAAC;YAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;QAC5D,OAAO,EAAE,CAAC;IACX,CAAC,CAAC,CACF,CAAC;IACF,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAA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onomy/path-scope.ts\";\nimport { mapToolNamesForPlatform, STABLE_SHELL_TOOL_NAME } from \"../default-tool-surface.ts\";\nimport type {\n\tExecutionGrant,\n\tHarnessCapability,\n\tOrchestrationProfile,\n\tResourcePointer,\n\tRiskBudget,\n\tToolCapabilityManifest,\n\tWorkerExecutionAuthorityContract,\n\tWorkerRole,\n} from \"../orchestration/contracts.ts\";\nimport { buildLaneToolManifests } from \"../orchestration/lane-tool-manifests.ts\";\nimport { ExecutionPolicyCompiler } from \"../orchestration/policy-compiler.ts\";\nimport { intersectRiskBudgets } from \"../orchestration/risk-budget.ts\";\nimport type { ResolvedWorkerDelegationSettings } from \"../settings-manager.ts\";\nimport { getToolCapabilityPolicy } from \"../tool-capability-policy.ts\";\n\nconst READ_TOOL_NAMES = [\"read\", \"grep\", \"find\", \"ls\"] as const;\nconst WRITE_TOOL_NAMES = [\"write\", \"edit\"] as const;\n\nexport interface WorkerExecutionPlan {\n\ttoolManifests: readonly ToolCapabilityManifest[];\n\trequiredCapabilities: readonly HarnessCapability[];\n\treadPaths: readonly string[];\n\twritePaths: readonly string[];\n\tdeniedPaths: readonly string[];\n\treadMemory: boolean;\n\twriteEnabled: boolean;\n\tprocessEnabled: boolean;\n\tbudget: RiskBudget;\n}\n\nfunction intersectPathScopes(admittedPaths: readonly string[], currentPaths: readonly string[]): string[] {\n\tconst intersections = admittedPaths.flatMap((admitted) =>\n\t\tcurrentPaths.flatMap((current) => {\n\t\t\tif (isPathWithinScope(current, admitted)) return [current];\n\t\t\tif (isPathWithinScope(admitted, current)) return [admitted];\n\t\t\treturn [];\n\t\t}),\n\t);\n\treturn [...new Set(intersections.map((entry) => path.resolve(entry)))];\n}\n\nexport function workerExecutionAuthorityFromPlan(plan: WorkerExecutionPlan): WorkerExecutionAuthorityContract {\n\treturn {\n\t\tcapabilities: [...plan.requiredCapabilities],\n\t\ttoolNames: plan.toolManifests.map((manifest) => manifest.toolName),\n\t\treadPaths: [...plan.readPaths],\n\t\twritePaths: [...plan.writePaths],\n\t\tdeniedPaths: [...plan.deniedPaths],\n\t\tbudget: { ...plan.budget },\n\t};\n}\n\n/** Apply live revocations to admitted authority without allowing later settings to widen it. */\nexport function narrowWorkerExecutionPlan(\n\tadmitted: WorkerExecutionAuthorityContract,\n\tcurrent: WorkerExecutionPlan,\n): WorkerExecutionPlan {\n\tconst admittedTools = new Set(mapToolNamesForPlatform(admitted.toolNames));\n\tconst admittedCapabilities = new Set(admitted.capabilities);\n\tconst toolManifests = current.toolManifests.filter(\n\t\t(manifest) =>\n\t\t\tadmittedTools.has(manifest.toolName) &&\n\t\t\tmanifest.capabilities.every((capability) => admittedCapabilities.has(capability)),\n\t);\n\tconst requiredCapabilities = [...new Set(toolManifests.flatMap((manifest) => manifest.capabilities))];\n\tconst grantedTools = new Set(toolManifests.map((manifest) => manifest.toolName));\n\tconst readEnabled = requiredCapabilities.some(\n\t\t(capability) => capability === \"filesystem.read\" || capability === \"worktree.read\",\n\t);\n\tconst writeEnabled = grantedTools.has(\"write\") || grantedTools.has(\"edit\");\n\treturn {\n\t\ttoolManifests,\n\t\trequiredCapabilities,\n\t\treadPaths: readEnabled ? intersectPathScopes(admitted.readPaths, current.readPaths) : [],\n\t\twritePaths: writeEnabled ? intersectPathScopes(admitted.writePaths, current.writePaths) : [],\n\t\tdeniedPaths: [...new Set([...admitted.deniedPaths, ...current.deniedPaths].map((entry) => path.resolve(entry)))],\n\t\treadMemory: grantedTools.has(\"memory\"),\n\t\twriteEnabled,\n\t\tprocessEnabled: grantedTools.has(\"run_process\") || grantedTools.has(STABLE_SHELL_TOOL_NAME),\n\t\tbudget: intersectRiskBudgets(admitted.budget, current.budget),\n\t};\n}\n\nexport function buildWorkerExecutionPlan(args: {\n\tprofile: OrchestrationProfile;\n\tsettings: ResolvedWorkerDelegationSettings;\n\tcwd: string;\n\tdeniedPaths: readonly string[];\n\tforegroundMaxCostUsd?: number;\n\tmemoryEnabled: boolean;\n\trequestedReadPaths?: readonly string[];\n\trequestedWritePaths?: readonly string[];\n}): WorkerExecutionPlan {\n\tconst profileToolNames = new Set(mapToolNamesForPlatform(args.profile.toolNames));\n\tconst grantsRead =\n\t\targs.profile.capabilityCeiling.includes(\"filesystem.read\") ||\n\t\targs.profile.capabilityCeiling.includes(\"worktree.read\");\n\tconst writeEligible =\n\t\targs.settings.writeEnabled &&\n\t\targs.settings.writePaths.length > 0 &&\n\t\t(args.profile.capabilityCeiling.includes(\"filesystem.write\") ||\n\t\t\targs.profile.capabilityCeiling.includes(\"worktree.mutate\"));\n\tconst memoryEligible = args.memoryEnabled;\n\tconst processEligible =\n\t\targs.profile.capabilityCeiling.includes(\"process.exec\") ||\n\t\targs.profile.capabilityCeiling.includes(\"tests.execute\");\n\tconst enabledProcessToolNames = processEligible\n\t\t? [\n\t\t\t\t...(args.profile.executionPolicy && profileToolNames.has(\"run_process\") ? ([\"run_process\"] as const) : []),\n\t\t\t\t...(profileToolNames.has(STABLE_SHELL_TOOL_NAME) ? [STABLE_SHELL_TOOL_NAME] : []),\n\t\t\t]\n\t\t: [];\n\tconst enabledToolNames = [\n\t\t...(grantsRead ? READ_TOOL_NAMES : []),\n\t\t...(writeEligible ? WRITE_TOOL_NAMES : []),\n\t\t...(memoryEligible ? ([\"memory\"] as const) : []),\n\t\t...enabledProcessToolNames,\n\t\t...(profileToolNames.has(\"delegate\") && args.profile.capabilityCeiling.includes(\"workflow.delegate\")\n\t\t\t? ([\"delegate\"] as const)\n\t\t\t: []),\n\t];\n\tconst toolManifests = buildLaneToolManifests(args.profile, enabledToolNames);\n\tif (memoryEligible && !toolManifests.some((manifest) => manifest.toolName === \"memory\")) {\n\t\ttoolManifests.push({\n\t\t\ttoolName: \"memory\",\n\t\t\tmoduleSpecifier: \"../tools/memory.ts\",\n\t\t\tcapabilities: [\"memory.query\"],\n\t\t\troles: [args.profile.role],\n\t\t\tenforcements: [\"memory-broker\"],\n\t\t});\n\t}\n\tconst grantedTools = new Set(toolManifests.map((manifest) => manifest.toolName));\n\tconst readEnabled = toolManifests.some((manifest) =>\n\t\tmanifest.capabilities.some((capability) => capability === \"filesystem.read\" || capability === \"worktree.read\"),\n\t);\n\tconst writeEnabled = grantedTools.has(\"write\") || grantedTools.has(\"edit\");\n\tconst readMemory = grantedTools.has(\"memory\");\n\tconst processEnabled = grantedTools.has(\"run_process\") || grantedTools.has(STABLE_SHELL_TOOL_NAME);\n\tconst budget = intersectRiskBudgets(\n\t\targs.profile.budget,\n\t\t...(args.settings.maxUsd > 0 ? [{ maxCostUsd: args.settings.maxUsd }] : []),\n\t\t...(args.foregroundMaxCostUsd !== undefined ? [{ maxCostUsd: args.foregroundMaxCostUsd }] : []),\n\t\t...(args.settings.maxWallClockMs > 0 ? [{ maxWallClockMs: args.settings.maxWallClockMs }] : []),\n\t);\n\treturn {\n\t\ttoolManifests,\n\t\trequiredCapabilities: [...new Set(toolManifests.flatMap((manifest) => manifest.capabilities))],\n\t\treadPaths: readEnabled\n\t\t\t? (args.requestedReadPaths ?? [args.cwd]).map((entry) =>\n\t\t\t\t\tpath.isAbsolute(entry) ? path.resolve(entry) : path.resolve(args.cwd, entry),\n\t\t\t\t)\n\t\t\t: [],\n\t\twritePaths: writeEnabled\n\t\t\t? intersectPathScopes(\n\t\t\t\t\targs.settings.writePaths.map((entry) =>\n\t\t\t\t\t\tpath.isAbsolute(entry) ? path.resolve(entry) : path.resolve(args.cwd, entry),\n\t\t\t\t\t),\n\t\t\t\t\t(args.requestedWritePaths ?? args.settings.writePaths).map((entry) =>\n\t\t\t\t\t\tpath.isAbsolute(entry) ? path.resolve(entry) : path.resolve(args.cwd, entry),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t: [],\n\t\tdeniedPaths: args.deniedPaths.map((entry) => path.resolve(entry)),\n\t\treadMemory,\n\t\twriteEnabled,\n\t\tprocessEnabled,\n\t\tbudget,\n\t};\n}\n\nexport function compileWorkerExecutionGrant(args: {\n\ttarget: { objectiveId: string; taskId: string; attemptId: string };\n\tprofile: OrchestrationProfile;\n\tplan: WorkerExecutionPlan;\n\tresources: readonly ResourcePointer[];\n}): { ok: true; grant: ExecutionGrant } | { ok: false; reasonCodes: readonly string[] } {\n\tconst authorityCapabilities =\n\t\targs.plan.readMemory && !args.profile.capabilityCeiling.includes(\"memory.query\")\n\t\t\t? [...args.profile.capabilityCeiling, \"memory.query\" as const]\n\t\t\t: args.profile.capabilityCeiling;\n\tconst compiled = new ExecutionPolicyCompiler().compile({\n\t\tobjectiveId: args.target.objectiveId,\n\t\ttaskId: args.target.taskId,\n\t\tattemptId: args.target.attemptId,\n\t\tsubjectId: `in-process:${args.target.attemptId}`,\n\t\trole: args.profile.role,\n\t\trequiredCapabilities: args.plan.requiredCapabilities,\n\t\trequestedCapabilities: args.plan.requiredCapabilities,\n\t\tauthorityCapabilities,\n\t\trequestedTools: args.plan.toolManifests.map((manifest) => manifest.toolName),\n\t\ttoolManifests: args.plan.toolManifests,\n\t\tresources: args.resources,\n\t\treadPaths: args.plan.readPaths,\n\t\twritePaths: args.plan.writePaths,\n\t\tdeniedPaths: args.plan.deniedPaths,\n\t\trequestedBudget: args.plan.budget,\n\t\tauthorityBudget: args.plan.budget,\n\t\tpolicyVersion: \"worker-profile-v1\",\n\t});\n\tif (compiled.outcome !== \"allow\") return { ok: false, reasonCodes: compiled.reasonCodes };\n\treturn { ok: true, grant: compiled.grant };\n}\n\n/** Compile the host's durable authority record before an externally managed process is launched. */\nexport function compileManagedProcessExecutionGrant(args: {\n\ttarget: { objectiveId: string; taskId: string; attemptId: string };\n\tlaneId: string;\n\tauthorizationId: string;\n\trole: WorkerRole;\n\tallowedTools: readonly string[];\n\twritePaths: readonly string[];\n\tcwd: string;\n\tdeniedPaths: readonly string[];\n\tbudget: RiskBudget;\n}): { ok: true; grant: ExecutionGrant } | { ok: false; reasonCodes: readonly string[] } {\n\tconst manifests: ToolCapabilityManifest[] = [];\n\tconst unknownTools: string[] = [];\n\tfor (const toolName of [...new Set(args.allowedTools)]) {\n\t\tconst policy = getToolCapabilityPolicy(toolName);\n\t\tconst capability = policy?.capabilityCandidates[0];\n\t\tif (!policy || !capability) {\n\t\t\tunknownTools.push(toolName);\n\t\t\tcontinue;\n\t\t}\n\t\tmanifests.push({\n\t\t\ttoolName,\n\t\t\tmoduleSpecifier: `managed-process:${toolName}`,\n\t\t\tcapabilities: [capability],\n\t\t\troles: [args.role],\n\t\t\tenforcements: [policy.enforcement],\n\t\t});\n\t}\n\tif (unknownTools.length > 0) return { ok: false, reasonCodes: unknownTools.map((name) => `unknown_tool:${name}`) };\n\tconst capabilities = [...new Set(manifests.flatMap((manifest) => manifest.capabilities))];\n\tconst readEnabled = capabilities.some(\n\t\t(capability) => capability === \"filesystem.read\" || capability === \"worktree.read\",\n\t);\n\tconst compiled = new ExecutionPolicyCompiler().compile({\n\t\t...args.target,\n\t\tsubjectId: `managed:${args.laneId}:${args.authorizationId}`,\n\t\trole: args.role,\n\t\trequiredCapabilities: capabilities,\n\t\trequestedCapabilities: capabilities,\n\t\tauthorityCapabilities: capabilities,\n\t\trequestedTools: manifests.map((manifest) => manifest.toolName),\n\t\ttoolManifests: manifests,\n\t\treadPaths: readEnabled ? [path.resolve(args.cwd)] : [],\n\t\twritePaths: args.writePaths.map((entry) =>\n\t\t\tpath.isAbsolute(entry) ? path.resolve(entry) : path.resolve(args.cwd, entry),\n\t\t),\n\t\tdeniedPaths: args.deniedPaths.map((entry) => path.resolve(entry)),\n\t\trequestedBudget: args.budget,\n\t\tauthorityBudget: args.budget,\n\t\tpolicyVersion: \"managed-process-v1\",\n\t});\n\tif (compiled.outcome !== \"allow\") return { ok: false, reasonCodes: compiled.reasonCodes };\n\treturn { ok: true, grant: compiled.grant };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"worker-execution-policy.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-execution-policy.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AA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EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE;QACtD,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CACzC,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,KAAK,CAAC,CAC5E;QACD,WAAW,EAAE,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QACjE,eAAe,EAAE,IAAI,CAAC,MAAM;QAC5B,eAAe,EAAE,IAAI,CAAC,MAAM;QAC5B,aAAa,EAAE,oBAAoB;KACnC,CAAC,CAAC;IACH,IAAI,QAAQ,CAAC,OAAO,KAAK,OAAO;QAAE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,WAAW,EAAE,QAAQ,CAAC,WAAW,EAAE,CAAC;IAC1F,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,CAAC;AAC5C,CAAC","sourcesContent":["import path from \"node:path\";\nimport { isPathWithinScope } from \"../autonomy/path-scope.ts\";\nimport { mapToolNamesForPlatform, STABLE_SHELL_TOOL_NAME } from \"../default-tool-surface.ts\";\nimport type {\n\tExecutionGrant,\n\tHarnessCapability,\n\tOrchestrationProfile,\n\tResourcePointer,\n\tRiskBudget,\n\tToolCapabilityManifest,\n\tWorkerExecutionAuthorityContract,\n\tWorkerRole,\n} from \"../orchestration/contracts.ts\";\nimport { buildLaneToolManifests } from \"../orchestration/lane-tool-manifests.ts\";\nimport { ExecutionPolicyCompiler } from \"../orchestration/policy-compiler.ts\";\nimport { intersectRiskBudgets } from \"../orchestration/risk-budget.ts\";\nimport type { ResolvedWorkerDelegationSettings } from \"../settings-manager.ts\";\nimport { getToolCapabilityPolicy, requiredEnvelopeCapabilities } from \"../tool-capability-policy.ts\";\n\nconst READ_TOOL_NAMES = [\"read\", \"grep\", \"find\", \"ls\"] as const;\nconst WRITE_TOOL_NAMES = [\"write\", \"edit\"] as const;\n\nfunction delegatedToolCapabilities(toolName: string): readonly HarnessCapability[] {\n\treturn toolName === \"memory\" ? [\"memory.query\"] : requiredEnvelopeCapabilities(toolName);\n}\n\nexport interface WorkerExecutionPlan {\n\ttoolManifests: readonly ToolCapabilityManifest[];\n\trequiredCapabilities: readonly HarnessCapability[];\n\treadPaths: readonly string[];\n\twritePaths: readonly string[];\n\tdeniedPaths: readonly string[];\n\treadMemory: boolean;\n\twriteEnabled: boolean;\n\tprocessEnabled: boolean;\n\tbudget: RiskBudget;\n}\n\nfunction intersectPathScopes(admittedPaths: readonly string[], currentPaths: readonly string[]): string[] {\n\tconst intersections = admittedPaths.flatMap((admitted) =>\n\t\tcurrentPaths.flatMap((current) => {\n\t\t\tif (isPathWithinScope(current, admitted)) return [current];\n\t\t\tif (isPathWithinScope(admitted, current)) return [admitted];\n\t\t\treturn [];\n\t\t}),\n\t);\n\treturn [...new Set(intersections.map((entry) => path.resolve(entry)))];\n}\n\nexport function workerExecutionAuthorityFromPlan(plan: WorkerExecutionPlan): WorkerExecutionAuthorityContract {\n\treturn {\n\t\tcapabilities: [...plan.requiredCapabilities],\n\t\ttoolNames: plan.toolManifests.map((manifest) => manifest.toolName),\n\t\treadPaths: [...plan.readPaths],\n\t\twritePaths: [...plan.writePaths],\n\t\tdeniedPaths: [...plan.deniedPaths],\n\t\tbudget: { ...plan.budget },\n\t};\n}\n\n/** Apply live revocations to admitted authority without allowing later settings to widen it. */\nexport function narrowWorkerExecutionPlan(\n\tadmitted: WorkerExecutionAuthorityContract,\n\tcurrent: WorkerExecutionPlan,\n): WorkerExecutionPlan {\n\tconst admittedTools = new Set(mapToolNamesForPlatform(admitted.toolNames));\n\tconst admittedCapabilities = new Set(admitted.capabilities);\n\tconst toolManifests = current.toolManifests.filter(\n\t\t(manifest) =>\n\t\t\tadmittedTools.has(manifest.toolName) &&\n\t\t\tmanifest.capabilities.every((capability) => admittedCapabilities.has(capability)),\n\t);\n\tconst requiredCapabilities = [...new Set(toolManifests.flatMap((manifest) => manifest.capabilities))];\n\tconst grantedTools = new Set(toolManifests.map((manifest) => manifest.toolName));\n\tconst readEnabled = requiredCapabilities.some(\n\t\t(capability) => capability === \"filesystem.read\" || capability === \"worktree.read\",\n\t);\n\tconst writeEnabled = grantedTools.has(\"write\") || grantedTools.has(\"edit\");\n\treturn {\n\t\ttoolManifests,\n\t\trequiredCapabilities,\n\t\treadPaths: readEnabled ? intersectPathScopes(admitted.readPaths, current.readPaths) : [],\n\t\twritePaths: writeEnabled ? intersectPathScopes(admitted.writePaths, current.writePaths) : [],\n\t\tdeniedPaths: [...new Set([...admitted.deniedPaths, ...current.deniedPaths].map((entry) => path.resolve(entry)))],\n\t\treadMemory: grantedTools.has(\"memory\"),\n\t\twriteEnabled,\n\t\tprocessEnabled: grantedTools.has(\"run_process\") || grantedTools.has(STABLE_SHELL_TOOL_NAME),\n\t\tbudget: intersectRiskBudgets(admitted.budget, current.budget),\n\t};\n}\n\nexport function buildWorkerExecutionPlan(args: {\n\tprofile: OrchestrationProfile;\n\tsettings: ResolvedWorkerDelegationSettings;\n\tcwd: string;\n\tdeniedPaths: readonly string[];\n\tforegroundMaxCostUsd?: number;\n\tmemoryEnabled: boolean;\n\trequestedReadPaths?: readonly string[];\n\trequestedWritePaths?: readonly string[];\n}): WorkerExecutionPlan {\n\tconst profileToolNames = new Set(mapToolNamesForPlatform(args.profile.toolNames));\n\tconst grantsRead =\n\t\targs.profile.capabilityCeiling.includes(\"filesystem.read\") ||\n\t\targs.profile.capabilityCeiling.includes(\"worktree.read\");\n\tconst writeEligible =\n\t\targs.settings.writeEnabled &&\n\t\targs.settings.writePaths.length > 0 &&\n\t\t(args.profile.capabilityCeiling.includes(\"filesystem.write\") ||\n\t\t\targs.profile.capabilityCeiling.includes(\"worktree.mutate\"));\n\tconst memoryEligible = args.memoryEnabled;\n\tconst processEligible =\n\t\targs.profile.capabilityCeiling.includes(\"process.exec\") ||\n\t\targs.profile.capabilityCeiling.includes(\"tests.execute\");\n\tconst enabledProcessToolNames = processEligible\n\t\t? [\n\t\t\t\t...(args.profile.executionPolicy && profileToolNames.has(\"run_process\") ? ([\"run_process\"] as const) : []),\n\t\t\t\t...(profileToolNames.has(STABLE_SHELL_TOOL_NAME) ? [STABLE_SHELL_TOOL_NAME] : []),\n\t\t\t]\n\t\t: [];\n\tconst enabledToolNames = [\n\t\t...(grantsRead ? READ_TOOL_NAMES : []),\n\t\t...(writeEligible ? WRITE_TOOL_NAMES : []),\n\t\t...enabledProcessToolNames,\n\t\t...(profileToolNames.has(\"delegate\") && args.profile.capabilityCeiling.includes(\"workflow.delegate\")\n\t\t\t? ([\"delegate\"] as const)\n\t\t\t: []),\n\t];\n\tconst toolManifests = buildLaneToolManifests(args.profile, enabledToolNames);\n\tif (memoryEligible) {\n\t\ttoolManifests.push({\n\t\t\ttoolName: \"memory\",\n\t\t\tmoduleSpecifier: \"../tools/memory.ts\",\n\t\t\tcapabilities: delegatedToolCapabilities(\"memory\"),\n\t\t\troles: [args.profile.role],\n\t\t\tenforcements: [\"memory-broker\"],\n\t\t});\n\t}\n\tconst grantedTools = new Set(toolManifests.map((manifest) => manifest.toolName));\n\tconst readEnabled = toolManifests.some((manifest) =>\n\t\tmanifest.capabilities.some((capability) => capability === \"filesystem.read\" || capability === \"worktree.read\"),\n\t);\n\tconst writeEnabled = grantedTools.has(\"write\") || grantedTools.has(\"edit\");\n\tconst readMemory = grantedTools.has(\"memory\");\n\tconst processEnabled = grantedTools.has(\"run_process\") || grantedTools.has(STABLE_SHELL_TOOL_NAME);\n\tconst budget = intersectRiskBudgets(\n\t\targs.profile.budget,\n\t\t...(args.settings.maxUsd > 0 ? [{ maxCostUsd: args.settings.maxUsd }] : []),\n\t\t...(args.foregroundMaxCostUsd !== undefined ? [{ maxCostUsd: args.foregroundMaxCostUsd }] : []),\n\t\t...(args.settings.maxWallClockMs > 0 ? [{ maxWallClockMs: args.settings.maxWallClockMs }] : []),\n\t);\n\treturn {\n\t\ttoolManifests,\n\t\trequiredCapabilities: [...new Set(toolManifests.flatMap((manifest) => manifest.capabilities))],\n\t\treadPaths: readEnabled\n\t\t\t? (args.requestedReadPaths ?? [args.cwd]).map((entry) =>\n\t\t\t\t\tpath.isAbsolute(entry) ? path.resolve(entry) : path.resolve(args.cwd, entry),\n\t\t\t\t)\n\t\t\t: [],\n\t\twritePaths: writeEnabled\n\t\t\t? intersectPathScopes(\n\t\t\t\t\targs.settings.writePaths.map((entry) =>\n\t\t\t\t\t\tpath.isAbsolute(entry) ? path.resolve(entry) : path.resolve(args.cwd, entry),\n\t\t\t\t\t),\n\t\t\t\t\t(args.requestedWritePaths ?? args.settings.writePaths).map((entry) =>\n\t\t\t\t\t\tpath.isAbsolute(entry) ? path.resolve(entry) : path.resolve(args.cwd, entry),\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t: [],\n\t\tdeniedPaths: args.deniedPaths.map((entry) => path.resolve(entry)),\n\t\treadMemory,\n\t\twriteEnabled,\n\t\tprocessEnabled,\n\t\tbudget,\n\t};\n}\n\nexport function compileWorkerExecutionGrant(args: {\n\ttarget: { objectiveId: string; taskId: string; attemptId: string };\n\tprofile: OrchestrationProfile;\n\tplan: WorkerExecutionPlan;\n\tresources: readonly ResourcePointer[];\n}): { ok: true; grant: ExecutionGrant } | { ok: false; reasonCodes: readonly string[] } {\n\tconst authorityCapabilities =\n\t\targs.plan.readMemory && !args.profile.capabilityCeiling.includes(\"memory.query\")\n\t\t\t? [...args.profile.capabilityCeiling, \"memory.query\" as const]\n\t\t\t: args.profile.capabilityCeiling;\n\tconst compiled = new ExecutionPolicyCompiler().compile({\n\t\tobjectiveId: args.target.objectiveId,\n\t\ttaskId: args.target.taskId,\n\t\tattemptId: args.target.attemptId,\n\t\tsubjectId: `in-process:${args.target.attemptId}`,\n\t\trole: args.profile.role,\n\t\trequiredCapabilities: args.plan.requiredCapabilities,\n\t\trequestedCapabilities: args.plan.requiredCapabilities,\n\t\tauthorityCapabilities,\n\t\trequestedTools: args.plan.toolManifests.map((manifest) => manifest.toolName),\n\t\ttoolManifests: args.plan.toolManifests,\n\t\tresources: args.resources,\n\t\treadPaths: args.plan.readPaths,\n\t\twritePaths: args.plan.writePaths,\n\t\tdeniedPaths: args.plan.deniedPaths,\n\t\trequestedBudget: args.plan.budget,\n\t\tauthorityBudget: args.plan.budget,\n\t\tpolicyVersion: \"worker-profile-v1\",\n\t});\n\tif (compiled.outcome !== \"allow\") return { ok: false, reasonCodes: compiled.reasonCodes };\n\treturn { ok: true, grant: compiled.grant };\n}\n\n/** Compile the host's durable authority record before an externally managed process is launched. */\nexport function compileManagedProcessExecutionGrant(args: {\n\ttarget: { objectiveId: string; taskId: string; attemptId: string };\n\tlaneId: string;\n\tauthorizationId: string;\n\trole: WorkerRole;\n\tallowedTools: readonly string[];\n\twritePaths: readonly string[];\n\tcwd: string;\n\tdeniedPaths: readonly string[];\n\tbudget: RiskBudget;\n}): { ok: true; grant: ExecutionGrant } | { ok: false; reasonCodes: readonly string[] } {\n\tconst manifests: ToolCapabilityManifest[] = [];\n\tconst unknownTools: string[] = [];\n\tfor (const toolName of [...new Set(args.allowedTools)]) {\n\t\tconst policy = getToolCapabilityPolicy(toolName);\n\t\tconst capabilities = delegatedToolCapabilities(toolName);\n\t\tif (!policy || capabilities.length === 0) {\n\t\t\tunknownTools.push(toolName);\n\t\t\tcontinue;\n\t\t}\n\t\tmanifests.push({\n\t\t\ttoolName,\n\t\t\tmoduleSpecifier: `managed-process:${toolName}`,\n\t\t\tcapabilities,\n\t\t\troles: [args.role],\n\t\t\tenforcements: policy.enforcements,\n\t\t});\n\t}\n\tif (unknownTools.length > 0) return { ok: false, reasonCodes: unknownTools.map((name) => `unknown_tool:${name}`) };\n\tconst capabilities = [...new Set(manifests.flatMap((manifest) => manifest.capabilities))];\n\tconst readEnabled = capabilities.some(\n\t\t(capability) => capability === \"filesystem.read\" || capability === \"worktree.read\",\n\t);\n\tconst compiled = new ExecutionPolicyCompiler().compile({\n\t\t...args.target,\n\t\tsubjectId: `managed:${args.laneId}:${args.authorizationId}`,\n\t\trole: args.role,\n\t\trequiredCapabilities: capabilities,\n\t\trequestedCapabilities: capabilities,\n\t\tauthorityCapabilities: capabilities,\n\t\trequestedTools: manifests.map((manifest) => manifest.toolName),\n\t\ttoolManifests: manifests,\n\t\treadPaths: readEnabled ? [path.resolve(args.cwd)] : [],\n\t\twritePaths: args.writePaths.map((entry) =>\n\t\t\tpath.isAbsolute(entry) ? path.resolve(entry) : path.resolve(args.cwd, entry),\n\t\t),\n\t\tdeniedPaths: args.deniedPaths.map((entry) => path.resolve(entry)),\n\t\trequestedBudget: args.budget,\n\t\tauthorityBudget: args.budget,\n\t\tpolicyVersion: \"managed-process-v1\",\n\t});\n\tif (compiled.outcome !== \"allow\") return { ok: false, reasonCodes: compiled.reasonCodes };\n\treturn { ok: true, grant: compiled.grant };\n}\n"]}
|
|
@@ -36,6 +36,7 @@ export interface ForegroundRecoveryControllerDeps {
|
|
|
36
36
|
onSuccessfulAssistant(): void;
|
|
37
37
|
prepareRun(): Promise<void>;
|
|
38
38
|
afterRun(): Promise<void>;
|
|
39
|
+
isCompacting?: () => boolean;
|
|
39
40
|
}
|
|
40
41
|
/** Owns the complete logical foreground run plus retry/failover/compaction recovery ordering. */
|
|
41
42
|
export declare class ForegroundRecoveryController {
|
|
@@ -59,6 +60,7 @@ export declare class ForegroundRecoveryController {
|
|
|
59
60
|
ownsSubmission(lease: ForegroundSubmissionLease | undefined): boolean;
|
|
60
61
|
releaseSubmission(lease: ForegroundSubmissionLease): void;
|
|
61
62
|
runAgentPrompt(messages: AgentMessage | AgentMessage[], submissionLease?: ForegroundSubmissionLease): Promise<void>;
|
|
63
|
+
wakeIdleWaiters(): void;
|
|
62
64
|
waitForIdle(): Promise<void>;
|
|
63
65
|
shutdown(): void;
|
|
64
66
|
private resolveIdleWaiters;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"foreground-recovery-controller.d.ts","sourceRoot":"","sources":["../../src/core/foreground-recovery-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,KAAK,EAAkB,MAAM,iCAAiC,CAAC;AAO7E,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAG1D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,0BAA0B,CAAC;AAC1E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAE7D,KAAK,uBAAuB,GACzB;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GACpC;IAAE,IAAI,EAAE,kBAAkB,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,GACzG;IAAE,IAAI,EAAE,gBAAgB,CAAC;IAAC,OAAO,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,UAAU,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAEtF,QAAA,MAAM,+BAA+B,EAAE,OAAO,MAA4C,CAAC;AAE3F,yFAAyF;AACzF,MAAM,WAAW,yBAAyB;IACzC,QAAQ,CAAC,CAAC,+BAA+B,CAAC,EAAE,IAA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IAED,IAAI,UAAU,IAAI,OAAO,CAExB;IAED,IAAI,WAAW,IAAI,OAAO,CAEzB;IAED,IAAI,MAAM,IAAI,OAAO,CAQpB;IAED,mGAAmG;IACnG,oBAAoB,IAAI,yBAAyB,GAAG,SAAS,CAK5D;IAED,oFAAoF;IAC9E,iBAAiB,IAAI,OAAO,CAAC,yBAAyB,CAAC,CAO5D;IAED,cAAc,CAAC,KAAK,EAAE,yBAAyB,GAAG,SAAS,GAAG,OAAO,CAEpE;IAED,iBAAiB,CAAC,KAAK,EAAE,yBAAyB,GAAG,IAAI,CAQxD;IAEK,cAAc,CACnB,QAAQ,EAAE,YAAY,GAAG,YAAY,EAAE,EACvC,eAAe,CAAC,EAAE,yBAAyB,GACzC,OAAO,CAAC,IAAI,CAAC,CAsCf;IAED,eAAe,IAAI,IAAI,CAEtB;IAEK,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC,CAUjC;IAED,QAAQ,IAAI,IAAI,CAIf;IAED,OAAO,CAAC,kBAAkB;IAM1B,UAAU,IAAI,IAAI,CAEjB;IAED,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAErC;IAED,iBAAiB,IAAI,yBAAyB,CAE7C;IAED,gBAAgB,CAAC,OAAO,EAAE,gBAAgB,GAAG,IAAI,CAShD;IAED,sBAAsB,CAAC,KAAK,EAAE,OAAO,CAAC,UAAU,EAAE;QAAE,IAAI,EAAE,WAAW,CAAA;KAAE,CAAC,GAAG,OAAO,CAQjF;IAEK,kBAAkB,IAAI,OAAO,CAAC,OAAO,CAAC,CAoB3C;IAED,OAAO,CAAC,WAAW;IAMnB,OAAO,CAAC,sBAAsB;CAQ9B"}
|
|
@@ -27,7 +27,7 @@ export class ForegroundRecoveryController {
|
|
|
27
27
|
modelRegistry: deps.modelRegistry,
|
|
28
28
|
exhausted: new ExhaustedProviderRegistry(),
|
|
29
29
|
subscriptionHop: deps.settingsManager.getFailoverSettings().subscriptionHop,
|
|
30
|
-
emit: deps.emit,
|
|
30
|
+
emit: (event) => deps.emit(event),
|
|
31
31
|
recordFailure: (record) => deps.failureCorpus.record(record),
|
|
32
32
|
});
|
|
33
33
|
}
|
|
@@ -41,7 +41,11 @@ export class ForegroundRecoveryController {
|
|
|
41
41
|
return this.activeRuns > 0;
|
|
42
42
|
}
|
|
43
43
|
get isBusy() {
|
|
44
|
-
return (this.submissionLease !== undefined ||
|
|
44
|
+
return (this.submissionLease !== undefined ||
|
|
45
|
+
this.isRunActive ||
|
|
46
|
+
this.deps.agent.state.isStreaming ||
|
|
47
|
+
this.isRetrying ||
|
|
48
|
+
this.deps.isCompacting?.() === true);
|
|
45
49
|
}
|
|
46
50
|
/** Atomically reserve the full foreground lifecycle, including asynchronous prompt preparation. */
|
|
47
51
|
tryAcquireSubmission() {
|
|
@@ -69,11 +73,10 @@ export class ForegroundRecoveryController {
|
|
|
69
73
|
if (!this.ownsSubmission(lease)) {
|
|
70
74
|
throw new Error("Cannot release foreground submission authority owned by another caller");
|
|
71
75
|
}
|
|
72
|
-
if (this.activeRuns > 0) {
|
|
73
|
-
throw new Error("Cannot release foreground submission authority while its agent run is active");
|
|
74
|
-
}
|
|
75
76
|
this.submissionLease = undefined;
|
|
76
|
-
this.
|
|
77
|
+
if (this.activeRuns === 0) {
|
|
78
|
+
this.resolveIdleWaiters();
|
|
79
|
+
}
|
|
77
80
|
}
|
|
78
81
|
async runAgentPrompt(messages, submissionLease) {
|
|
79
82
|
let lease = submissionLease;
|
|
@@ -90,7 +93,7 @@ export class ForegroundRecoveryController {
|
|
|
90
93
|
releaseLease = true;
|
|
91
94
|
}
|
|
92
95
|
if (this.activeRuns > 0) {
|
|
93
|
-
if (releaseLease)
|
|
96
|
+
if (releaseLease && lease)
|
|
94
97
|
this.releaseSubmission(lease);
|
|
95
98
|
throw new AgentBusyError("Agent is already processing.");
|
|
96
99
|
}
|
|
@@ -111,16 +114,22 @@ export class ForegroundRecoveryController {
|
|
|
111
114
|
}
|
|
112
115
|
finally {
|
|
113
116
|
this.activeRuns--;
|
|
114
|
-
if (releaseLease)
|
|
117
|
+
if (releaseLease && lease && this.ownsSubmission(lease))
|
|
115
118
|
this.releaseSubmission(lease);
|
|
119
|
+
if (this.activeRuns === 0 && this.submissionLease === undefined) {
|
|
120
|
+
this.resolveIdleWaiters();
|
|
121
|
+
}
|
|
116
122
|
}
|
|
117
123
|
}
|
|
118
124
|
}
|
|
125
|
+
wakeIdleWaiters() {
|
|
126
|
+
this.resolveIdleWaiters();
|
|
127
|
+
}
|
|
119
128
|
async waitForIdle() {
|
|
120
129
|
while (true) {
|
|
121
130
|
if (this.shutdownReason)
|
|
122
131
|
return;
|
|
123
|
-
if (this.submissionLease !== undefined || this.activeRuns > 0) {
|
|
132
|
+
if (this.submissionLease !== undefined || this.activeRuns > 0 || this.deps.isCompacting?.() === true) {
|
|
124
133
|
await new Promise((resolve) => this.idleWaiters.add(resolve));
|
|
125
134
|
continue;
|
|
126
135
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"foreground-recovery-controller.js","sourceRoot":"","sources":["../../src/core/foreground-recovery-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAC7E,OAAO,EAEN,eAAe,EACf,oBAAoB,EACpB,eAAe,GACf,MAAM,uCAAuC,CAAC;AAG/C,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EAAE,yBAAyB,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAWxG,MAAM,+BAA+B,GAAkB,MAAM,CAAC,2BAA2B,CAAC,CAAC;AAoB3F,iGAAiG;AACjG,MAAM,OAAO,4BAA4B;IAUxC,YAAY,IAAsC;QAN1C,eAAU,GAAG,CAAC,CAAC;QAGN,gBAAW,GAAG,IAAI,GAAG,EAAc,CAAC;QAIpD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,IAAI,eAA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AE,UAAU,EAAE,CAAC,CAAC;QAC7F,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACpB,CAAC;IAEO,sBAAsB,CAAC,OAAyB;QACvD,IAAI,OAAO,CAAC,UAAU,KAAK,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY;YAAE,OAAO,SAAS,CAAC;QAC9E,OAAO,eAAe,CAAC;YACtB,OAAO,EAAE,OAAO,CAAC,YAAY;YAC7B,eAAe,EAAE,iBAAiB,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACzE,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC1B,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["import { type Agent, AgentBusyError } from \"@caupulican/pi-agent-core/agent\";\nimport {\n\ttype ClassifiedError,\n\tclassifyFailure,\n\tDEFAULT_RETRY_POLICY,\n\tRetryController,\n} from \"@caupulican/pi-agent-core/reliability\";\nimport type { AgentEvent, AgentMessage } from \"@caupulican/pi-agent-core/types\";\nimport type { AssistantMessage } from \"@caupulican/pi-ai\";\nimport { isContextOverflow } from \"@caupulican/pi-ai/overflow\";\nimport { BillingFailoverController, ExhaustedProviderRegistry } from \"./billing-failover-controller.ts\";\nimport type { FailureCorpusRecorder } from \"./failure-corpus.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport type { ModelRouterFailoverStatus } from \"./model-router/status.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\ntype ForegroundRecoveryEvent =\n\t| { type: \"warning\"; message: string }\n\t| { type: \"auto_retry_start\"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }\n\t| { type: \"auto_retry_end\"; success: boolean; attempt: number; finalError?: string };\n\nconst foregroundSubmissionLeaseMarker: unique symbol = Symbol(\"foregroundSubmissionLease\");\n\n/** Identity-bound authority to prepare and execute one logical foreground submission. */\nexport interface ForegroundSubmissionLease {\n\treadonly [foregroundSubmissionLeaseMarker]: true;\n}\n\nexport interface ForegroundRecoveryControllerDeps {\n\tagent: Agent;\n\tsettingsManager: SettingsManager;\n\tmodelRegistry: ModelRegistry;\n\tfailureCorpus: FailureCorpusRecorder;\n\tgetContextWindow(): number;\n\temit(event: ForegroundRecoveryEvent): void;\n\tcheckCompaction(message: AssistantMessage): Promise<boolean>;\n\tonSuccessfulAssistant(): void;\n\tprepareRun(): Promise<void>;\n\tafterRun(): Promise<void>;\n}\n\n/** Owns the complete logical foreground run plus retry/failover/compaction recovery ordering. */\nexport class ForegroundRecoveryController {\n\tprivate readonly retry: RetryController;\n\tprivate readonly billingFailover: BillingFailoverController;\n\tprivate lastAssistantMessage: AssistantMessage | undefined;\n\tprivate activeRuns = 0;\n\tprivate submissionLease: ForegroundSubmissionLease | undefined;\n\tprivate shutdownReason: Error | undefined;\n\tprivate readonly idleWaiters = new Set<() => void>();\n\tprivate readonly deps: ForegroundRecoveryControllerDeps;\n\n\tconstructor(deps: ForegroundRecoveryControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis.retry = new RetryController(\n\t\t\tdeps.agent,\n\t\t\t() => {\n\t\t\t\tconst retry = deps.settingsManager.getRetrySettings();\n\t\t\t\treturn {\n\t\t\t\t\tenabled: retry.enabled,\n\t\t\t\t\tmaxAttempts: retry.maxRetries,\n\t\t\t\t\tbaseDelayMs: retry.baseDelayMs,\n\t\t\t\t\tmaxDelayMs: DEFAULT_RETRY_POLICY.maxDelayMs,\n\t\t\t\t\tjitterRatio: 0,\n\t\t\t\t};\n\t\t\t},\n\t\t\t{\n\t\t\t\tonRetryStart: (info) => deps.emit({ type: \"auto_retry_start\", ...info }),\n\t\t\t\tonRetryEnd: (info) => deps.emit({ type: \"auto_retry_end\", ...info }),\n\t\t\t},\n\t\t\tdeps.getContextWindow,\n\t\t);\n\t\tthis.billingFailover = new BillingFailoverController({\n\t\t\tagent: deps.agent,\n\t\t\tmodelRegistry: deps.modelRegistry,\n\t\t\texhausted: new ExhaustedProviderRegistry(),\n\t\t\tsubscriptionHop: deps.settingsManager.getFailoverSettings().subscriptionHop,\n\t\t\temit: deps.emit,\n\t\t\trecordFailure: (record) => deps.failureCorpus.record(record),\n\t\t});\n\t}\n\n\tget attempt(): number {\n\t\treturn this.retry.attempt;\n\t}\n\n\tget isRetrying(): boolean {\n\t\treturn this.retry.isRetrying;\n\t}\n\n\tget isRunActive(): boolean {\n\t\treturn this.activeRuns > 0;\n\t}\n\n\tget isBusy(): boolean {\n\t\treturn (\n\t\t\tthis.submissionLease !== undefined || this.isRunActive || this.deps.agent.state.isStreaming || this.isRetrying\n\t\t);\n\t}\n\n\t/** Atomically reserve the full foreground lifecycle, including asynchronous prompt preparation. */\n\ttryAcquireSubmission(): ForegroundSubmissionLease | undefined {\n\t\tif (this.shutdownReason || this.isBusy) return undefined;\n\t\tconst lease: ForegroundSubmissionLease = { [foregroundSubmissionLeaseMarker]: true };\n\t\tthis.submissionLease = lease;\n\t\treturn lease;\n\t}\n\n\t/** Wait until foreground ownership can be acquired without a check-then-act gap. */\n\tasync acquireSubmission(): Promise<ForegroundSubmissionLease> {\n\t\twhile (true) {\n\t\t\tif (this.shutdownReason) throw this.shutdownReason;\n\t\t\tconst lease = this.tryAcquireSubmission();\n\t\t\tif (lease) return lease;\n\t\t\tawait this.waitForIdle();\n\t\t}\n\t}\n\n\townsSubmission(lease: ForegroundSubmissionLease | undefined): boolean {\n\t\treturn lease !== undefined && lease === this.submissionLease;\n\t}\n\n\treleaseSubmission(lease: ForegroundSubmissionLease): void {\n\t\tif (!this.ownsSubmission(lease)) {\n\t\t\tthrow new Error(\"Cannot release foreground submission authority owned by another caller\");\n\t\t}\n\t\tif (this.activeRuns > 0) {\n\t\t\tthrow new Error(\"Cannot release foreground submission authority while its agent run is active\");\n\t\t}\n\t\tthis.submissionLease = undefined;\n\t\tthis.resolveIdleWaiters();\n\t}\n\n\tasync runAgentPrompt(\n\t\tmessages: AgentMessage | AgentMessage[],\n\t\tsubmissionLease?: ForegroundSubmissionLease,\n\t): Promise<void> {\n\t\tlet lease = submissionLease;\n\t\tlet releaseLease = false;\n\t\tif (lease) {\n\t\t\tif (!this.ownsSubmission(lease)) {\n\t\t\t\tthrow new AgentBusyError(\"Foreground submission authority is no longer active.\");\n\t\t\t}\n\t\t} else {\n\t\t\tlease = this.tryAcquireSubmission();\n\t\t\tif (!lease) throw new AgentBusyError(\"Agent is already processing.\");\n\t\t\treleaseLease = true;\n\t\t}\n\t\tif (this.activeRuns > 0) {\n\t\t\tif (releaseLease) this.releaseSubmission(lease);\n\t\t\tthrow new AgentBusyError(\"Agent is already processing.\");\n\t\t}\n\n\t\tthis.activeRuns++;\n\t\ttry {\n\t\t\tconst maxGoalLoopRounds = this.deps.settingsManager.getAutonomySettings().maxStallTurns;\n\t\t\tawait this.deps.prepareRun();\n\t\t\tlet goalLoopRounds = 1;\n\t\t\tawait this.deps.agent.prompt(messages);\n\t\t\twhile ((maxGoalLoopRounds === 0 || goalLoopRounds < maxGoalLoopRounds) && (await this.handlePostAgentRun())) {\n\t\t\t\tawait this.deps.agent.continue();\n\t\t\t\tgoalLoopRounds++;\n\t\t\t}\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tawait this.deps.afterRun();\n\t\t\t} finally {\n\t\t\t\tthis.activeRuns--;\n\t\t\t\tif (releaseLease) this.releaseSubmission(lease);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync waitForIdle(): Promise<void> {\n\t\twhile (true) {\n\t\t\tif (this.shutdownReason) return;\n\t\t\tif (this.submissionLease !== undefined || this.activeRuns > 0) {\n\t\t\t\tawait new Promise<void>((resolve) => this.idleWaiters.add(resolve));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tawait this.deps.agent.waitForIdle();\n\t\t\tif (!this.isBusy) return;\n\t\t}\n\t}\n\n\tshutdown(): void {\n\t\tthis.shutdownReason ??= new Error(\"Session disposed before foreground submission authority was acquired\");\n\t\tfor (const resolve of this.idleWaiters) resolve();\n\t\tthis.idleWaiters.clear();\n\t}\n\n\tprivate resolveIdleWaiters(): void {\n\t\tif (this.submissionLease !== undefined || this.activeRuns > 0) return;\n\t\tfor (const resolve of this.idleWaiters) resolve();\n\t\tthis.idleWaiters.clear();\n\t}\n\n\tabortRetry(): void {\n\t\tthis.retry.abort();\n\t}\n\n\tisModelExhausted(ref: string): boolean {\n\t\treturn this.billingFailover.isExhausted(ref);\n\t}\n\n\tgetFailoverStatus(): ModelRouterFailoverStatus {\n\t\treturn this.billingFailover.getStatus();\n\t}\n\n\tobserveAssistant(message: AssistantMessage): void {\n\t\tthis.lastAssistantMessage = message;\n\t\tif (message.stopReason === \"error\") return;\n\t\tif (message.stopReason === \"aborted\") {\n\t\t\tthis.finishRetry(false, message.errorMessage ?? \"Retry aborted\");\n\t\t\treturn;\n\t\t}\n\t\tthis.deps.onSuccessfulAssistant();\n\t\tthis.finishRetry(true);\n\t}\n\n\twillRetryAfterAgentEnd(event: Extract<AgentEvent, { type: \"agent_end\" }>): boolean {\n\t\tconst settings = this.deps.settingsManager.getRetrySettings();\n\t\tif (!settings.enabled || this.retry.attempt >= settings.maxRetries) return false;\n\t\tfor (let index = event.messages.length - 1; index >= 0; index--) {\n\t\t\tconst message = event.messages[index];\n\t\t\tif (message.role === \"assistant\") return this.classifyAssistantError(message)?.retryable ?? false;\n\t\t}\n\t\treturn false;\n\t}\n\n\tasync handlePostAgentRun(): Promise<boolean> {\n\t\tconst message = this.lastAssistantMessage;\n\t\tthis.lastAssistantMessage = undefined;\n\t\tif (!message) return false;\n\n\t\tconst classified = this.classifyAssistantError(message);\n\t\tif (classified) {\n\t\t\tthis.deps.failureCorpus.record({\n\t\t\t\tprovider: message.provider,\n\t\t\t\tmodelId: message.model,\n\t\t\t\tmessage: message.errorMessage ?? \"\",\n\t\t\t\tclassified,\n\t\t\t});\n\t\t}\n\t\tif (classified?.retryable && (await this.retry.prepareRetry(message))) return true;\n\t\tif (await this.billingFailover.handleAssistantError(message, classified)) return false;\n\n\t\tif (message.stopReason === \"error\") this.finishRetry(false, message.errorMessage);\n\t\tif (await this.deps.checkCompaction(message)) return true;\n\t\treturn this.deps.agent.hasQueuedMessages();\n\t}\n\n\tprivate finishRetry(success: boolean, finalError?: string): void {\n\t\tif (this.retry.attempt === 0) return;\n\t\tthis.deps.emit({ type: \"auto_retry_end\", success, attempt: this.retry.attempt, finalError });\n\t\tthis.retry.reset();\n\t}\n\n\tprivate classifyAssistantError(message: AssistantMessage): ClassifiedError | undefined {\n\t\tif (message.stopReason !== \"error\" || !message.errorMessage) return undefined;\n\t\treturn classifyFailure({\n\t\t\tmessage: message.errorMessage,\n\t\t\tcontextOverflow: isContextOverflow(message, this.deps.getContextWindow()),\n\t\t\tprovider: message.provider,\n\t\t});\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"foreground-recovery-controller.js","sourceRoot":"","sources":["../../src/core/foreground-recovery-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAC7E,OAAO,EAEN,eAAe,EACf,oBAAoB,EACpB,eAAe,GACf,MAAM,uCAAuC,CAAC;AAG/C,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EAAE,yBAAyB,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAWxG,MAAM,+BAA+B,GAAkB,MAAM,CAAC,2BAA2B,CAAC,CAAC;AAqB3F,iGAAiG;AACjG,MAAM,OAAO,4BAA4B;IAUxC,YAAY,IAAsC;QAN1C,eAAU,GAAG,CAAC,CAAC;QAGN,gBAAW,GAAG,IAAI,GAAG,EAAc,CAAC;QAIpD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,IAAI,eAAe,CAC/B,IAAI,CAAC,KAAK,EACV,GAAG,EAAE;YACJ,MAAM,KAAK,GAAG,IAAI,CAAC,eAAe,CAAC,gBAAgB,EAAE,CAAC;YACtD,OAAO;gBACN,OAAO,EAAE,KAAK,CAAC,OAA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WAAW,CAAC,OAAgB,EAAE,UAAmB;QACxD,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,KAAK,CAAC;YAAE,OAAO;QACrC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,gBAAgB,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,UAAU,EAAE,CAAC,CAAC;QAC7F,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;IACpB,CAAC;IAEO,sBAAsB,CAAC,OAAyB;QACvD,IAAI,OAAO,CAAC,UAAU,KAAK,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY;YAAE,OAAO,SAAS,CAAC;QAC9E,OAAO,eAAe,CAAC;YACtB,OAAO,EAAE,OAAO,CAAC,YAAY;YAC7B,eAAe,EAAE,iBAAiB,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACzE,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC1B,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["import { type Agent, AgentBusyError } from \"@caupulican/pi-agent-core/agent\";\nimport {\n\ttype ClassifiedError,\n\tclassifyFailure,\n\tDEFAULT_RETRY_POLICY,\n\tRetryController,\n} from \"@caupulican/pi-agent-core/reliability\";\nimport type { AgentEvent, AgentMessage } from \"@caupulican/pi-agent-core/types\";\nimport type { AssistantMessage } from \"@caupulican/pi-ai\";\nimport { isContextOverflow } from \"@caupulican/pi-ai/overflow\";\nimport { BillingFailoverController, ExhaustedProviderRegistry } from \"./billing-failover-controller.ts\";\nimport type { FailureCorpusRecorder } from \"./failure-corpus.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport type { ModelRouterFailoverStatus } from \"./model-router/status.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\ntype ForegroundRecoveryEvent =\n\t| { type: \"warning\"; message: string }\n\t| { type: \"auto_retry_start\"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }\n\t| { type: \"auto_retry_end\"; success: boolean; attempt: number; finalError?: string };\n\nconst foregroundSubmissionLeaseMarker: unique symbol = Symbol(\"foregroundSubmissionLease\");\n\n/** Identity-bound authority to prepare and execute one logical foreground submission. */\nexport interface ForegroundSubmissionLease {\n\treadonly [foregroundSubmissionLeaseMarker]: true;\n}\n\nexport interface ForegroundRecoveryControllerDeps {\n\tagent: Agent;\n\tsettingsManager: SettingsManager;\n\tmodelRegistry: ModelRegistry;\n\tfailureCorpus: FailureCorpusRecorder;\n\tgetContextWindow(): number;\n\temit(event: ForegroundRecoveryEvent): void;\n\tcheckCompaction(message: AssistantMessage): Promise<boolean>;\n\tonSuccessfulAssistant(): void;\n\tprepareRun(): Promise<void>;\n\tafterRun(): Promise<void>;\n\tisCompacting?: () => boolean;\n}\n\n/** Owns the complete logical foreground run plus retry/failover/compaction recovery ordering. */\nexport class ForegroundRecoveryController {\n\tprivate readonly retry: RetryController;\n\tprivate readonly billingFailover: BillingFailoverController;\n\tprivate lastAssistantMessage: AssistantMessage | undefined;\n\tprivate activeRuns = 0;\n\tprivate submissionLease: ForegroundSubmissionLease | undefined;\n\tprivate shutdownReason: Error | undefined;\n\tprivate readonly idleWaiters = new Set<() => void>();\n\tprivate readonly deps: ForegroundRecoveryControllerDeps;\n\n\tconstructor(deps: ForegroundRecoveryControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis.retry = new RetryController(\n\t\t\tdeps.agent,\n\t\t\t() => {\n\t\t\t\tconst retry = deps.settingsManager.getRetrySettings();\n\t\t\t\treturn {\n\t\t\t\t\tenabled: retry.enabled,\n\t\t\t\t\tmaxAttempts: retry.maxRetries,\n\t\t\t\t\tbaseDelayMs: retry.baseDelayMs,\n\t\t\t\t\tmaxDelayMs: DEFAULT_RETRY_POLICY.maxDelayMs,\n\t\t\t\t\tjitterRatio: 0,\n\t\t\t\t};\n\t\t\t},\n\t\t\t{\n\t\t\t\tonRetryStart: (info) => deps.emit({ type: \"auto_retry_start\", ...info }),\n\t\t\t\tonRetryEnd: (info) => deps.emit({ type: \"auto_retry_end\", ...info }),\n\t\t\t},\n\t\t\tdeps.getContextWindow,\n\t\t);\n\t\tthis.billingFailover = new BillingFailoverController({\n\t\t\tagent: deps.agent,\n\t\t\tmodelRegistry: deps.modelRegistry,\n\t\t\texhausted: new ExhaustedProviderRegistry(),\n\t\t\tsubscriptionHop: deps.settingsManager.getFailoverSettings().subscriptionHop,\n\t\t\temit: (event) => deps.emit(event),\n\t\t\trecordFailure: (record) => deps.failureCorpus.record(record),\n\t\t});\n\t}\n\n\tget attempt(): number {\n\t\treturn this.retry.attempt;\n\t}\n\n\tget isRetrying(): boolean {\n\t\treturn this.retry.isRetrying;\n\t}\n\n\tget isRunActive(): boolean {\n\t\treturn this.activeRuns > 0;\n\t}\n\n\tget isBusy(): boolean {\n\t\treturn (\n\t\t\tthis.submissionLease !== undefined ||\n\t\t\tthis.isRunActive ||\n\t\t\tthis.deps.agent.state.isStreaming ||\n\t\t\tthis.isRetrying ||\n\t\t\tthis.deps.isCompacting?.() === true\n\t\t);\n\t}\n\n\t/** Atomically reserve the full foreground lifecycle, including asynchronous prompt preparation. */\n\ttryAcquireSubmission(): ForegroundSubmissionLease | undefined {\n\t\tif (this.shutdownReason || this.isBusy) return undefined;\n\t\tconst lease: ForegroundSubmissionLease = { [foregroundSubmissionLeaseMarker]: true };\n\t\tthis.submissionLease = lease;\n\t\treturn lease;\n\t}\n\n\t/** Wait until foreground ownership can be acquired without a check-then-act gap. */\n\tasync acquireSubmission(): Promise<ForegroundSubmissionLease> {\n\t\twhile (true) {\n\t\t\tif (this.shutdownReason) throw this.shutdownReason;\n\t\t\tconst lease = this.tryAcquireSubmission();\n\t\t\tif (lease) return lease;\n\t\t\tawait this.waitForIdle();\n\t\t}\n\t}\n\n\townsSubmission(lease: ForegroundSubmissionLease | undefined): boolean {\n\t\treturn lease !== undefined && lease === this.submissionLease;\n\t}\n\n\treleaseSubmission(lease: ForegroundSubmissionLease): void {\n\t\tif (!this.ownsSubmission(lease)) {\n\t\t\tthrow new Error(\"Cannot release foreground submission authority owned by another caller\");\n\t\t}\n\t\tthis.submissionLease = undefined;\n\t\tif (this.activeRuns === 0) {\n\t\t\tthis.resolveIdleWaiters();\n\t\t}\n\t}\n\n\tasync runAgentPrompt(\n\t\tmessages: AgentMessage | AgentMessage[],\n\t\tsubmissionLease?: ForegroundSubmissionLease,\n\t): Promise<void> {\n\t\tlet lease = submissionLease;\n\t\tlet releaseLease = false;\n\t\tif (lease) {\n\t\t\tif (!this.ownsSubmission(lease)) {\n\t\t\t\tthrow new AgentBusyError(\"Foreground submission authority is no longer active.\");\n\t\t\t}\n\t\t} else {\n\t\t\tlease = this.tryAcquireSubmission();\n\t\t\tif (!lease) throw new AgentBusyError(\"Agent is already processing.\");\n\t\t\treleaseLease = true;\n\t\t}\n\t\tif (this.activeRuns > 0) {\n\t\t\tif (releaseLease && lease) this.releaseSubmission(lease);\n\t\t\tthrow new AgentBusyError(\"Agent is already processing.\");\n\t\t}\n\n\t\tthis.activeRuns++;\n\t\ttry {\n\t\t\tconst maxGoalLoopRounds = this.deps.settingsManager.getAutonomySettings().maxStallTurns;\n\t\t\tawait this.deps.prepareRun();\n\t\t\tlet goalLoopRounds = 1;\n\t\t\tawait this.deps.agent.prompt(messages);\n\t\t\twhile ((maxGoalLoopRounds === 0 || goalLoopRounds < maxGoalLoopRounds) && (await this.handlePostAgentRun())) {\n\t\t\t\tawait this.deps.agent.continue();\n\t\t\t\tgoalLoopRounds++;\n\t\t\t}\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tawait this.deps.afterRun();\n\t\t\t} finally {\n\t\t\t\tthis.activeRuns--;\n\t\t\t\tif (releaseLease && lease && this.ownsSubmission(lease)) this.releaseSubmission(lease);\n\t\t\t\tif (this.activeRuns === 0 && this.submissionLease === undefined) {\n\t\t\t\t\tthis.resolveIdleWaiters();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\twakeIdleWaiters(): void {\n\t\tthis.resolveIdleWaiters();\n\t}\n\n\tasync waitForIdle(): Promise<void> {\n\t\twhile (true) {\n\t\t\tif (this.shutdownReason) return;\n\t\t\tif (this.submissionLease !== undefined || this.activeRuns > 0 || this.deps.isCompacting?.() === true) {\n\t\t\t\tawait new Promise<void>((resolve) => this.idleWaiters.add(resolve));\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tawait this.deps.agent.waitForIdle();\n\t\t\tif (!this.isBusy) return;\n\t\t}\n\t}\n\n\tshutdown(): void {\n\t\tthis.shutdownReason ??= new Error(\"Session disposed before foreground submission authority was acquired\");\n\t\tfor (const resolve of this.idleWaiters) resolve();\n\t\tthis.idleWaiters.clear();\n\t}\n\n\tprivate resolveIdleWaiters(): void {\n\t\tif (this.submissionLease !== undefined || this.activeRuns > 0) return;\n\t\tfor (const resolve of this.idleWaiters) resolve();\n\t\tthis.idleWaiters.clear();\n\t}\n\n\tabortRetry(): void {\n\t\tthis.retry.abort();\n\t}\n\n\tisModelExhausted(ref: string): boolean {\n\t\treturn this.billingFailover.isExhausted(ref);\n\t}\n\n\tgetFailoverStatus(): ModelRouterFailoverStatus {\n\t\treturn this.billingFailover.getStatus();\n\t}\n\n\tobserveAssistant(message: AssistantMessage): void {\n\t\tthis.lastAssistantMessage = message;\n\t\tif (message.stopReason === \"error\") return;\n\t\tif (message.stopReason === \"aborted\") {\n\t\t\tthis.finishRetry(false, message.errorMessage ?? \"Retry aborted\");\n\t\t\treturn;\n\t\t}\n\t\tthis.deps.onSuccessfulAssistant();\n\t\tthis.finishRetry(true);\n\t}\n\n\twillRetryAfterAgentEnd(event: Extract<AgentEvent, { type: \"agent_end\" }>): boolean {\n\t\tconst settings = this.deps.settingsManager.getRetrySettings();\n\t\tif (!settings.enabled || this.retry.attempt >= settings.maxRetries) return false;\n\t\tfor (let index = event.messages.length - 1; index >= 0; index--) {\n\t\t\tconst message = event.messages[index];\n\t\t\tif (message.role === \"assistant\") return this.classifyAssistantError(message)?.retryable ?? false;\n\t\t}\n\t\treturn false;\n\t}\n\n\tasync handlePostAgentRun(): Promise<boolean> {\n\t\tconst message = this.lastAssistantMessage;\n\t\tthis.lastAssistantMessage = undefined;\n\t\tif (!message) return false;\n\n\t\tconst classified = this.classifyAssistantError(message);\n\t\tif (classified) {\n\t\t\tthis.deps.failureCorpus.record({\n\t\t\t\tprovider: message.provider,\n\t\t\t\tmodelId: message.model,\n\t\t\t\tmessage: message.errorMessage ?? \"\",\n\t\t\t\tclassified,\n\t\t\t});\n\t\t}\n\t\tif (classified?.retryable && (await this.retry.prepareRetry(message))) return true;\n\t\tif (await this.billingFailover.handleAssistantError(message, classified)) return false;\n\n\t\tif (message.stopReason === \"error\") this.finishRetry(false, message.errorMessage);\n\t\tif (await this.deps.checkCompaction(message)) return true;\n\t\treturn this.deps.agent.hasQueuedMessages();\n\t}\n\n\tprivate finishRetry(success: boolean, finalError?: string): void {\n\t\tif (this.retry.attempt === 0) return;\n\t\tthis.deps.emit({ type: \"auto_retry_end\", success, attempt: this.retry.attempt, finalError });\n\t\tthis.retry.reset();\n\t}\n\n\tprivate classifyAssistantError(message: AssistantMessage): ClassifiedError | undefined {\n\t\tif (message.stopReason !== \"error\" || !message.errorMessage) return undefined;\n\t\treturn classifyFailure({\n\t\t\tmessage: message.errorMessage,\n\t\t\tcontextOverflow: isContextOverflow(message, this.deps.getContextWindow()),\n\t\t\tprovider: message.provider,\n\t\t});\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"goal-loop-controller.d.ts","sourceRoot":"","sources":["../../src/core/goal-loop-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAGH,OAAO,KAAK,EACX,2BAA2B,EAC3B,0BAA0B,EAE1B,2BAA2B,EAC3B,0BAA0B,EAC1B,aAAa,EACb,MAAM,8BAA8B,CAAC;AAMtC,OAAO,KAAK,EAAE,mBAAmB,EAAE,2BAA2B,EAAE,MAAM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,sBAAsB,CAAC,QAAQ,EAAE,2BAA2B,GAAG,mBAAmB,CAAC;IACnF,0EAA0E;IAC1E,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7D;;;;OAIG;IACH,0BAA0B,CAAC,IAAI,EAAE;QAChC,KAAK,EAAE,MAAM,CAAC;QACd,WAAW,EAAE,MAAM,CAAC;QACpB,MAAM,EAAE,MAAM,CAAC;QACf,gBAAgB,EAAE,MAAM,CAAC;QACzB,UAAU,EAAE,MAAM,CAAC;KACnB,GAAG,IAAI,CAAC;IACT,uFAAuF;IACvF,6BAA6B,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAAC;IACpD,gFAAgF;IAChF,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5C;AAED,qBAAa,kBAAkB;IAC9B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAyB;IAE9C,YAAY,IAAI,EAAE,sBAAsB,EAEvC;IAEK,gBAAgB,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAiBhG;IAEK,gBAAgB,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CA0FhG;CACD"}
|
|
@@ -107,15 +107,13 @@ export class GoalLoopController {
|
|
|
107
107
|
// coordination, not a consumed goal turn and not evidence that the goal is blocked.
|
|
108
108
|
if (error instanceof AgentBusyError)
|
|
109
109
|
throw error;
|
|
110
|
-
turnsSubmitted++;
|
|
111
|
-
this.deps.recordGoalContinuationPass({ ...passAccounting, wallClockMs: now() - passStartedAt });
|
|
112
110
|
if (error instanceof GoalBudgetExhaustedError) {
|
|
113
111
|
// The goal already stopped itself durably (markBudgetLimited ran synchronously before
|
|
114
|
-
// this signal was thrown) — surface the existing clean stop instead of
|
|
115
|
-
// intentional, already-recorded stop as a generic continuation failure and rejecting
|
|
116
|
-
// the whole loop promise.
|
|
112
|
+
// this signal was thrown) — surface the existing clean stop instead of charging a turn.
|
|
117
113
|
return { turnsSubmitted, stopReason: "goal_budget_exhausted", finalSnapshot: snapshot() };
|
|
118
114
|
}
|
|
115
|
+
turnsSubmitted++;
|
|
116
|
+
this.deps.recordGoalContinuationPass({ ...passAccounting, wallClockMs: now() - passStartedAt });
|
|
119
117
|
this.deps.recordGoalContinuationFailure(error);
|
|
120
118
|
throw error;
|
|
121
119
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"goal-loop-controller.js","sourceRoot":"","sources":["../../src/core/goal-loop-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AASjE,OAAO,EACN,2BAA2B,EAC3B,qCAAqC,GACrC,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAE5E,OAAO,EAAkB,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAE9E;;;;GAIG;AACH,SAAS,+BAA+B,CAAC,KAA4B;IACpE,IAAI,CAAC,KAAK,IAAI,CAAC,qBAAqB,CAAC,KAAK,CAAC,MAAM,CAAC;QAAE,OAAO,SAAS,CAAC;IACrE,IAAI,KAAK,CAAC,WAAW,KAAK,SAAS,IAAI,CAAC,KAAK,CAAC,UAAU,IAAI,CAAC,CAAC,IAAI,KAAK,CAAC,WAAW,EAAE,CAAC;QACrF,OAAO,2BAA2B,KAAK,CAAC,UAAU,IAAI,CAAC,IAAI,KAAK,CAAC,WAAW,GAAG,CAAC;IACjF,CAAC;IACD,OAAO,SAAS,CAAC;AAClB,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,qBAAqB,CAAC,QAA6B;IAC3D,OAAO,QAAQ,CAAC,YAAY,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,0BAA0B,C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AAG,EAAE,GAAG,aAAa,EAAE,CAAC,CAAC;YACjG,CAAC;YAED,IAAI,yBAAyB,EAAE,EAAE,CAAC;gBACjC,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,2BAA2B,EAAE,aAAa,EAAE,QAAQ,EAAE,EAAE,CAAC;YAC/F,CAAC;YAED,IAAI,aAAa,GAAG,QAAQ,EAAE,CAAC;YAC/B,IAAI,aAAa,CAAC,SAAS,EAAE,MAAM,KAAK,gBAAgB,EAAE,CAAC;gBAC1D,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,uBAAuB,EAAE,aAAa,EAAE,aAAa,EAAE,CAAC;YAC9F,CAAC;YACD,MAAM,qBAAqB,GAAG,+BAA+B,CAAC,aAAa,CAAC,SAAS,CAAC,CAAC;YACvF,IAAI,qBAAqB,EAAE,CAAC;gBAC3B,IAAI,CAAC,IAAI,CAAC,qBAAqB,CAAC,qBAAqB,CAAC,CAAC;gBACvD,aAAa,GAAG,QAAQ,EAAE,CAAC;gBAC3B,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,uBAAuB,EAAE,aAAa,EAAE,aAAa,EAAE,CAAC;YAC9F,CAAC;YACD,IAAI,aAAa,CAAC,YAAY,CAAC,MAAM,KAAK,UAAU,EAAE,CAAC;gBACtD,OAAO,EAAE,cAAc,EAAE,UAAU,EAAE,qBAAqB,CAAC,aAAa,CAAC,EAAE,aAAa,EAAE,aAAa,EAAE,CAAC;YAC3G,CAAC;QACF,CAAC;QAED,OAAO;YACN,cAAc;YACd,UAAU,EAAE,mBAAmB;YAC/B,aAAa,EAAE,QAAQ,EAAE;SACzB,CAAC;IACH,CAAC;CACD","sourcesContent":["/**\n * Goal auto-continuation loop.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Drives the bounded \"keep the\n * active goal moving\" loop: each pass reads the goal runtime snapshot, and — only while the snapshot\n * says `continue` — submits one continuation prompt back through the session's own prompt path. It\n * owns no state; the goal state lives in the session log and is read fresh every pass. Termination is\n * gated only by real terminal conditions and limits the owner explicitly supplied: an optional\n * per-invocation turn cap, an optional per-invocation wall-clock cap, and an optional durable token\n * budget on the goal. Each submitted pass still reports turn/wall-clock telemetry; provider usage\n * and spend are attributed at the response boundary. The host compares each pass's authoritative\n * progress revision and records unchanged passes as stalls, so a model cannot bypass the stall\n * limit by omitting a voluntary `no_progress` call.\n */\n\nimport { AgentBusyError } from \"@caupulican/pi-agent-core/agent\";\nimport type {\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tGoalContinuationLoopStopReason,\n\tGoalContinuationOnceOptions,\n\tGoalContinuationOnceResult,\n\tPromptOptions,\n} from \"./agent-session-contracts.ts\";\nimport {\n\tbuildGoalContinuationPrompt,\n\tGOAL_CONTINUATION_TRIGGER_CUSTOM_TYPE,\n} from \"./goals/goal-continuation-prompt.ts\";\nimport { GoalBudgetExhaustedError } from \"./goals/goal-execution-errors.ts\";\nimport type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from \"./goals/goal-runtime-snapshot.ts\";\nimport { type GoalState, isGoalExecutionActive } from \"./goals/goal-state.ts\";\n\n/**\n * Resolve an owner-supplied durable goal budget. Wall-clock and spend counters are deliberately\n * absent here: they are telemetry unless the public goal contract grows matching explicit limits.\n * Execution limits are policy inputs, not hidden runtime defaults.\n */\nfunction getExplicitGoalBudgetExhaustion(state: GoalState | undefined): string | undefined {\n\tif (!state || !isGoalExecutionActive(state.status)) return undefined;\n\tif (state.tokenBudget !== undefined && (state.tokensUsed ?? 0) >= state.tokenBudget) {\n\t\treturn `token budget exhausted (${state.tokensUsed ?? 0}/${state.tokenBudget})`;\n\t}\n\treturn undefined;\n}\n\n/**\n * Maps a non-\"continue\" continuation action onto the loop's own stopReason vocabulary.\n * `\"waiting\"` (a worker is dispatched against an open requirement) gets its OWN benign stopReason so\n * a wait is never misreported as `continuation_not_allowed` (which reads as a terminal refusal) —\n * callers/telemetry can tell \"paused, will resume on its own\" apart from \"stopped, needs a human or a\n * new decision.\" Every other non-continue action (ask-user/finalize/stop) keeps the existing\n * `continuation_not_allowed` stopReason unchanged.\n */\nfunction nonContinueStopReason(snapshot: GoalRuntimeSnapshot): GoalContinuationLoopStopReason {\n\treturn snapshot.continuation.action === \"waiting\" ? \"worker_in_flight\" : \"continuation_not_allowed\";\n}\n\nexport interface GoalLoopControllerDeps {\n\t/** Read the current goal runtime snapshot (continuation decision + goal state) fresh each pass. */\n\tgetGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;\n\t/** Submit a continuation prompt through the session's own prompt path. */\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\t/**\n\t * Persist one submitted pass's turn and active-wall-clock contribution. Provider usage is charged\n\t * at each assistant response before another request can be admitted. Called once per\n\t * pass actually SUBMITTED (never for a no-op `continueGoalOnce` call).\n\t */\n\trecordGoalContinuationPass(pass: {\n\t\tturns: number;\n\t\twallClockMs: number;\n\t\tgoalId: string;\n\t\tprogressRevision: number;\n\t\tstallTurns: number;\n\t}): void;\n\t/** Persist an exhausted/non-retryable continuation failure as a stopped goal state. */\n\trecordGoalContinuationFailure(error: unknown): void;\n\t/** Persist a reason-specific budget terminal state before returning control. */\n\tmarkGoalBudgetLimited(reason: string): void;\n}\n\nexport class GoalLoopController {\n\tprivate readonly deps: GoalLoopControllerDeps;\n\n\tconstructor(deps: GoalLoopControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tasync continueGoalOnce(options: GoalContinuationOnceOptions): Promise<GoalContinuationOnceResult> {\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns: options.maxStallTurns });\n\n\t\tif (snapshot.continuation.action !== \"continue\") {\n\t\t\treturn { submitted: false, snapshot };\n\t\t}\n\n\t\tconst prompt = buildGoalContinuationPrompt();\n\t\tawait this.deps.prompt(prompt.text, {\n\t\t\texpandPromptTemplates: false,\n\t\t\tprocessSlashCommands: false,\n\t\t\tautoContinueGoal: false,\n\t\t\tinternalContextType: GOAL_CONTINUATION_TRIGGER_CUSTOM_TYPE,\n\t\t\tgoalExecutionId: snapshot.goalState?.goalId,\n\t\t});\n\n\t\treturn { submitted: true, snapshot, prompt };\n\t}\n\n\tasync continueGoalLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\tif (!Number.isSafeInteger(options.maxTurns) || options.maxTurns < 0) {\n\t\t\tthrow new Error(\"Goal continuation maxTurns must be a non-negative safe integer; 0 means unbounded.\");\n\t\t}\n\t\tlet turnsSubmitted = 0;\n\t\tconst hasExplicitTurnLimit = options.maxTurns > 0;\n\t\tconst now = options.now ?? Date.now;\n\t\tconst maxWallClockMs =\n\t\t\ttypeof options.maxWallClockMinutes === \"number\" && options.maxWallClockMinutes > 0\n\t\t\t\t? options.maxWallClockMinutes * 60_000\n\t\t\t\t: undefined;\n\t\tconst startedAt = now();\n\t\tconst hasReachedWallClockBudget = () => maxWallClockMs !== undefined && now() - startedAt >= maxWallClockMs;\n\t\tconst snapshot = () => this.deps.getGoalRuntimeSnapshot({ maxStallTurns: options.maxStallTurns });\n\n\t\tif (hasReachedWallClockBudget()) {\n\t\t\treturn { turnsSubmitted, stopReason: \"wall_clock_budget_reached\", finalSnapshot: snapshot() };\n\t\t}\n\n\t\twhile (!hasExplicitTurnLimit || turnsSubmitted < options.maxTurns) {\n\t\t\tconst beforeSnapshot = snapshot();\n\t\t\tif (beforeSnapshot.continuation.action !== \"continue\") {\n\t\t\t\treturn { turnsSubmitted, stopReason: nonContinueStopReason(beforeSnapshot), finalSnapshot: beforeSnapshot };\n\t\t\t}\n\n\t\t\t// Owner-supplied durable token budget — read fresh every pass so an invocation stops as\n\t\t\t// soon as its own latest persisted usage crosses the explicit ceiling.\n\t\t\tconst beforeBudgetExhaustion = getExplicitGoalBudgetExhaustion(beforeSnapshot.goalState);\n\t\t\tif (beforeBudgetExhaustion) {\n\t\t\t\tthis.deps.markGoalBudgetLimited(beforeBudgetExhaustion);\n\t\t\t\treturn { turnsSubmitted, stopReason: \"goal_budget_exhausted\", finalSnapshot: snapshot() };\n\t\t\t}\n\n\t\t\tconst passStartedAt = now();\n\t\t\tconst beforeGoal = beforeSnapshot.goalState;\n\t\t\tif (!beforeGoal) {\n\t\t\t\treturn { turnsSubmitted, stopReason: \"continuation_not_allowed\", finalSnapshot: beforeSnapshot };\n\t\t\t}\n\t\t\tconst passAccounting = {\n\t\t\t\tturns: 1,\n\t\t\t\tgoalId: beforeGoal.goalId,\n\t\t\t\tprogressRevision: beforeGoal.progressRevision ?? 0,\n\t\t\t\tstallTurns: beforeGoal.stallTurns,\n\t\t\t};\n\t\t\tlet result: GoalContinuationOnceResult;\n\t\t\ttry {\n\t\t\t\tresult = await this.continueGoalOnce(options);\n\t\t\t} catch (error) {\n\t\t\t\t// Prompt admission did not happen. A concurrent foreground owner is transient session\n\t\t\t\t// coordination, not a consumed goal turn and not evidence that the goal is blocked.\n\t\t\t\tif (error instanceof AgentBusyError) throw error;\n\t\t\t\tturnsSubmitted++;\n\t\t\t\tthis.deps.recordGoalContinuationPass({ ...passAccounting, wallClockMs: now() - passStartedAt });\n\t\t\t\tif (error instanceof GoalBudgetExhaustedError) {\n\t\t\t\t\t// The goal already stopped itself durably (markBudgetLimited ran synchronously before\n\t\t\t\t\t// this signal was thrown) — surface the existing clean stop instead of reclassifying an\n\t\t\t\t\t// intentional, already-recorded stop as a generic continuation failure and rejecting\n\t\t\t\t\t// the whole loop promise.\n\t\t\t\t\treturn { turnsSubmitted, stopReason: \"goal_budget_exhausted\", finalSnapshot: snapshot() };\n\t\t\t\t}\n\t\t\t\tthis.deps.recordGoalContinuationFailure(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (result.submitted) {\n\t\t\t\tturnsSubmitted++;\n\t\t\t\tthis.deps.recordGoalContinuationPass({ ...passAccounting, wallClockMs: now() - passStartedAt });\n\t\t\t}\n\n\t\t\tif (hasReachedWallClockBudget()) {\n\t\t\t\treturn { turnsSubmitted, stopReason: \"wall_clock_budget_reached\", finalSnapshot: snapshot() };\n\t\t\t}\n\n\t\t\tlet afterSnapshot = snapshot();\n\t\t\tif (afterSnapshot.goalState?.status === \"budget_limited\") {\n\t\t\t\treturn { turnsSubmitted, stopReason: \"goal_budget_exhausted\", finalSnapshot: afterSnapshot };\n\t\t\t}\n\t\t\tconst afterBudgetExhaustion = getExplicitGoalBudgetExhaustion(afterSnapshot.goalState);\n\t\t\tif (afterBudgetExhaustion) {\n\t\t\t\tthis.deps.markGoalBudgetLimited(afterBudgetExhaustion);\n\t\t\t\tafterSnapshot = snapshot();\n\t\t\t\treturn { turnsSubmitted, stopReason: \"goal_budget_exhausted\", finalSnapshot: afterSnapshot };\n\t\t\t}\n\t\t\tif (afterSnapshot.continuation.action !== \"continue\") {\n\t\t\t\treturn { turnsSubmitted, stopReason: nonContinueStopReason(afterSnapshot), finalSnapshot: afterSnapshot };\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tturnsSubmitted,\n\t\t\tstopReason: \"max_turns_reached\",\n\t\t\tfinalSnapshot: snapshot(),\n\t\t};\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"goal-loop-controller.js","sourceRoot":"","sources":["../../src/core/goal-loop-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AASjE,OAAO,EACN,2BAA2B,EAC3B,qCAAqC,GACrC,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAE5E,OAAO,EAAkB,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAE9E;;;;GAIG;AACH,SAAS,+BAA+B,CAAC,KAA4B;IACpE,IAAI,CAAC,KAAK,IAAI,CAAC,qBAAqB,CAAC,KAAK,CAAC,MAAM,CAAC;QAAE,OAAO,SAAS,CAAC;IACrE,IAAI,KAAK,CAAC,WAAW,KAAK,SAAS,IAAI,CAAC,KAAK,CAAC,UAAU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AC;QAED,OAAO;YACN,cAAc;YACd,UAAU,EAAE,mBAAmB;YAC/B,aAAa,EAAE,QAAQ,EAAE;SACzB,CAAC;IACH,CAAC;CACD","sourcesContent":["/**\n * Goal auto-continuation loop.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Drives the bounded \"keep the\n * active goal moving\" loop: each pass reads the goal runtime snapshot, and — only while the snapshot\n * says `continue` — submits one continuation prompt back through the session's own prompt path. It\n * owns no state; the goal state lives in the session log and is read fresh every pass. Termination is\n * gated only by real terminal conditions and limits the owner explicitly supplied: an optional\n * per-invocation turn cap, an optional per-invocation wall-clock cap, and an optional durable token\n * budget on the goal. Each submitted pass still reports turn/wall-clock telemetry; provider usage\n * and spend are attributed at the response boundary. The host compares each pass's authoritative\n * progress revision and records unchanged passes as stalls, so a model cannot bypass the stall\n * limit by omitting a voluntary `no_progress` call.\n */\n\nimport { AgentBusyError } from \"@caupulican/pi-agent-core/agent\";\nimport type {\n\tGoalContinuationLoopOptions,\n\tGoalContinuationLoopResult,\n\tGoalContinuationLoopStopReason,\n\tGoalContinuationOnceOptions,\n\tGoalContinuationOnceResult,\n\tPromptOptions,\n} from \"./agent-session-contracts.ts\";\nimport {\n\tbuildGoalContinuationPrompt,\n\tGOAL_CONTINUATION_TRIGGER_CUSTOM_TYPE,\n} from \"./goals/goal-continuation-prompt.ts\";\nimport { GoalBudgetExhaustedError } from \"./goals/goal-execution-errors.ts\";\nimport type { GoalRuntimeSnapshot, GoalRuntimeSnapshotSettings } from \"./goals/goal-runtime-snapshot.ts\";\nimport { type GoalState, isGoalExecutionActive } from \"./goals/goal-state.ts\";\n\n/**\n * Resolve an owner-supplied durable goal budget. Wall-clock and spend counters are deliberately\n * absent here: they are telemetry unless the public goal contract grows matching explicit limits.\n * Execution limits are policy inputs, not hidden runtime defaults.\n */\nfunction getExplicitGoalBudgetExhaustion(state: GoalState | undefined): string | undefined {\n\tif (!state || !isGoalExecutionActive(state.status)) return undefined;\n\tif (state.tokenBudget !== undefined && (state.tokensUsed ?? 0) >= state.tokenBudget) {\n\t\treturn `token budget exhausted (${state.tokensUsed ?? 0}/${state.tokenBudget})`;\n\t}\n\treturn undefined;\n}\n\n/**\n * Maps a non-\"continue\" continuation action onto the loop's own stopReason vocabulary.\n * `\"waiting\"` (a worker is dispatched against an open requirement) gets its OWN benign stopReason so\n * a wait is never misreported as `continuation_not_allowed` (which reads as a terminal refusal) —\n * callers/telemetry can tell \"paused, will resume on its own\" apart from \"stopped, needs a human or a\n * new decision.\" Every other non-continue action (ask-user/finalize/stop) keeps the existing\n * `continuation_not_allowed` stopReason unchanged.\n */\nfunction nonContinueStopReason(snapshot: GoalRuntimeSnapshot): GoalContinuationLoopStopReason {\n\treturn snapshot.continuation.action === \"waiting\" ? \"worker_in_flight\" : \"continuation_not_allowed\";\n}\n\nexport interface GoalLoopControllerDeps {\n\t/** Read the current goal runtime snapshot (continuation decision + goal state) fresh each pass. */\n\tgetGoalRuntimeSnapshot(settings: GoalRuntimeSnapshotSettings): GoalRuntimeSnapshot;\n\t/** Submit a continuation prompt through the session's own prompt path. */\n\tprompt(text: string, options?: PromptOptions): Promise<void>;\n\t/**\n\t * Persist one submitted pass's turn and active-wall-clock contribution. Provider usage is charged\n\t * at each assistant response before another request can be admitted. Called once per\n\t * pass actually SUBMITTED (never for a no-op `continueGoalOnce` call).\n\t */\n\trecordGoalContinuationPass(pass: {\n\t\tturns: number;\n\t\twallClockMs: number;\n\t\tgoalId: string;\n\t\tprogressRevision: number;\n\t\tstallTurns: number;\n\t}): void;\n\t/** Persist an exhausted/non-retryable continuation failure as a stopped goal state. */\n\trecordGoalContinuationFailure(error: unknown): void;\n\t/** Persist a reason-specific budget terminal state before returning control. */\n\tmarkGoalBudgetLimited(reason: string): void;\n}\n\nexport class GoalLoopController {\n\tprivate readonly deps: GoalLoopControllerDeps;\n\n\tconstructor(deps: GoalLoopControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tasync continueGoalOnce(options: GoalContinuationOnceOptions): Promise<GoalContinuationOnceResult> {\n\t\tconst snapshot = this.deps.getGoalRuntimeSnapshot({ maxStallTurns: options.maxStallTurns });\n\n\t\tif (snapshot.continuation.action !== \"continue\") {\n\t\t\treturn { submitted: false, snapshot };\n\t\t}\n\n\t\tconst prompt = buildGoalContinuationPrompt();\n\t\tawait this.deps.prompt(prompt.text, {\n\t\t\texpandPromptTemplates: false,\n\t\t\tprocessSlashCommands: false,\n\t\t\tautoContinueGoal: false,\n\t\t\tinternalContextType: GOAL_CONTINUATION_TRIGGER_CUSTOM_TYPE,\n\t\t\tgoalExecutionId: snapshot.goalState?.goalId,\n\t\t});\n\n\t\treturn { submitted: true, snapshot, prompt };\n\t}\n\n\tasync continueGoalLoop(options: GoalContinuationLoopOptions): Promise<GoalContinuationLoopResult> {\n\t\tif (!Number.isSafeInteger(options.maxTurns) || options.maxTurns < 0) {\n\t\t\tthrow new Error(\"Goal continuation maxTurns must be a non-negative safe integer; 0 means unbounded.\");\n\t\t}\n\t\tlet turnsSubmitted = 0;\n\t\tconst hasExplicitTurnLimit = options.maxTurns > 0;\n\t\tconst now = options.now ?? Date.now;\n\t\tconst maxWallClockMs =\n\t\t\ttypeof options.maxWallClockMinutes === \"number\" && options.maxWallClockMinutes > 0\n\t\t\t\t? options.maxWallClockMinutes * 60_000\n\t\t\t\t: undefined;\n\t\tconst startedAt = now();\n\t\tconst hasReachedWallClockBudget = () => maxWallClockMs !== undefined && now() - startedAt >= maxWallClockMs;\n\t\tconst snapshot = () => this.deps.getGoalRuntimeSnapshot({ maxStallTurns: options.maxStallTurns });\n\n\t\tif (hasReachedWallClockBudget()) {\n\t\t\treturn { turnsSubmitted, stopReason: \"wall_clock_budget_reached\", finalSnapshot: snapshot() };\n\t\t}\n\n\t\twhile (!hasExplicitTurnLimit || turnsSubmitted < options.maxTurns) {\n\t\t\tconst beforeSnapshot = snapshot();\n\t\t\tif (beforeSnapshot.continuation.action !== \"continue\") {\n\t\t\t\treturn { turnsSubmitted, stopReason: nonContinueStopReason(beforeSnapshot), finalSnapshot: beforeSnapshot };\n\t\t\t}\n\n\t\t\t// Owner-supplied durable token budget — read fresh every pass so an invocation stops as\n\t\t\t// soon as its own latest persisted usage crosses the explicit ceiling.\n\t\t\tconst beforeBudgetExhaustion = getExplicitGoalBudgetExhaustion(beforeSnapshot.goalState);\n\t\t\tif (beforeBudgetExhaustion) {\n\t\t\t\tthis.deps.markGoalBudgetLimited(beforeBudgetExhaustion);\n\t\t\t\treturn { turnsSubmitted, stopReason: \"goal_budget_exhausted\", finalSnapshot: snapshot() };\n\t\t\t}\n\n\t\t\tconst passStartedAt = now();\n\t\t\tconst beforeGoal = beforeSnapshot.goalState;\n\t\t\tif (!beforeGoal) {\n\t\t\t\treturn { turnsSubmitted, stopReason: \"continuation_not_allowed\", finalSnapshot: beforeSnapshot };\n\t\t\t}\n\t\t\tconst passAccounting = {\n\t\t\t\tturns: 1,\n\t\t\t\tgoalId: beforeGoal.goalId,\n\t\t\t\tprogressRevision: beforeGoal.progressRevision ?? 0,\n\t\t\t\tstallTurns: beforeGoal.stallTurns,\n\t\t\t};\n\t\t\tlet result: GoalContinuationOnceResult;\n\t\t\ttry {\n\t\t\t\tresult = await this.continueGoalOnce(options);\n\t\t\t} catch (error) {\n\t\t\t\t// Prompt admission did not happen. A concurrent foreground owner is transient session\n\t\t\t\t// coordination, not a consumed goal turn and not evidence that the goal is blocked.\n\t\t\t\tif (error instanceof AgentBusyError) throw error;\n\t\t\t\tif (error instanceof GoalBudgetExhaustedError) {\n\t\t\t\t\t// The goal already stopped itself durably (markBudgetLimited ran synchronously before\n\t\t\t\t\t// this signal was thrown) — surface the existing clean stop instead of charging a turn.\n\t\t\t\t\treturn { turnsSubmitted, stopReason: \"goal_budget_exhausted\", finalSnapshot: snapshot() };\n\t\t\t\t}\n\t\t\t\tturnsSubmitted++;\n\t\t\t\tthis.deps.recordGoalContinuationPass({ ...passAccounting, wallClockMs: now() - passStartedAt });\n\t\t\t\tthis.deps.recordGoalContinuationFailure(error);\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (result.submitted) {\n\t\t\t\tturnsSubmitted++;\n\t\t\t\tthis.deps.recordGoalContinuationPass({ ...passAccounting, wallClockMs: now() - passStartedAt });\n\t\t\t}\n\n\t\t\tif (hasReachedWallClockBudget()) {\n\t\t\t\treturn { turnsSubmitted, stopReason: \"wall_clock_budget_reached\", finalSnapshot: snapshot() };\n\t\t\t}\n\n\t\t\tlet afterSnapshot = snapshot();\n\t\t\tif (afterSnapshot.goalState?.status === \"budget_limited\") {\n\t\t\t\treturn { turnsSubmitted, stopReason: \"goal_budget_exhausted\", finalSnapshot: afterSnapshot };\n\t\t\t}\n\t\t\tconst afterBudgetExhaustion = getExplicitGoalBudgetExhaustion(afterSnapshot.goalState);\n\t\t\tif (afterBudgetExhaustion) {\n\t\t\t\tthis.deps.markGoalBudgetLimited(afterBudgetExhaustion);\n\t\t\t\tafterSnapshot = snapshot();\n\t\t\t\treturn { turnsSubmitted, stopReason: \"goal_budget_exhausted\", finalSnapshot: afterSnapshot };\n\t\t\t}\n\t\t\tif (afterSnapshot.continuation.action !== \"continue\") {\n\t\t\t\treturn { turnsSubmitted, stopReason: nonContinueStopReason(afterSnapshot), finalSnapshot: afterSnapshot };\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tturnsSubmitted,\n\t\t\tstopReason: \"max_turns_reached\",\n\t\t\tfinalSnapshot: snapshot(),\n\t\t};\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"goal-auto-continue-controller.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-auto-continue-controller.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACX,iBAAiB,EACjB,2BAA2B,EAC3B,0BAA0B,EAC1B,aAAa,EACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,KAAK,EAAE,mBAAmB,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AAEnG,MAAM,WAAW,8BAA8B;IAC9C,UAAU,IAAI,OAAO,CAAC;IACtB,gBAAgB,IAAI,OAAO,CAAC;IAC5B,kBAAkB,IAAI,eAAe,CAAC;IACtC,sBAAsB,CAAC,QAAQ,EAAE,2BAA2B,GAAG,mBAAmB,CAAC;IACnF,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC;IAChD,gBAAgB,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAAC;IAC5F,gBAAgB,IAAI,OAAO,CAAC;IAC5B,qBAAqB,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvC,uBAAuB,IAAI,IAAI,CAAC;IAChC,IAAI,CAAC,KAAK,EAAE,iBAAiB,GAAG,IAAI,CAAC;CACrC;AAED,mFAAmF;AACnF,qBAAa,0BAA0B;IACtC,OAAO,CAAC,MAAM,CAA4C;IAC1D,OAAO,CAAC,aAAa,CAAS;IAC9B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAiC;IAEtD,YAAY,IAAI,EAAE,8BAA8B,EAE/C;IAED,UAAU,IAAI,IAAI,CAKjB;IAED,gBAAgB,CAAC,OAAO,CAAC,EAAE,aAAa,GAAG,IAAI,CAsB9C;IAEK,iBAAiB,CAAC,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAqBjG;IAED,OAAO,CAAC,iBAAiB;YAOX,YAAY;
|
|
1
|
+
{"version":3,"file":"goal-auto-continue-controller.d.ts","sourceRoot":"","sources":["../../../src/core/goals/goal-auto-continue-controller.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACX,iBAAiB,EACjB,2BAA2B,EAC3B,0BAA0B,EAC1B,aAAa,EACb,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,KAAK,EAAE,m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