@caupulican/pi-adaptative 0.93.3 → 0.93.4
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 +16 -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/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/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.map +1 -1
- package/dist/core/tools/shell-session.js +6 -1
- package/dist/core/tools/shell-session.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/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":"capability-gateway.js","sourceRoot":"","sources":["../../../src/core/orchestration/capability-gateway.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AAClF,OAAO,EAAE,oBAAoB,EAAE,MAAM,qCAAqC,CAAC;AAC3E,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAChF,OAAO,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AA6ElE;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,GAAG,CAAC;AAE5C;;;GAGG;AACH,MAAM,UAAU,cAAc,CAAC,KAM9B;IACA,MAAM,QAAQ,GAAG,KAAK,CAAC,WAAW,GAAG,KAAK,CAAC,YAAY,GAAG,KAAK,CAAC,gBAAgB,CAAC;IACjF,MAAM,YAAY,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,WAAW,GAAG,QAAQ,GA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D,CAAC;QACD,OAAO,YAAY,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE;YACpC,MAAM,IAAI,GAAG,eAAe,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;YAChD,OAAO,IAAI,KAAK,SAAS,IAAI,iBAAiB,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAC9D,CAAC,CAAC,CAAC;IACJ,CAAC;IAEO,IAAI,CAAC,QAAgB,EAAE,UAA+B,EAAE,OAAe;QAC9E,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,MAAM,EAAE,UAAU,CAAC,CAAC;QACzC,MAAM,IAAI,4BAA4B,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAC7D,CAAC;IAEO,KAAK,CAAC,QAAgB,EAAE,OAAyB,EAAE,UAA+B;QACzF,IAAI,CAAC,OAAO,EAAE,CAAC;YACd,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,OAAO;YAC3B,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,SAAS;YAC/B,QAAQ;YACR,OAAO;YACP,UAAU;YACV,EAAE,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,WAAW,EAAE;SAC9C,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["import { resolve } from \"node:path\";\nimport { BoundedCompletionFailureError } from \"../autonomy/bounded-completion.ts\";\nimport { extractPathArguments } from \"../autonomy/envelope-enforcement.ts\";\nimport { isPathWithinScope, safeRealpathSync } from \"../autonomy/path-scope.ts\";\nimport { validateAttemptUsageSnapshot } from \"./attempt-usage.ts\";\nimport type { AttemptUsageSnapshot, ExecutionGrant, HarnessCapability, ToolCapabilityManifest } from \"./contracts.ts\";\n\nexport type GatewayDecisionCode =\n\t| \"allowed\"\n\t| \"grant_expired\"\n\t| \"tool_not_granted\"\n\t| \"manifest_name_mismatch\"\n\t| \"capability_not_granted\"\n\t| \"path_argument_required\"\n\t| \"path_outside_scope\"\n\t| \"scope_denied\"\n\t| \"tool_call_budget_exhausted\"\n\t| \"token_budget_exhausted\"\n\t| \"cost_budget_exhausted\"\n\t| \"wall_clock_budget_exhausted\";\n\nexport interface GatewayAuditRecord {\n\tgrantId: string;\n\tattemptId: string;\n\ttoolName: string;\n\toutcome: \"allow\" | \"deny\";\n\treasonCode: GatewayDecisionCode;\n\tat: string;\n}\n\nexport interface CapabilityGatewayOptions {\n\tgrant: ExecutionGrant;\n\tcwd: string;\n\t/** Durable active usage carried forward when an attempt resumes in a new process. */\n\tinitialUsage?: GatewayInitialUsage;\n\tnow?: () => number;\n\tonAudit?: (record: GatewayAuditRecord) => void;\n\t/** Session-tree cumulative budget owner. Per-attempt grants remain independently enforced. */\n\tsharedBudget?: SharedCapabilityBudget;\n}\n\nexport interface GatewayUsageDelta {\n\tinputTokens?: number;\n\toutputTokens?: number;\n\tcacheReadTokens?: number;\n\tcacheWriteTokens?: number;\n\t/** Provider-authoritative total. Defaults to the supplied detail sum when omitted. */\n\ttotalTokens?: number;\n\tcostUsd?: number;\n}\n\nexport interface GatewayUsageSnapshot {\n\ttoolCalls: number;\n\tinputTokens: number;\n\toutputTokens: number;\n\tcacheReadTokens: number;\n\tcacheWriteTokens: number;\n\ttotalTokens: number;\n\tcostUsd: number;\n\twallClockMs: number;\n}\n\nexport interface ProviderBudgetReservation {\n\tmaxTokens: number;\n\trelease(): void;\n}\n\nexport interface SharedCapabilityBudget {\n\tassertBudgetAvailable(subject: string): void;\n\trecordAttemptUsage(usage: GatewayUsageSnapshot): void;\n\tremainingTokens(): number | undefined;\n\treserveProviderBudget(\n\t\trequestedMaxTokens: number,\n\t\tsubject: string,\n\t\tsignal?: AbortSignal,\n\t): Promise<ProviderBudgetReservation>;\n}\n\n/** Persistable cumulative usage from a prior active segment; excludes restart downtime. */\nexport type GatewayInitialUsage = AttemptUsageSnapshot;\n\n/**\n * Weight applied to prompt-cache reads when charging token budgets. Cache reads re-bill the\n * same context on every request (a worker's fixed system prompt alone is thousands of tokens),\n * so charging them at face value turns `maxTokens` into a request counter: a 9k grant died in\n * 2-3 responses while doing ~500 tokens of real work per response (field session 019fd4dc).\n * The weight mirrors the typical cache-read price ratio; money stays bounded by `maxCostUsd`.\n */\nexport const CACHE_READ_BUDGET_WEIGHT = 0.1;\n\n/**\n * Tokens charged against `maxTokens` budgets: real work at face value, cache reads discounted.\n * A provider-authoritative total above the detail sum is unattributed usage and charges fully.\n */\nexport function budgetedTokens(usage: {\n\tinputTokens: number;\n\toutputTokens: number;\n\tcacheReadTokens: number;\n\tcacheWriteTokens: number;\n\ttotalTokens: number;\n}): number {\n\tconst detailed = usage.inputTokens + usage.outputTokens + usage.cacheWriteTokens;\n\tconst unattributed = Math.max(0, usage.totalTokens - detailed - usage.cacheReadTokens);\n\treturn detailed + unattributed + Math.ceil(usage.cacheReadTokens * CACHE_READ_BUDGET_WEIGHT);\n}\n\nconst BUDGET_EXHAUSTION_DECISION_CODES: ReadonlySet<GatewayDecisionCode> = new Set([\n\t\"tool_call_budget_exhausted\",\n\t\"token_budget_exhausted\",\n\t\"cost_budget_exhausted\",\n\t\"wall_clock_budget_exhausted\",\n]);\n\nexport class CapabilityGatewayDeniedError extends BoundedCompletionFailureError {\n\treadonly reasonCode: GatewayDecisionCode;\n\n\tconstructor(reasonCode: GatewayDecisionCode, message: string) {\n\t\tsuper(BUDGET_EXHAUSTION_DECISION_CODES.has(reasonCode) ? \"budget_exhausted\" : \"failed\", reasonCode, message);\n\t\tthis.name = \"CapabilityGatewayDeniedError\";\n\t\tthis.reasonCode = reasonCode;\n\t}\n}\n\nconst PATH_CAPABILITIES: ReadonlySet<HarnessCapability> = new Set([\n\t\"filesystem.read\",\n\t\"filesystem.write\",\n\t\"worktree.read\",\n\t\"worktree.mutate\",\n]);\n\nconst WRITE_CAPABILITIES: ReadonlySet<HarnessCapability> = new Set([\"filesystem.write\", \"worktree.mutate\"]);\n\nfunction resolveRealPath(cwd: string, value: string): string | undefined {\n\ttry {\n\t\treturn safeRealpathSync(resolve(cwd, value));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction validateInitialUsage(usage: GatewayInitialUsage): void {\n\ttry {\n\t\tvalidateAttemptUsageSnapshot(usage, \"CapabilityGateway: initial usage\");\n\t} catch {\n\t\tthrow new Error(\n\t\t\t\"CapabilityGateway: initial usage must contain finite non-negative values and safe-integer counts.\",\n\t\t);\n\t}\n}\n\nfunction validatedUsageDelta(delta: GatewayUsageDelta): Required<GatewayUsageDelta> {\n\tconst inputTokens = delta.inputTokens === undefined ? 0 : delta.inputTokens;\n\tconst outputTokens = delta.outputTokens === undefined ? 0 : delta.outputTokens;\n\tconst cacheReadTokens = delta.cacheReadTokens === undefined ? 0 : delta.cacheReadTokens;\n\tconst cacheWriteTokens = delta.cacheWriteTokens === undefined ? 0 : delta.cacheWriteTokens;\n\tconst totalTokens =\n\t\tdelta.totalTokens === undefined\n\t\t\t? inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens\n\t\t\t: delta.totalTokens;\n\tconst costUsd = delta.costUsd === undefined ? 0 : delta.costUsd;\n\tif (\n\t\t!Number.isSafeInteger(inputTokens) ||\n\t\tinputTokens < 0 ||\n\t\t!Number.isSafeInteger(outputTokens) ||\n\t\toutputTokens < 0 ||\n\t\t!Number.isSafeInteger(cacheReadTokens) ||\n\t\tcacheReadTokens < 0 ||\n\t\t!Number.isSafeInteger(cacheWriteTokens) ||\n\t\tcacheWriteTokens < 0 ||\n\t\t!Number.isSafeInteger(totalTokens) ||\n\t\ttotalTokens < 0 ||\n\t\t!Number.isFinite(costUsd) ||\n\t\tcostUsd < 0\n\t) {\n\t\tthrow new Error(\n\t\t\t\"CapabilityGateway: usage delta must contain finite non-negative values and safe-integer token counts.\",\n\t\t);\n\t}\n\treturn { inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, totalTokens, costUsd };\n}\n\n/**\n * Per-invocation enforcement for an already-compiled grant. The compiler controls what may be\n * loaded; this gateway independently rechecks authority, path scope, expiry, and cumulative budget\n * immediately before execution.\n */\nexport class CapabilityGateway {\n\tprivate readonly grant: ExecutionGrant;\n\tprivate readonly cwd: string;\n\tprivate readonly now: () => number;\n\tprivate readonly onAudit?: (record: GatewayAuditRecord) => void;\n\tprivate readonly sharedBudget?: SharedCapabilityBudget;\n\tprivate readonly startedAt: number;\n\tprivate readonly initialWallClockMs: number;\n\tprivate toolCalls: number;\n\tprivate inputTokens: number;\n\tprivate outputTokens: number;\n\tprivate cacheReadTokens: number;\n\tprivate cacheWriteTokens: number;\n\tprivate totalTokens: number;\n\tprivate costUsd: number;\n\n\tconstructor(options: CapabilityGatewayOptions) {\n\t\tconst initialUsage: GatewayInitialUsage = options.initialUsage ?? {\n\t\t\ttoolCalls: 0,\n\t\t\tinputTokens: 0,\n\t\t\toutputTokens: 0,\n\t\t\tcacheReadTokens: 0,\n\t\t\tcacheWriteTokens: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcostUsd: 0,\n\t\t\tactiveWallClockMs: 0,\n\t\t};\n\t\tvalidateInitialUsage(initialUsage);\n\t\tthis.grant = options.grant;\n\t\tthis.cwd = options.cwd;\n\t\tthis.now = options.now ?? Date.now;\n\t\tthis.onAudit = options.onAudit;\n\t\tthis.sharedBudget = options.sharedBudget;\n\t\tthis.startedAt = this.currentTime();\n\t\tthis.initialWallClockMs = initialUsage.activeWallClockMs;\n\t\tthis.toolCalls = initialUsage.toolCalls;\n\t\tthis.inputTokens = initialUsage.inputTokens;\n\t\tthis.outputTokens = initialUsage.outputTokens;\n\t\tthis.cacheReadTokens = initialUsage.cacheReadTokens;\n\t\tthis.cacheWriteTokens = initialUsage.cacheWriteTokens;\n\t\tthis.totalTokens = initialUsage.totalTokens;\n\t\tthis.costUsd = initialUsage.costUsd;\n\t\tthis.sharedBudget?.recordAttemptUsage(this.getUsage());\n\t}\n\n\tasync execute<T>(\n\t\tmanifest: ToolCapabilityManifest,\n\t\ttoolName: string,\n\t\tparams: unknown,\n\t\tinvoke: () => Promise<T> | T,\n\t): Promise<T> {\n\t\tthis.authorizeToolCall(manifest, toolName, params);\n\t\treturn await invoke();\n\t}\n\n\t/** Immediate pre-execution authorization for runtimes that expose a before-tool-call hook. */\n\tauthorizeToolCall(manifest: ToolCapabilityManifest, toolName: string, params: unknown): void {\n\t\tconst now = this.currentTime();\n\t\tconst wallClockMs = this.wallClockMsAt(now);\n\t\tthis.authorize(manifest, toolName, params, now, wallClockMs);\n\t\tconst toolCalls = this.toolCalls + 1;\n\t\tif (!Number.isSafeInteger(toolCalls)) {\n\t\t\tthrow new Error(\"CapabilityGateway: tool-call count would exceed safe cumulative usage bounds.\");\n\t\t}\n\t\tthis.toolCalls = toolCalls;\n\t\tthis.sharedBudget?.recordAttemptUsage(this.getUsage());\n\t\tthis.audit(toolName, \"allow\", \"allowed\");\n\t}\n\n\trecordUsage(delta: GatewayUsageDelta): void {\n\t\tconst validated = validatedUsageDelta(delta);\n\t\tconst inputTokens = this.inputTokens + validated.inputTokens;\n\t\tconst outputTokens = this.outputTokens + validated.outputTokens;\n\t\tconst cacheReadTokens = this.cacheReadTokens + validated.cacheReadTokens;\n\t\tconst cacheWriteTokens = this.cacheWriteTokens + validated.cacheWriteTokens;\n\t\tconst totalTokens = this.totalTokens + validated.totalTokens;\n\t\tconst costUsd = this.costUsd + validated.costUsd;\n\t\tif (\n\t\t\t!Number.isSafeInteger(inputTokens) ||\n\t\t\t!Number.isSafeInteger(outputTokens) ||\n\t\t\t!Number.isSafeInteger(cacheReadTokens) ||\n\t\t\t!Number.isSafeInteger(cacheWriteTokens) ||\n\t\t\t!Number.isSafeInteger(totalTokens) ||\n\t\t\t!Number.isFinite(costUsd)\n\t\t) {\n\t\t\tthrow new Error(\"CapabilityGateway: usage delta would exceed safe cumulative usage bounds.\");\n\t\t}\n\t\tthis.inputTokens = inputTokens;\n\t\tthis.outputTokens = outputTokens;\n\t\tthis.cacheReadTokens = cacheReadTokens;\n\t\tthis.cacheWriteTokens = cacheWriteTokens;\n\t\tthis.totalTokens = totalTokens;\n\t\tthis.costUsd = costUsd;\n\t\tthis.sharedBudget?.recordAttemptUsage(this.getUsage());\n\t}\n\n\t/** Enforce resumed cumulative budgets before a provider request that has no tool-call boundary. */\n\tassertBudgetAvailable(subject = \"provider\"): void {\n\t\tthis.enforceBudget(subject, this.wallClockMsAt(this.currentTime()));\n\t\tthis.sharedBudget?.assertBudgetAvailable(subject);\n\t}\n\n\tasync reserveProviderBudget(\n\t\trequestedMaxTokens: number,\n\t\tsubject = \"provider\",\n\t\tsignal?: AbortSignal,\n\t): Promise<ProviderBudgetReservation> {\n\t\tif (!Number.isSafeInteger(requestedMaxTokens) || requestedMaxTokens <= 0) {\n\t\t\tthrow new Error(\"CapabilityGateway: provider token reservation must be a positive safe integer.\");\n\t\t}\n\t\tthis.assertBudgetAvailable(subject);\n\t\tconst localRemaining = this.remainingAttemptTokenBudget();\n\t\tconst maxTokens = Math.min(requestedMaxTokens, localRemaining ?? requestedMaxTokens);\n\t\tif (maxTokens <= 0) {\n\t\t\tthis.deny(subject, \"token_budget_exhausted\", \"Token budget exhausted.\");\n\t\t}\n\t\tif (this.sharedBudget) return this.sharedBudget.reserveProviderBudget(maxTokens, subject, signal);\n\t\tif (signal?.aborted) throw signal.reason;\n\t\treturn {\n\t\t\tmaxTokens,\n\t\t\trelease: () => undefined,\n\t\t};\n\t}\n\n\tremainingAttemptTokenBudget(): number | undefined {\n\t\tconst maximum = this.grant.budget.maxTokens;\n\t\treturn maximum === undefined ? undefined : Math.max(0, maximum - budgetedTokens(this.getUsage()));\n\t}\n\n\tremainingTokenBudget(): number | undefined {\n\t\tconst localRemaining = this.remainingAttemptTokenBudget();\n\t\tconst sharedRemaining = this.sharedBudget?.remainingTokens();\n\t\tif (localRemaining === undefined) return sharedRemaining;\n\t\tif (sharedRemaining === undefined) return localRemaining;\n\t\treturn Math.min(localRemaining, sharedRemaining);\n\t}\n\n\tgetUsage(): GatewayUsageSnapshot {\n\t\treturn {\n\t\t\ttoolCalls: this.toolCalls,\n\t\t\tinputTokens: this.inputTokens,\n\t\t\toutputTokens: this.outputTokens,\n\t\t\tcacheReadTokens: this.cacheReadTokens,\n\t\t\tcacheWriteTokens: this.cacheWriteTokens,\n\t\t\ttotalTokens: this.totalTokens,\n\t\t\tcostUsd: this.costUsd,\n\t\t\twallClockMs: this.wallClockMsAt(this.currentTime()),\n\t\t};\n\t}\n\n\tprivate authorize(\n\t\tmanifest: ToolCapabilityManifest,\n\t\ttoolName: string,\n\t\tparams: unknown,\n\t\tnow: number,\n\t\twallClockMs: number,\n\t): void {\n\t\tif (this.grant.expiresAt && Date.parse(this.grant.expiresAt) <= now) {\n\t\t\tthis.deny(toolName, \"grant_expired\", `Execution grant '${this.grant.grantId}' expired.`);\n\t\t}\n\t\tif (!this.grant.allowedTools.includes(toolName)) {\n\t\t\tthis.deny(toolName, \"tool_not_granted\", `Tool '${toolName}' is not in grant '${this.grant.grantId}'.`);\n\t\t}\n\t\tif (manifest.toolName !== toolName) {\n\t\t\tthis.deny(toolName, \"manifest_name_mismatch\", `Tool '${toolName}' does not match its capability manifest.`);\n\t\t}\n\t\tif (!manifest.capabilities.every((capability) => this.grant.capabilities.includes(capability))) {\n\t\t\tthis.deny(toolName, \"capability_not_granted\", `Tool '${toolName}' requires an ungranted capability.`);\n\t\t}\n\t\tthis.enforceBudget(toolName, wallClockMs);\n\t\tthis.sharedBudget?.assertBudgetAvailable(toolName);\n\n\t\tif (manifest.capabilities.some((capability) => PATH_CAPABILITIES.has(capability))) {\n\t\t\tconst isWrite = manifest.capabilities.some((capability) => WRITE_CAPABILITIES.has(capability));\n\t\t\tconst allowedPaths = isWrite ? this.grant.writePaths : this.grant.readPaths;\n\t\t\tconst paths = extractPathArguments(params);\n\t\t\tif (paths.length === 0) {\n\t\t\t\tthis.deny(toolName, \"path_argument_required\", `Tool '${toolName}' requires an explicit path argument.`);\n\t\t\t}\n\t\t\tfor (const rawPath of paths) {\n\t\t\t\tif (!this.pathAllowed(rawPath, allowedPaths)) {\n\t\t\t\t\tconst reasonCode = isWrite ? \"scope_denied\" : \"path_outside_scope\";\n\t\t\t\t\tthis.deny(toolName, reasonCode, `Path '${rawPath}' is outside grant '${this.grant.grantId}'.`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate enforceBudget(toolName: string, wallClockMs: number): void {\n\t\tconst budget = this.grant.budget;\n\t\tif (budget.maxToolCalls !== undefined && this.toolCalls >= budget.maxToolCalls) {\n\t\t\tthis.deny(toolName, \"tool_call_budget_exhausted\", \"Tool-call budget exhausted.\");\n\t\t}\n\t\tif (budget.maxTokens !== undefined && budgetedTokens(this.getUsage()) >= budget.maxTokens) {\n\t\t\tthis.deny(toolName, \"token_budget_exhausted\", \"Token budget exhausted.\");\n\t\t}\n\t\tif (budget.maxCostUsd !== undefined && this.costUsd >= budget.maxCostUsd) {\n\t\t\tthis.deny(toolName, \"cost_budget_exhausted\", \"Cost budget exhausted.\");\n\t\t}\n\t\tif (budget.maxWallClockMs !== undefined && wallClockMs >= budget.maxWallClockMs) {\n\t\t\tthis.deny(toolName, \"wall_clock_budget_exhausted\", \"Wall-clock budget exhausted.\");\n\t\t}\n\t}\n\n\tprivate currentTime(): number {\n\t\tconst now = this.now();\n\t\tif (!Number.isFinite(now)) {\n\t\t\tthrow new Error(\"CapabilityGateway: clock source must return a finite time.\");\n\t\t}\n\t\treturn now;\n\t}\n\n\tprivate wallClockMsAt(now: number): number {\n\t\tconst elapsed = now - this.startedAt;\n\t\tif (!Number.isFinite(elapsed)) {\n\t\t\tthrow new Error(\"CapabilityGateway: active wall-clock elapsed time must be finite.\");\n\t\t}\n\t\tconst wallClockMs = this.initialWallClockMs + Math.max(0, elapsed);\n\t\tif (!Number.isFinite(wallClockMs) || wallClockMs < 0) {\n\t\t\tthrow new Error(\"CapabilityGateway: accumulated wall-clock usage must be finite and non-negative.\");\n\t\t}\n\t\treturn wallClockMs;\n\t}\n\n\tprivate pathAllowed(rawPath: string, allowedPaths: readonly string[]): boolean {\n\t\tconst target = resolveRealPath(this.cwd, rawPath);\n\t\tif (!target || allowedPaths.length === 0) return false;\n\t\tfor (const denied of this.grant.deniedPaths) {\n\t\t\tconst root = resolveRealPath(this.cwd, denied);\n\t\t\tif (root && isPathWithinScope(target, root)) return false;\n\t\t}\n\t\treturn allowedPaths.some((allowed) => {\n\t\t\tconst root = resolveRealPath(this.cwd, allowed);\n\t\t\treturn root !== undefined && isPathWithinScope(target, root);\n\t\t});\n\t}\n\n\tprivate deny(toolName: string, reasonCode: GatewayDecisionCode, message: string): never {\n\t\tthis.audit(toolName, \"deny\", reasonCode);\n\t\tthrow new CapabilityGatewayDeniedError(reasonCode, message);\n\t}\n\n\tprivate audit(toolName: string, outcome: \"allow\" | \"deny\", reasonCode: GatewayDecisionCode): void {\n\t\tthis.onAudit?.({\n\t\t\tgrantId: this.grant.grantId,\n\t\t\tattemptId: this.grant.attemptId,\n\t\t\ttoolName,\n\t\t\toutcome,\n\t\t\treasonCode,\n\t\t\tat: new Date(this.currentTime()).toISOString(),\n\t\t});\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"capability-gateway.js","sourceRoot":"","sources":["../../../src/core/orchestration/capability-gateway.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AAClF,OAAO,EAAE,wBAAwB,EAAE,MAAM,qCAAqC,CAAC;AAC/E,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAChF,OAAO,EACN,uBAAuB,EACvB,2BAA2B,EAC3B,2BAA2B,EAC3B,yBAAyB,GACzB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AA6ElE;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAG,GAAG,CAAC;AAE5C;;;GAGG;AACH,MAAM,UAAU,cAAc,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AAiB,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC,EAAE,CAAC;YAC1E,OAAO,KAAK,CAAC;QACd,CAAC;QACD,MAAM,MAAM,GAAG,eAAe,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAClD,IAAI,CAAC,MAAM;YAAE,OAAO,KAAK,CAAC;QAC1B,KAAK,MAAM,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC;YAC7C,MAAM,IAAI,GAAG,eAAe,CAAC,IAAI,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;YAC/C,IAAI,IAAI,IAAI,iBAAiB,CAAC,MAAM,EAAE,IAAI,CAAC;gBAAE,OAAO,KAAK,CAAC;QAC3D,CAAC;QACD,OAAO,YAAY,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,iBAAiB,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC;IACrE,CAAC;IAEO,IAAI,CAAC,QAAgB,EAAE,UAA+B,EAAE,OAAe;QAC9E,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,MAAM,EAAE,UAAU,CAAC,CAAC;QACzC,MAAM,IAAI,4BAA4B,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAC7D,CAAC;IAEO,KAAK,CAAC,QAAgB,EAAE,OAAyB,EAAE,UAA+B;QACzF,IAAI,CAAC,OAAO,EAAE,CAAC;YACd,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,OAAO;YAC3B,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,SAAS;YAC/B,QAAQ;YACR,OAAO;YACP,UAAU;YACV,EAAE,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,WAAW,EAAE;SAC9C,CAAC,CAAC;IACJ,CAAC;CACD","sourcesContent":["import { resolve } from \"node:path\";\nimport { BoundedCompletionFailureError } from \"../autonomy/bounded-completion.ts\";\nimport { extractToolPathArguments } from \"../autonomy/envelope-enforcement.ts\";\nimport { isPathWithinScope, safeRealpathSync } from \"../autonomy/path-scope.ts\";\nimport {\n\tgetToolCapabilityPolicy,\n\tresolveCapabilityPathAccess,\n\tresolveToolCallCapabilities,\n\tresolveToolCallPathAccess,\n} from \"../tool-capability-policy.ts\";\nimport { validateAttemptUsageSnapshot } from \"./attempt-usage.ts\";\nimport type { AttemptUsageSnapshot, ExecutionGrant, HarnessCapability, ToolCapabilityManifest } from \"./contracts.ts\";\n\nexport type GatewayDecisionCode =\n\t| \"allowed\"\n\t| \"grant_expired\"\n\t| \"tool_not_granted\"\n\t| \"manifest_name_mismatch\"\n\t| \"capability_not_granted\"\n\t| \"path_argument_required\"\n\t| \"path_outside_scope\"\n\t| \"scope_denied\"\n\t| \"tool_call_budget_exhausted\"\n\t| \"token_budget_exhausted\"\n\t| \"cost_budget_exhausted\"\n\t| \"wall_clock_budget_exhausted\";\n\nexport interface GatewayAuditRecord {\n\tgrantId: string;\n\tattemptId: string;\n\ttoolName: string;\n\toutcome: \"allow\" | \"deny\";\n\treasonCode: GatewayDecisionCode;\n\tat: string;\n}\n\nexport interface CapabilityGatewayOptions {\n\tgrant: ExecutionGrant;\n\tcwd: string;\n\t/** Durable active usage carried forward when an attempt resumes in a new process. */\n\tinitialUsage?: GatewayInitialUsage;\n\tnow?: () => number;\n\tonAudit?: (record: GatewayAuditRecord) => void;\n\t/** Session-tree cumulative budget owner. Per-attempt grants remain independently enforced. */\n\tsharedBudget?: SharedCapabilityBudget;\n}\n\nexport interface GatewayUsageDelta {\n\tinputTokens?: number;\n\toutputTokens?: number;\n\tcacheReadTokens?: number;\n\tcacheWriteTokens?: number;\n\t/** Provider-authoritative total. Defaults to the supplied detail sum when omitted. */\n\ttotalTokens?: number;\n\tcostUsd?: number;\n}\n\nexport interface GatewayUsageSnapshot {\n\ttoolCalls: number;\n\tinputTokens: number;\n\toutputTokens: number;\n\tcacheReadTokens: number;\n\tcacheWriteTokens: number;\n\ttotalTokens: number;\n\tcostUsd: number;\n\twallClockMs: number;\n}\n\nexport interface ProviderBudgetReservation {\n\tmaxTokens: number;\n\trelease(): void;\n}\n\nexport interface SharedCapabilityBudget {\n\tassertBudgetAvailable(subject: string): void;\n\trecordAttemptUsage(usage: GatewayUsageSnapshot): void;\n\tremainingTokens(): number | undefined;\n\treserveProviderBudget(\n\t\trequestedMaxTokens: number,\n\t\tsubject: string,\n\t\tsignal?: AbortSignal,\n\t): Promise<ProviderBudgetReservation>;\n}\n\n/** Persistable cumulative usage from a prior active segment; excludes restart downtime. */\nexport type GatewayInitialUsage = AttemptUsageSnapshot;\n\n/**\n * Weight applied to prompt-cache reads when charging token budgets. Cache reads re-bill the\n * same context on every request (a worker's fixed system prompt alone is thousands of tokens),\n * so charging them at face value turns `maxTokens` into a request counter: a 9k grant died in\n * 2-3 responses while doing ~500 tokens of real work per response (field session 019fd4dc).\n * The weight mirrors the typical cache-read price ratio; money stays bounded by `maxCostUsd`.\n */\nexport const CACHE_READ_BUDGET_WEIGHT = 0.1;\n\n/**\n * Tokens charged against `maxTokens` budgets: real work at face value, cache reads discounted.\n * A provider-authoritative total above the detail sum is unattributed usage and charges fully.\n */\nexport function budgetedTokens(usage: {\n\tinputTokens: number;\n\toutputTokens: number;\n\tcacheReadTokens: number;\n\tcacheWriteTokens: number;\n\ttotalTokens: number;\n}): number {\n\tconst detailed = usage.inputTokens + usage.outputTokens + usage.cacheWriteTokens;\n\tconst unattributed = Math.max(0, usage.totalTokens - detailed - usage.cacheReadTokens);\n\treturn detailed + unattributed + Math.ceil(usage.cacheReadTokens * CACHE_READ_BUDGET_WEIGHT);\n}\n\nconst BUDGET_EXHAUSTION_DECISION_CODES: ReadonlySet<GatewayDecisionCode> = new Set([\n\t\"tool_call_budget_exhausted\",\n\t\"token_budget_exhausted\",\n\t\"cost_budget_exhausted\",\n\t\"wall_clock_budget_exhausted\",\n]);\n\nexport class CapabilityGatewayDeniedError extends BoundedCompletionFailureError {\n\treadonly reasonCode: GatewayDecisionCode;\n\n\tconstructor(reasonCode: GatewayDecisionCode, message: string) {\n\t\tsuper(BUDGET_EXHAUSTION_DECISION_CODES.has(reasonCode) ? \"budget_exhausted\" : \"failed\", reasonCode, message);\n\t\tthis.name = \"CapabilityGatewayDeniedError\";\n\t\tthis.reasonCode = reasonCode;\n\t}\n}\n\nconst PATH_CAPABILITIES: ReadonlySet<HarnessCapability> = new Set([\n\t\"filesystem.read\",\n\t\"filesystem.write\",\n\t\"worktree.read\",\n\t\"worktree.mutate\",\n]);\n\nconst WRITE_CAPABILITIES: ReadonlySet<HarnessCapability> = new Set([\"filesystem.write\", \"worktree.mutate\"]);\n\nfunction resolveRealPath(cwd: string, value: string): string | undefined {\n\ttry {\n\t\treturn safeRealpathSync(resolve(cwd, value));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction validateInitialUsage(usage: GatewayInitialUsage): void {\n\ttry {\n\t\tvalidateAttemptUsageSnapshot(usage, \"CapabilityGateway: initial usage\");\n\t} catch {\n\t\tthrow new Error(\n\t\t\t\"CapabilityGateway: initial usage must contain finite non-negative values and safe-integer counts.\",\n\t\t);\n\t}\n}\n\nfunction validatedUsageDelta(delta: GatewayUsageDelta): Required<GatewayUsageDelta> {\n\tconst inputTokens = delta.inputTokens === undefined ? 0 : delta.inputTokens;\n\tconst outputTokens = delta.outputTokens === undefined ? 0 : delta.outputTokens;\n\tconst cacheReadTokens = delta.cacheReadTokens === undefined ? 0 : delta.cacheReadTokens;\n\tconst cacheWriteTokens = delta.cacheWriteTokens === undefined ? 0 : delta.cacheWriteTokens;\n\tconst totalTokens =\n\t\tdelta.totalTokens === undefined\n\t\t\t? inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens\n\t\t\t: delta.totalTokens;\n\tconst costUsd = delta.costUsd === undefined ? 0 : delta.costUsd;\n\tif (\n\t\t!Number.isSafeInteger(inputTokens) ||\n\t\tinputTokens < 0 ||\n\t\t!Number.isSafeInteger(outputTokens) ||\n\t\toutputTokens < 0 ||\n\t\t!Number.isSafeInteger(cacheReadTokens) ||\n\t\tcacheReadTokens < 0 ||\n\t\t!Number.isSafeInteger(cacheWriteTokens) ||\n\t\tcacheWriteTokens < 0 ||\n\t\t!Number.isSafeInteger(totalTokens) ||\n\t\ttotalTokens < 0 ||\n\t\t!Number.isFinite(costUsd) ||\n\t\tcostUsd < 0\n\t) {\n\t\tthrow new Error(\n\t\t\t\"CapabilityGateway: usage delta must contain finite non-negative values and safe-integer token counts.\",\n\t\t);\n\t}\n\treturn { inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, totalTokens, costUsd };\n}\n\n/**\n * Per-invocation enforcement for an already-compiled grant. The compiler controls what may be\n * loaded; this gateway independently rechecks authority, path scope, expiry, and cumulative budget\n * immediately before execution.\n */\nexport class CapabilityGateway {\n\tprivate readonly grant: ExecutionGrant;\n\tprivate readonly cwd: string;\n\tprivate readonly now: () => number;\n\tprivate readonly onAudit?: (record: GatewayAuditRecord) => void;\n\tprivate readonly sharedBudget?: SharedCapabilityBudget;\n\tprivate readonly startedAt: number;\n\tprivate readonly initialWallClockMs: number;\n\tprivate toolCalls: number;\n\tprivate inputTokens: number;\n\tprivate outputTokens: number;\n\tprivate cacheReadTokens: number;\n\tprivate cacheWriteTokens: number;\n\tprivate totalTokens: number;\n\tprivate costUsd: number;\n\n\tconstructor(options: CapabilityGatewayOptions) {\n\t\tconst initialUsage: GatewayInitialUsage = options.initialUsage ?? {\n\t\t\ttoolCalls: 0,\n\t\t\tinputTokens: 0,\n\t\t\toutputTokens: 0,\n\t\t\tcacheReadTokens: 0,\n\t\t\tcacheWriteTokens: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcostUsd: 0,\n\t\t\tactiveWallClockMs: 0,\n\t\t};\n\t\tvalidateInitialUsage(initialUsage);\n\t\tthis.grant = options.grant;\n\t\tthis.cwd = options.cwd;\n\t\tthis.now = options.now ?? Date.now;\n\t\tthis.onAudit = options.onAudit;\n\t\tthis.sharedBudget = options.sharedBudget;\n\t\tthis.startedAt = this.currentTime();\n\t\tthis.initialWallClockMs = initialUsage.activeWallClockMs;\n\t\tthis.toolCalls = initialUsage.toolCalls;\n\t\tthis.inputTokens = initialUsage.inputTokens;\n\t\tthis.outputTokens = initialUsage.outputTokens;\n\t\tthis.cacheReadTokens = initialUsage.cacheReadTokens;\n\t\tthis.cacheWriteTokens = initialUsage.cacheWriteTokens;\n\t\tthis.totalTokens = initialUsage.totalTokens;\n\t\tthis.costUsd = initialUsage.costUsd;\n\t\tthis.sharedBudget?.recordAttemptUsage(this.getUsage());\n\t}\n\n\tasync execute<T>(\n\t\tmanifest: ToolCapabilityManifest,\n\t\ttoolName: string,\n\t\tparams: unknown,\n\t\tinvoke: () => Promise<T> | T,\n\t): Promise<T> {\n\t\tthis.authorizeToolCall(manifest, toolName, params);\n\t\treturn await invoke();\n\t}\n\n\t/** Immediate pre-execution authorization for runtimes that expose a before-tool-call hook. */\n\tauthorizeToolCall(manifest: ToolCapabilityManifest, toolName: string, params: unknown): void {\n\t\tconst now = this.currentTime();\n\t\tconst wallClockMs = this.wallClockMsAt(now);\n\t\tthis.authorize(manifest, toolName, params, now, wallClockMs);\n\t\tconst toolCalls = this.toolCalls + 1;\n\t\tif (!Number.isSafeInteger(toolCalls)) {\n\t\t\tthrow new Error(\"CapabilityGateway: tool-call count would exceed safe cumulative usage bounds.\");\n\t\t}\n\t\tthis.toolCalls = toolCalls;\n\t\tthis.sharedBudget?.recordAttemptUsage(this.getUsage());\n\t\tthis.audit(toolName, \"allow\", \"allowed\");\n\t}\n\n\trecordUsage(delta: GatewayUsageDelta): void {\n\t\tconst validated = validatedUsageDelta(delta);\n\t\tconst inputTokens = this.inputTokens + validated.inputTokens;\n\t\tconst outputTokens = this.outputTokens + validated.outputTokens;\n\t\tconst cacheReadTokens = this.cacheReadTokens + validated.cacheReadTokens;\n\t\tconst cacheWriteTokens = this.cacheWriteTokens + validated.cacheWriteTokens;\n\t\tconst totalTokens = this.totalTokens + validated.totalTokens;\n\t\tconst costUsd = this.costUsd + validated.costUsd;\n\t\tif (\n\t\t\t!Number.isSafeInteger(inputTokens) ||\n\t\t\t!Number.isSafeInteger(outputTokens) ||\n\t\t\t!Number.isSafeInteger(cacheReadTokens) ||\n\t\t\t!Number.isSafeInteger(cacheWriteTokens) ||\n\t\t\t!Number.isSafeInteger(totalTokens) ||\n\t\t\t!Number.isFinite(costUsd)\n\t\t) {\n\t\t\tthrow new Error(\"CapabilityGateway: usage delta would exceed safe cumulative usage bounds.\");\n\t\t}\n\t\tthis.inputTokens = inputTokens;\n\t\tthis.outputTokens = outputTokens;\n\t\tthis.cacheReadTokens = cacheReadTokens;\n\t\tthis.cacheWriteTokens = cacheWriteTokens;\n\t\tthis.totalTokens = totalTokens;\n\t\tthis.costUsd = costUsd;\n\t\tthis.sharedBudget?.recordAttemptUsage(this.getUsage());\n\t}\n\n\t/** Enforce resumed cumulative budgets before a provider request that has no tool-call boundary. */\n\tassertBudgetAvailable(subject = \"provider\"): void {\n\t\tthis.enforceBudget(subject, this.wallClockMsAt(this.currentTime()));\n\t\tthis.sharedBudget?.assertBudgetAvailable(subject);\n\t}\n\n\tasync reserveProviderBudget(\n\t\trequestedMaxTokens: number,\n\t\tsubject = \"provider\",\n\t\tsignal?: AbortSignal,\n\t): Promise<ProviderBudgetReservation> {\n\t\tif (!Number.isSafeInteger(requestedMaxTokens) || requestedMaxTokens <= 0) {\n\t\t\tthrow new Error(\"CapabilityGateway: provider token reservation must be a positive safe integer.\");\n\t\t}\n\t\tthis.assertBudgetAvailable(subject);\n\t\tconst localRemaining = this.remainingAttemptTokenBudget();\n\t\tconst maxTokens = Math.min(requestedMaxTokens, localRemaining ?? requestedMaxTokens);\n\t\tif (maxTokens <= 0) {\n\t\t\tthis.deny(subject, \"token_budget_exhausted\", \"Token budget exhausted.\");\n\t\t}\n\t\tif (this.sharedBudget) return this.sharedBudget.reserveProviderBudget(maxTokens, subject, signal);\n\t\tif (signal?.aborted) throw signal.reason;\n\t\treturn {\n\t\t\tmaxTokens,\n\t\t\trelease: () => undefined,\n\t\t};\n\t}\n\n\tremainingAttemptTokenBudget(): number | undefined {\n\t\tconst maximum = this.grant.budget.maxTokens;\n\t\treturn maximum === undefined ? undefined : Math.max(0, maximum - budgetedTokens(this.getUsage()));\n\t}\n\n\tremainingTokenBudget(): number | undefined {\n\t\tconst localRemaining = this.remainingAttemptTokenBudget();\n\t\tconst sharedRemaining = this.sharedBudget?.remainingTokens();\n\t\tif (localRemaining === undefined) return sharedRemaining;\n\t\tif (sharedRemaining === undefined) return localRemaining;\n\t\treturn Math.min(localRemaining, sharedRemaining);\n\t}\n\n\tgetUsage(): GatewayUsageSnapshot {\n\t\treturn {\n\t\t\ttoolCalls: this.toolCalls,\n\t\t\tinputTokens: this.inputTokens,\n\t\t\toutputTokens: this.outputTokens,\n\t\t\tcacheReadTokens: this.cacheReadTokens,\n\t\t\tcacheWriteTokens: this.cacheWriteTokens,\n\t\t\ttotalTokens: this.totalTokens,\n\t\t\tcostUsd: this.costUsd,\n\t\t\twallClockMs: this.wallClockMsAt(this.currentTime()),\n\t\t};\n\t}\n\n\tprivate authorize(\n\t\tmanifest: ToolCapabilityManifest,\n\t\ttoolName: string,\n\t\tparams: unknown,\n\t\tnow: number,\n\t\twallClockMs: number,\n\t): void {\n\t\tif (this.grant.expiresAt && Date.parse(this.grant.expiresAt) <= now) {\n\t\t\tthis.deny(toolName, \"grant_expired\", `Execution grant '${this.grant.grantId}' expired.`);\n\t\t}\n\t\tif (!this.grant.allowedTools.includes(toolName)) {\n\t\t\tthis.deny(toolName, \"tool_not_granted\", `Tool '${toolName}' is not in grant '${this.grant.grantId}'.`);\n\t\t}\n\t\tif (manifest.toolName !== toolName) {\n\t\t\tthis.deny(toolName, \"manifest_name_mismatch\", `Tool '${toolName}' does not match its capability manifest.`);\n\t\t}\n\t\tif (!manifest.capabilities.every((capability) => this.grant.capabilities.includes(capability))) {\n\t\t\tthis.deny(toolName, \"capability_not_granted\", `Tool '${toolName}' requires an ungranted capability.`);\n\t\t}\n\t\tconst callCapabilities = getToolCapabilityPolicy(toolName)\n\t\t\t? resolveToolCallCapabilities(manifest.capabilities, toolName, params)\n\t\t\t: manifest.capabilities;\n\t\tif (!callCapabilities) {\n\t\t\tthis.deny(\n\t\t\t\ttoolName,\n\t\t\t\t\"capability_not_granted\",\n\t\t\t\t`Tool '${toolName}' action requires a capability outside its compiled manifest.`,\n\t\t\t);\n\t\t}\n\t\tthis.enforceBudget(toolName, wallClockMs);\n\t\tthis.sharedBudget?.assertBudgetAvailable(toolName);\n\n\t\tconst canonicalPolicy = getToolCapabilityPolicy(toolName);\n\t\tconst hasDeclaredPathScope = manifest.enforcements.includes(\"path-scope\");\n\t\tconst pathAccess = canonicalPolicy\n\t\t\t? resolveToolCallPathAccess(manifest.capabilities, toolName, params)\n\t\t\t: hasDeclaredPathScope\n\t\t\t\t? (resolveCapabilityPathAccess(callCapabilities) ?? \"none\")\n\t\t\t\t: \"none\";\n\t\tconst paths = pathAccess === \"none\" ? [] : extractToolPathArguments(toolName, params);\n\t\tif (\n\t\t\tpathAccess !== \"none\" &&\n\t\t\t(callCapabilities.some((capability) => PATH_CAPABILITIES.has(capability)) || paths.length > 0)\n\t\t) {\n\t\t\tconst isWrite =\n\t\t\t\tpathAccess === \"write\" || callCapabilities.some((capability) => WRITE_CAPABILITIES.has(capability));\n\t\t\tconst allowedPaths = isWrite ? this.grant.writePaths : this.grant.readPaths;\n\t\t\tif (paths.length === 0) {\n\t\t\t\tthis.deny(toolName, \"path_argument_required\", `Tool '${toolName}' requires an explicit path argument.`);\n\t\t\t}\n\t\t\tfor (const rawPath of paths) {\n\t\t\t\tif (!this.pathAllowed(rawPath, allowedPaths)) {\n\t\t\t\t\tconst reasonCode = isWrite ? \"scope_denied\" : \"path_outside_scope\";\n\t\t\t\t\tthis.deny(toolName, reasonCode, `Path '${rawPath}' is outside grant '${this.grant.grantId}'.`);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate enforceBudget(toolName: string, wallClockMs: number): void {\n\t\tconst budget = this.grant.budget;\n\t\tif (budget.maxToolCalls !== undefined && this.toolCalls >= budget.maxToolCalls) {\n\t\t\tthis.deny(toolName, \"tool_call_budget_exhausted\", \"Tool-call budget exhausted.\");\n\t\t}\n\t\tif (budget.maxTokens !== undefined && budgetedTokens(this.getUsage()) >= budget.maxTokens) {\n\t\t\tthis.deny(toolName, \"token_budget_exhausted\", \"Token budget exhausted.\");\n\t\t}\n\t\tif (budget.maxCostUsd !== undefined && this.costUsd >= budget.maxCostUsd) {\n\t\t\tthis.deny(toolName, \"cost_budget_exhausted\", \"Cost budget exhausted.\");\n\t\t}\n\t\tif (budget.maxWallClockMs !== undefined && wallClockMs >= budget.maxWallClockMs) {\n\t\t\tthis.deny(toolName, \"wall_clock_budget_exhausted\", \"Wall-clock budget exhausted.\");\n\t\t}\n\t}\n\n\tprivate currentTime(): number {\n\t\tconst now = this.now();\n\t\tif (!Number.isFinite(now)) {\n\t\t\tthrow new Error(\"CapabilityGateway: clock source must return a finite time.\");\n\t\t}\n\t\treturn now;\n\t}\n\n\tprivate wallClockMsAt(now: number): number {\n\t\tconst elapsed = now - this.startedAt;\n\t\tif (!Number.isFinite(elapsed)) {\n\t\t\tthrow new Error(\"CapabilityGateway: active wall-clock elapsed time must be finite.\");\n\t\t}\n\t\tconst wallClockMs = this.initialWallClockMs + Math.max(0, elapsed);\n\t\tif (!Number.isFinite(wallClockMs) || wallClockMs < 0) {\n\t\t\tthrow new Error(\"CapabilityGateway: accumulated wall-clock usage must be finite and non-negative.\");\n\t\t}\n\t\treturn wallClockMs;\n\t}\n\n\tprivate pathAllowed(rawPath: string, allowedPaths: readonly string[]): boolean {\n\t\tif (allowedPaths.length === 0) return false;\n\t\tconst lexicalTarget = resolve(this.cwd, rawPath);\n\t\tconst allowedRoots = allowedPaths.flatMap((allowed) => {\n\t\t\tconst lexicalRoot = resolve(this.cwd, allowed);\n\t\t\tconst realRoot = resolveRealPath(this.cwd, allowed);\n\t\t\treturn realRoot ? [lexicalRoot, realRoot] : [lexicalRoot];\n\t\t});\n\t\tif (!allowedRoots.some((root) => isPathWithinScope(lexicalTarget, root))) {\n\t\t\treturn false;\n\t\t}\n\t\tconst target = resolveRealPath(this.cwd, rawPath);\n\t\tif (!target) return false;\n\t\tfor (const denied of this.grant.deniedPaths) {\n\t\t\tconst root = resolveRealPath(this.cwd, denied);\n\t\t\tif (root && isPathWithinScope(target, root)) return false;\n\t\t}\n\t\treturn allowedRoots.some((root) => isPathWithinScope(target, root));\n\t}\n\n\tprivate deny(toolName: string, reasonCode: GatewayDecisionCode, message: string): never {\n\t\tthis.audit(toolName, \"deny\", reasonCode);\n\t\tthrow new CapabilityGatewayDeniedError(reasonCode, message);\n\t}\n\n\tprivate audit(toolName: string, outcome: \"allow\" | \"deny\", reasonCode: GatewayDecisionCode): void {\n\t\tthis.onAudit?.({\n\t\t\tgrantId: this.grant.grantId,\n\t\t\tattemptId: this.grant.attemptId,\n\t\t\ttoolName,\n\t\t\toutcome,\n\t\t\treasonCode,\n\t\t\tat: new Date(this.currentTime()).toISOString(),\n\t\t});\n\t}\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { mapToolNamesForPlatform } from "../default-tool-surface.js";
|
|
2
|
-
import { getToolCapabilityPolicy,
|
|
2
|
+
import { getToolCapabilityPolicy, resolveProfileToolCapabilities } from "../tool-capability-policy.js";
|
|
3
3
|
export const CLASSIFIED_LANE_TOOL_NAMES = [
|
|
4
4
|
"read",
|
|
5
5
|
"grep",
|
|
@@ -24,15 +24,15 @@ export function buildLaneToolManifests(profile, enabledToolNames) {
|
|
|
24
24
|
if (!enabled.has(toolName))
|
|
25
25
|
continue;
|
|
26
26
|
const policy = getToolCapabilityPolicy(toolName);
|
|
27
|
-
const
|
|
28
|
-
if (!
|
|
27
|
+
const capabilities = resolveProfileToolCapabilities(profile, toolName);
|
|
28
|
+
if (!capabilities || !policy)
|
|
29
29
|
continue;
|
|
30
30
|
manifests.push({
|
|
31
31
|
toolName,
|
|
32
32
|
moduleSpecifier: `../tools/${toolName}.ts`,
|
|
33
|
-
capabilities
|
|
33
|
+
capabilities,
|
|
34
34
|
roles: [profile.role],
|
|
35
|
-
enforcements:
|
|
35
|
+
enforcements: policy.enforcements,
|
|
36
36
|
});
|
|
37
37
|
}
|
|
38
38
|
return manifests;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lane-tool-manifests.js","sourceRoot":"","sources":["../../../src/core/orchestration/lane-tool-manifests.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,
|
|
1
|
+
{"version":3,"file":"lane-tool-manifests.js","sourceRoot":"","sources":["../../../src/core/orchestration/lane-tool-manifests.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AACrE,OAAO,EAAE,uBAAuB,EAAE,8BAA8B,EAAE,MAAM,8BAA8B,CAAC;AAGvG,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACzC,MAAM;IACN,MAAM;IACN,MAAM;IACN,IAAI;IACJ,OAAO;IACP,MAAM;IACN,QAAQ;IACR,QAAQ;IACR,aAAa;IACb,MAAM;CACG,CAAC;AACX,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,GAAG,0BAA0B,EAAE,UAAU,CAAU,CAAC;AAErG;;;GAGG;AACH,MAAM,UAAU,sBAAsB,CACrC,OAA6B,EAC7B,gBAAmC;IAEnC,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,gBAAgB,CAAC,CAAC;IAC1C,MAAM,SAAS,GAA6B,EAAE,CAAC;IAE/C,KAAK,MAAM,QAAQ,IAAI,IAAI,GAAG,CAAC,uBAAuB,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,EAAE,CAAC;QAC5E,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;YAAE,SAAS;QACrC,MAAM,MAAM,GAAG,uBAAuB,CAAC,QAAQ,CAAC,CAAC;QACjD,MAAM,YAAY,GAAG,8BAA8B,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QACvE,IAAI,CAAC,YAAY,IAAI,CAAC,MAAM;YAAE,SAAS;QACvC,SAAS,CAAC,IAAI,CAAC;YACd,QAAQ;YACR,eAAe,EAAE,YAAY,QAAQ,KAAK;YAC1C,YAAY;YACZ,KAAK,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC;YACrB,YAAY,EAAE,MAAM,CAAC,YAAY;SACjC,CAAC,CAAC;IACJ,CAAC;IACD,OAAO,SAAS,CAAC;AAClB,CAAC","sourcesContent":["import { mapToolNamesForPlatform } from \"../default-tool-surface.ts\";\nimport { getToolCapabilityPolicy, resolveProfileToolCapabilities } from \"../tool-capability-policy.ts\";\nimport type { OrchestrationProfile, ToolCapabilityManifest } from \"./contracts.ts\";\n\nexport const CLASSIFIED_LANE_TOOL_NAMES = [\n\t\"read\",\n\t\"grep\",\n\t\"find\",\n\t\"ls\",\n\t\"write\",\n\t\"edit\",\n\t\"memory\",\n\t\"python\",\n\t\"run_process\",\n\t\"bash\",\n] as const;\nexport const ORCHESTRATION_PROFILE_TOOL_NAMES = [...CLASSIFIED_LANE_TOOL_NAMES, \"delegate\"] as const;\n\n/**\n * Manifest-only lane catalogue. It contains no tool factories, so policy compilation can omit\n * denied tools before their executable implementations are constructed.\n */\nexport function buildLaneToolManifests(\n\tprofile: OrchestrationProfile,\n\tenabledToolNames: readonly string[],\n): ToolCapabilityManifest[] {\n\tconst enabled = new Set(enabledToolNames);\n\tconst manifests: ToolCapabilityManifest[] = [];\n\n\tfor (const toolName of new Set(mapToolNamesForPlatform(profile.toolNames))) {\n\t\tif (!enabled.has(toolName)) continue;\n\t\tconst policy = getToolCapabilityPolicy(toolName);\n\t\tconst capabilities = resolveProfileToolCapabilities(profile, toolName);\n\t\tif (!capabilities || !policy) continue;\n\t\tmanifests.push({\n\t\t\ttoolName,\n\t\t\tmoduleSpecifier: `../tools/${toolName}.ts`,\n\t\t\tcapabilities,\n\t\t\troles: [profile.role],\n\t\t\tenforcements: policy.enforcements,\n\t\t});\n\t}\n\treturn manifests;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"policy-compiler.d.ts","sourceRoot":"","sources":["../../../src/core/orchestration/policy-compiler.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"policy-compiler.d.ts","sourceRoot":"","sources":["../../../src/core/orchestration/policy-compiler.ts"],"names":[],"mappings":"AAEA,OAAO,EACN,KAAK,uBAAuB,EAC5B,KAAK,kBAAkB,EACvB,KAAK,cAAc,EAEnB,KAAK,iBAAiB,EAEtB,KAAK,eAAe,EACpB,KAAK,UAAU,EACf,KAAK,sBAAsB,EAC3B,KAAK,UAAU,EACf,MAAM,gBAAgB,CAAC;AAGxB,eAAO,MAAM,gCAAgC,EAAE,QAAQ,CAAC,MAAM,CAAC,UAAU,EAAE,SAAS,iBAAiB,EAAE,CAAC,CAQvG,CAAC;AAEF,MAAM,WAAW,0BAA0B;IAC1C,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,UAAU,CAAC;IACjB,oBAAoB,EAAE,SAAS,iBAAiB,EAAE,CAAC;IACnD,qBAAqB,CAAC,EAAE,SAAS,iBAAiB,EAAE,CAAC;IACrD,qBAAqB,EAAE,SAAS,iBAAiB,EAAE,CAAC;IACpD,cAAc,EAAE,SAAS,MAAM,EAAE,CAAC;IAClC,aAAa,EAAE,SAAS,sBAAsB,EAAE,CAAC;IACjD,SAAS,CAAC,EAAE,SAAS,eAAe,EAAE,CAAC;IACvC,SAAS,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9B,UAAU,CAAC,EAAE,SAAS,MAAM,EAA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ability-policy.js";
|
|
2
3
|
import { HARNESS_CAPABILITIES, ORCHESTRATION_SCHEMA_VERSION, } from "./contracts.js";
|
|
3
4
|
import { exceededRiskBudgetFields, intersectRiskBudgets, validateRiskBudget } from "./risk-budget.js";
|
|
4
5
|
export const DEFAULT_ROLE_CAPABILITY_CEILINGS = {
|
|
@@ -140,6 +141,12 @@ export class ExecutionPolicyCompiler {
|
|
|
140
141
|
toolReasonCodes.push(`tool_capability_denied:${toolName}`);
|
|
141
142
|
continue;
|
|
142
143
|
}
|
|
144
|
+
const canonicalPolicy = getToolCapabilityPolicy(toolName);
|
|
145
|
+
if (canonicalPolicy &&
|
|
146
|
+
!canonicalPolicy.enforcements.every((enforcement) => manifest.enforcements.includes(enforcement))) {
|
|
147
|
+
toolReasonCodes.push(`tool_enforcement_missing:${toolName}`);
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
143
150
|
if (!manifest.capabilities.every((capability) => {
|
|
144
151
|
const enforcement = CAPABILITY_ENFORCEMENT.get(capability);
|
|
145
152
|
return enforcement !== undefined && manifest.enforcements.includes(enforcement);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"policy-compiler.js","sourceRoot":"","sources":["../../../src/core/orchestration/policy-compiler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAIN,oBAAoB,EAEpB,4BAA4B,GAK5B,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAEtG,MAAM,CAAC,MAAM,gCAAgC,GAA+D;IAC3G,YAAY,EAAE,oBAAoB;IAClC,OAAO,EAAE,oBAAoB;IAC7B,QAAQ,EAAE,oBAAoB;IAC9B,WAAW,EAAE,oBAAoB;IACjC,QAAQ,EAAE,oBAAoB;IAC9B,QAAQ,EAAE,oBAAoB;IAC9B,QAAQ,EAAE,oBAAoB;CAC9B,C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Contract,\n\ttype CapabilityDecision,\n\ttype ExecutionGrant,\n\tHARNESS_CAPABILITIES,\n\ttype HarnessCapability,\n\tORCHESTRATION_SCHEMA_VERSION,\n\ttype ResourcePointer,\n\ttype RiskBudget,\n\ttype ToolCapabilityManifest,\n\ttype WorkerRole,\n} from \"./contracts.ts\";\nimport { exceededRiskBudgetFields, intersectRiskBudgets, validateRiskBudget } from \"./risk-budget.ts\";\n\nexport const DEFAULT_ROLE_CAPABILITY_CEILINGS: Readonly<Record<WorkerRole, readonly HarnessCapability[]>> = {\n\torchestrator: HARNESS_CAPABILITIES,\n\tplanner: HARNESS_CAPABILITIES,\n\texplorer: HARNESS_CAPABILITIES,\n\timplementer: HARNESS_CAPABILITIES,\n\toperator: HARNESS_CAPABILITIES,\n\tverifier: HARNESS_CAPABILITIES,\n\tdatabase: HARNESS_CAPABILITIES,\n};\n\nexport interface CompileExecutionGrantInput {\n\tobjectiveId: string;\n\ttaskId: string;\n\tattemptId: string;\n\tsubjectId: string;\n\trole: WorkerRole;\n\trequiredCapabilities: readonly HarnessCapability[];\n\trequestedCapabilities?: readonly HarnessCapability[];\n\tauthorityCapabilities: readonly HarnessCapability[];\n\trequestedTools: readonly string[];\n\ttoolManifests: readonly ToolCapabilityManifest[];\n\tresources?: readonly ResourcePointer[];\n\treadPaths?: readonly string[];\n\twritePaths?: readonly string[];\n\tdeniedPaths?: readonly string[];\n\trequestedBudget?: RiskBudget;\n\tauthorityBudget?: RiskBudget;\n\tpolicyVersion: string;\n\texpiresAt?: string;\n}\n\nexport type PolicyCompilationResult =\n\t| { outcome: \"allow\"; grant: ExecutionGrant; toolManifests: readonly ToolCapabilityManifest[] }\n\t| {\n\t\t\toutcome: \"approval-required\";\n\t\t\tapproval: ApprovalRequestContract;\n\t\t\tdecisions: readonly CapabilityDecision[];\n\t\t\treasonCodes: readonly string[];\n\t }\n\t| { outcome: \"deny\"; decisions: readonly CapabilityDecision[]; reasonCodes: readonly string[] };\n\nexport interface PolicyCompilerOptions {\n\tnow?: () => string;\n\tcreateId?: () => string;\n\troleCapabilityCeilings?: Readonly<Record<WorkerRole, readonly HarnessCapability[]>>;\n}\n\nfunction unique<T>(values: readonly T[]): T[] {\n\treturn [...new Set(values)];\n}\n\nfunction freezeGrant(grant: ExecutionGrant): ExecutionGrant {\n\tfor (const resource of grant.resources) {\n\t\tif (resource.metadata) Object.freeze(resource.metadata);\n\t\tObject.freeze(resource);\n\t}\n\tfor (const decision of grant.decisionTrace) Object.freeze(decision);\n\tObject.freeze(grant.capabilities);\n\tObject.freeze(grant.allowedTools);\n\tObject.freeze(grant.resources);\n\tObject.freeze(grant.readPaths);\n\tObject.freeze(grant.writePaths);\n\tObject.freeze(grant.deniedPaths);\n\tObject.freeze(grant.budget);\n\tObject.freeze(grant.decisionTrace);\n\treturn Object.freeze(grant);\n}\n\nconst CAPABILITY_ENFORCEMENT = new Map<HarnessCapability, ToolCapabilityManifest[\"enforcements\"][number]>([\n\t[\"filesystem.read\", \"path-scope\"],\n\t[\"filesystem.write\", \"path-scope\"],\n\t[\"worktree.read\", \"path-scope\"],\n\t[\"worktree.mutate\", \"path-scope\"],\n\t[\"process.exec\", \"process-launcher\"],\n\t[\"tests.execute\", \"process-launcher\"],\n\t[\"network.http\", \"service-proxy\"],\n\t[\"service.mcp\", \"service-proxy\"],\n\t[\"credentials.use\", \"service-proxy\"],\n\t[\"memory.query\", \"memory-broker\"],\n\t[\"memory.mutate\", \"memory-broker\"],\n\t[\"settings.read\", \"control-plane\"],\n\t[\"settings.write\", \"control-plane\"],\n\t[\"skill.read\", \"path-scope\"],\n\t[\"skill.write\", \"path-scope\"],\n\t[\"source.read\", \"path-scope\"],\n\t[\"source.write\", \"path-scope\"],\n\t[\"research.execute\", \"control-plane\"],\n\t[\"workflow.plan\", \"control-plane\"],\n\t[\"workflow.delegate\", \"control-plane\"],\n\t[\"policy.modify\", \"control-plane\"],\n\t[\"learning.propose\", \"control-plane\"],\n\t[\"publish.execute\", \"control-plane\"],\n]);\n\nexport class ExecutionPolicyCompiler {\n\tprivate readonly now: () => string;\n\tprivate readonly createId: () => string;\n\tprivate readonly roleCapabilityCeilings: Readonly<Record<WorkerRole, readonly HarnessCapability[]>>;\n\n\tconstructor(options: PolicyCompilerOptions = {}) {\n\t\tthis.now = options.now ?? (() => new Date().toISOString());\n\t\tthis.createId = options.createId ?? randomUUID;\n\t\tthis.roleCapabilityCeilings = options.roleCapabilityCeilings ?? DEFAULT_ROLE_CAPABILITY_CEILINGS;\n\t}\n\n\tcompile(input: CompileExecutionGrantInput): PolicyCompilationResult {\n\t\tconst required = unique(input.requiredCapabilities);\n\t\tconst requested = unique([...(input.requestedCapabilities ?? required), ...required]);\n\t\tconst authority = new Set(input.authorityCapabilities);\n\t\tconst roleCeiling = new Set(this.roleCapabilityCeilings[input.role]);\n\t\tconst decisions: CapabilityDecision[] = [];\n\t\tconst roleDenied: HarnessCapability[] = [];\n\t\tconst approvalCapabilities: HarnessCapability[] = [];\n\t\tconst granted: HarnessCapability[] = [];\n\n\t\tfor (const capability of requested) {\n\t\t\tif (!roleCeiling.has(capability)) {\n\t\t\t\troleDenied.push(capability);\n\t\t\t\tdecisions.push({ capability, outcome: \"deny\", reasonCode: \"role_ceiling_denied\", source: input.role });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!authority.has(capability)) {\n\t\t\t\tapprovalCapabilities.push(capability);\n\t\t\t\tdecisions.push({\n\t\t\t\t\tcapability,\n\t\t\t\t\toutcome: \"deny\",\n\t\t\t\t\treasonCode: \"owner_authority_required\",\n\t\t\t\t\tsource: \"authority\",\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tgranted.push(capability);\n\t\t\tdecisions.push({ capability, outcome: \"allow\", reasonCode: \"role_and_authority_allowed\", source: input.role });\n\t\t}\n\n\t\tif (roleDenied.some((capability) => required.includes(capability))) {\n\t\t\treturn { outcome: \"deny\", decisions, reasonCodes: [\"required_capability_exceeds_role_ceiling\"] };\n\t\t}\n\n\t\tconst requestedBudget = { ...(input.requestedBudget ?? {}) };\n\t\tconst authorityBudget = { ...(input.authorityBudget ?? {}) };\n\t\tvalidateRiskBudget(requestedBudget, \"requestedBudget\");\n\t\tvalidateRiskBudget(authorityBudget, \"authorityBudget\");\n\t\tconst exceededBudgetFields = exceededRiskBudgetFields(requestedBudget, authorityBudget);\n\t\tif (approvalCapabilities.some((capability) => required.includes(capability)) || exceededBudgetFields.length > 0) {\n\t\t\tconst approval: ApprovalRequestContract = {\n\t\t\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\t\t\tapprovalId: `approval-${this.createId()}`,\n\t\t\t\tobjectiveId: input.objectiveId,\n\t\t\t\ttaskId: input.taskId,\n\t\t\t\tattemptId: input.attemptId,\n\t\t\t\treasonCode:\n\t\t\t\t\texceededBudgetFields.length > 0\n\t\t\t\t\t\t? \"requested_budget_exceeds_authority\"\n\t\t\t\t\t\t: \"required_capability_needs_authority\",\n\t\t\t\tsummary:\n\t\t\t\t\texceededBudgetFields.length > 0\n\t\t\t\t\t\t? `Requested budget exceeds authority for: ${exceededBudgetFields.join(\", \")}.`\n\t\t\t\t\t\t: `Required capabilities need owner authority: ${approvalCapabilities.join(\", \")}.`,\n\t\t\t\trequestedCapabilities: approvalCapabilities,\n\t\t\t\t...(Object.keys(requestedBudget).length > 0 ? { requestedBudget } : {}),\n\t\t\t\treversible: true,\n\t\t\t\tcreatedAt: this.now(),\n\t\t\t};\n\t\t\treturn {\n\t\t\t\toutcome: \"approval-required\",\n\t\t\t\tapproval,\n\t\t\t\tdecisions,\n\t\t\t\treasonCodes: [approval.reasonCode],\n\t\t\t};\n\t\t}\n\n\t\tconst manifestsByName = new Map(input.toolManifests.map((manifest) => [manifest.toolName, manifest]));\n\t\tconst allowedManifests: ToolCapabilityManifest[] = [];\n\t\tconst toolReasonCodes: string[] = [];\n\t\tfor (const toolName of unique(input.requestedTools)) {\n\t\t\tconst manifest = manifestsByName.get(toolName);\n\t\t\tif (!manifest) {\n\t\t\t\ttoolReasonCodes.push(`unknown_tool:${toolName}`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!manifest.roles.includes(input.role)) {\n\t\t\t\ttoolReasonCodes.push(`tool_role_denied:${toolName}`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!manifest.capabilities.every((capability) => granted.includes(capability))) {\n\t\t\t\ttoolReasonCodes.push(`tool_capability_denied:${toolName}`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\t!manifest.capabilities.every((capability) => {\n\t\t\t\t\tconst enforcement = CAPABILITY_ENFORCEMENT.get(capability);\n\t\t\t\t\treturn enforcement !== undefined && manifest.enforcements.includes(enforcement);\n\t\t\t\t})\n\t\t\t) {\n\t\t\t\ttoolReasonCodes.push(`tool_enforcement_missing:${toolName}`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tallowedManifests.push(structuredClone(manifest));\n\t\t}\n\n\t\tif (toolReasonCodes.length > 0) {\n\t\t\treturn { outcome: \"deny\", decisions, reasonCodes: toolReasonCodes };\n\t\t}\n\n\t\tconst readPaths = unique(input.readPaths ?? []);\n\t\tconst writePaths = unique(input.writePaths ?? []);\n\t\tconst deniedPaths = unique(input.deniedPaths ?? []);\n\t\tif ((granted.includes(\"filesystem.read\") || granted.includes(\"worktree.read\")) && readPaths.length === 0) {\n\t\t\treturn { outcome: \"deny\", decisions, reasonCodes: [\"read_capability_missing_positive_path_scope\"] };\n\t\t}\n\t\tif ((granted.includes(\"filesystem.write\") || granted.includes(\"worktree.mutate\")) && writePaths.length === 0) {\n\t\t\treturn { outcome: \"deny\", decisions, reasonCodes: [\"write_capability_missing_positive_path_scope\"] };\n\t\t}\n\n\t\tconst grant = freezeGrant({\n\t\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\t\tgrantId: `grant-${this.createId()}`,\n\t\t\tobjectiveId: input.objectiveId,\n\t\t\ttaskId: input.taskId,\n\t\t\tattemptId: input.attemptId,\n\t\t\tsubjectId: input.subjectId,\n\t\t\trole: input.role,\n\t\t\tcapabilities: granted,\n\t\t\tallowedTools: allowedManifests.map((manifest) => manifest.toolName),\n\t\t\tresources: structuredClone(input.resources ?? []),\n\t\t\treadPaths,\n\t\t\twritePaths,\n\t\t\tdeniedPaths,\n\t\t\tbudget: intersectRiskBudgets(requestedBudget, authorityBudget),\n\t\t\tpolicyVersion: input.policyVersion,\n\t\t\tdecisionTrace: decisions,\n\t\t\tissuedAt: this.now(),\n\t\t\t...(input.expiresAt ? { expiresAt: input.expiresAt } : {}),\n\t\t});\n\t\treturn { outcome: \"allow\", grant, toolManifests: allowedManifests };\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"policy-compiler.js","sourceRoot":"","sources":["../../../src/core/orchestration/policy-compiler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,OAAO,EAIN,oBAAoB,EAEpB,4BAA4B,GAK5B,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAEtG,MAAM,CAAC,MAAM,gCAAgC,GAA+D;IAC3G,YAAY,EAAE,oBAAoB;IAClC,OAAO,EAAE,oBAAoB;IAC7B,QAAQ,EAAE,oBAAoB;IAC9B,WAAW,EAAE,oBAAoB;IACjC,QAAQ,EAAE,oBAAoB;IAC9B,QAAQ,EAAE,oBAAoB;IAC9B,QAAQ,EAAE,oBAAoB;CAC9B,CAAC;AAuCF,SAAS,MAAM,CAAI,MAAoB;IACtC,OAAO,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;AAC7B,CAAC;AAED,SAAS,WAAW,CAAC,KAAqB;IACzC,KAAK,MAAM,QAAQ,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;QACxC,I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AE,gBAAgB,EAAE,CAAC;IACrE,CAAC;CACD","sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { getToolCapabilityPolicy } from \"../tool-capability-policy.ts\";\nimport {\n\ttype ApprovalRequestContract,\n\ttype CapabilityDecision,\n\ttype ExecutionGrant,\n\tHARNESS_CAPABILITIES,\n\ttype HarnessCapability,\n\tORCHESTRATION_SCHEMA_VERSION,\n\ttype ResourcePointer,\n\ttype RiskBudget,\n\ttype ToolCapabilityManifest,\n\ttype WorkerRole,\n} from \"./contracts.ts\";\nimport { exceededRiskBudgetFields, intersectRiskBudgets, validateRiskBudget } from \"./risk-budget.ts\";\n\nexport const DEFAULT_ROLE_CAPABILITY_CEILINGS: Readonly<Record<WorkerRole, readonly HarnessCapability[]>> = {\n\torchestrator: HARNESS_CAPABILITIES,\n\tplanner: HARNESS_CAPABILITIES,\n\texplorer: HARNESS_CAPABILITIES,\n\timplementer: HARNESS_CAPABILITIES,\n\toperator: HARNESS_CAPABILITIES,\n\tverifier: HARNESS_CAPABILITIES,\n\tdatabase: HARNESS_CAPABILITIES,\n};\n\nexport interface CompileExecutionGrantInput {\n\tobjectiveId: string;\n\ttaskId: string;\n\tattemptId: string;\n\tsubjectId: string;\n\trole: WorkerRole;\n\trequiredCapabilities: readonly HarnessCapability[];\n\trequestedCapabilities?: readonly HarnessCapability[];\n\tauthorityCapabilities: readonly HarnessCapability[];\n\trequestedTools: readonly string[];\n\ttoolManifests: readonly ToolCapabilityManifest[];\n\tresources?: readonly ResourcePointer[];\n\treadPaths?: readonly string[];\n\twritePaths?: readonly string[];\n\tdeniedPaths?: readonly string[];\n\trequestedBudget?: RiskBudget;\n\tauthorityBudget?: RiskBudget;\n\tpolicyVersion: string;\n\texpiresAt?: string;\n}\n\nexport type PolicyCompilationResult =\n\t| { outcome: \"allow\"; grant: ExecutionGrant; toolManifests: readonly ToolCapabilityManifest[] }\n\t| {\n\t\t\toutcome: \"approval-required\";\n\t\t\tapproval: ApprovalRequestContract;\n\t\t\tdecisions: readonly CapabilityDecision[];\n\t\t\treasonCodes: readonly string[];\n\t }\n\t| { outcome: \"deny\"; decisions: readonly CapabilityDecision[]; reasonCodes: readonly string[] };\n\nexport interface PolicyCompilerOptions {\n\tnow?: () => string;\n\tcreateId?: () => string;\n\troleCapabilityCeilings?: Readonly<Record<WorkerRole, readonly HarnessCapability[]>>;\n}\n\nfunction unique<T>(values: readonly T[]): T[] {\n\treturn [...new Set(values)];\n}\n\nfunction freezeGrant(grant: ExecutionGrant): ExecutionGrant {\n\tfor (const resource of grant.resources) {\n\t\tif (resource.metadata) Object.freeze(resource.metadata);\n\t\tObject.freeze(resource);\n\t}\n\tfor (const decision of grant.decisionTrace) Object.freeze(decision);\n\tObject.freeze(grant.capabilities);\n\tObject.freeze(grant.allowedTools);\n\tObject.freeze(grant.resources);\n\tObject.freeze(grant.readPaths);\n\tObject.freeze(grant.writePaths);\n\tObject.freeze(grant.deniedPaths);\n\tObject.freeze(grant.budget);\n\tObject.freeze(grant.decisionTrace);\n\treturn Object.freeze(grant);\n}\n\nconst CAPABILITY_ENFORCEMENT = new Map<HarnessCapability, ToolCapabilityManifest[\"enforcements\"][number]>([\n\t[\"filesystem.read\", \"path-scope\"],\n\t[\"filesystem.write\", \"path-scope\"],\n\t[\"worktree.read\", \"path-scope\"],\n\t[\"worktree.mutate\", \"path-scope\"],\n\t[\"process.exec\", \"process-launcher\"],\n\t[\"tests.execute\", \"process-launcher\"],\n\t[\"network.http\", \"service-proxy\"],\n\t[\"service.mcp\", \"service-proxy\"],\n\t[\"credentials.use\", \"service-proxy\"],\n\t[\"memory.query\", \"memory-broker\"],\n\t[\"memory.mutate\", \"memory-broker\"],\n\t[\"settings.read\", \"control-plane\"],\n\t[\"settings.write\", \"control-plane\"],\n\t[\"skill.read\", \"path-scope\"],\n\t[\"skill.write\", \"path-scope\"],\n\t[\"source.read\", \"path-scope\"],\n\t[\"source.write\", \"path-scope\"],\n\t[\"research.execute\", \"control-plane\"],\n\t[\"workflow.plan\", \"control-plane\"],\n\t[\"workflow.delegate\", \"control-plane\"],\n\t[\"policy.modify\", \"control-plane\"],\n\t[\"learning.propose\", \"control-plane\"],\n\t[\"publish.execute\", \"control-plane\"],\n]);\n\nexport class ExecutionPolicyCompiler {\n\tprivate readonly now: () => string;\n\tprivate readonly createId: () => string;\n\tprivate readonly roleCapabilityCeilings: Readonly<Record<WorkerRole, readonly HarnessCapability[]>>;\n\n\tconstructor(options: PolicyCompilerOptions = {}) {\n\t\tthis.now = options.now ?? (() => new Date().toISOString());\n\t\tthis.createId = options.createId ?? randomUUID;\n\t\tthis.roleCapabilityCeilings = options.roleCapabilityCeilings ?? DEFAULT_ROLE_CAPABILITY_CEILINGS;\n\t}\n\n\tcompile(input: CompileExecutionGrantInput): PolicyCompilationResult {\n\t\tconst required = unique(input.requiredCapabilities);\n\t\tconst requested = unique([...(input.requestedCapabilities ?? required), ...required]);\n\t\tconst authority = new Set(input.authorityCapabilities);\n\t\tconst roleCeiling = new Set(this.roleCapabilityCeilings[input.role]);\n\t\tconst decisions: CapabilityDecision[] = [];\n\t\tconst roleDenied: HarnessCapability[] = [];\n\t\tconst approvalCapabilities: HarnessCapability[] = [];\n\t\tconst granted: HarnessCapability[] = [];\n\n\t\tfor (const capability of requested) {\n\t\t\tif (!roleCeiling.has(capability)) {\n\t\t\t\troleDenied.push(capability);\n\t\t\t\tdecisions.push({ capability, outcome: \"deny\", reasonCode: \"role_ceiling_denied\", source: input.role });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!authority.has(capability)) {\n\t\t\t\tapprovalCapabilities.push(capability);\n\t\t\t\tdecisions.push({\n\t\t\t\t\tcapability,\n\t\t\t\t\toutcome: \"deny\",\n\t\t\t\t\treasonCode: \"owner_authority_required\",\n\t\t\t\t\tsource: \"authority\",\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tgranted.push(capability);\n\t\t\tdecisions.push({ capability, outcome: \"allow\", reasonCode: \"role_and_authority_allowed\", source: input.role });\n\t\t}\n\n\t\tif (roleDenied.some((capability) => required.includes(capability))) {\n\t\t\treturn { outcome: \"deny\", decisions, reasonCodes: [\"required_capability_exceeds_role_ceiling\"] };\n\t\t}\n\n\t\tconst requestedBudget = { ...(input.requestedBudget ?? {}) };\n\t\tconst authorityBudget = { ...(input.authorityBudget ?? {}) };\n\t\tvalidateRiskBudget(requestedBudget, \"requestedBudget\");\n\t\tvalidateRiskBudget(authorityBudget, \"authorityBudget\");\n\t\tconst exceededBudgetFields = exceededRiskBudgetFields(requestedBudget, authorityBudget);\n\t\tif (approvalCapabilities.some((capability) => required.includes(capability)) || exceededBudgetFields.length > 0) {\n\t\t\tconst approval: ApprovalRequestContract = {\n\t\t\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\t\t\tapprovalId: `approval-${this.createId()}`,\n\t\t\t\tobjectiveId: input.objectiveId,\n\t\t\t\ttaskId: input.taskId,\n\t\t\t\tattemptId: input.attemptId,\n\t\t\t\treasonCode:\n\t\t\t\t\texceededBudgetFields.length > 0\n\t\t\t\t\t\t? \"requested_budget_exceeds_authority\"\n\t\t\t\t\t\t: \"required_capability_needs_authority\",\n\t\t\t\tsummary:\n\t\t\t\t\texceededBudgetFields.length > 0\n\t\t\t\t\t\t? `Requested budget exceeds authority for: ${exceededBudgetFields.join(\", \")}.`\n\t\t\t\t\t\t: `Required capabilities need owner authority: ${approvalCapabilities.join(\", \")}.`,\n\t\t\t\trequestedCapabilities: approvalCapabilities,\n\t\t\t\t...(Object.keys(requestedBudget).length > 0 ? { requestedBudget } : {}),\n\t\t\t\treversible: true,\n\t\t\t\tcreatedAt: this.now(),\n\t\t\t};\n\t\t\treturn {\n\t\t\t\toutcome: \"approval-required\",\n\t\t\t\tapproval,\n\t\t\t\tdecisions,\n\t\t\t\treasonCodes: [approval.reasonCode],\n\t\t\t};\n\t\t}\n\n\t\tconst manifestsByName = new Map(input.toolManifests.map((manifest) => [manifest.toolName, manifest]));\n\t\tconst allowedManifests: ToolCapabilityManifest[] = [];\n\t\tconst toolReasonCodes: string[] = [];\n\t\tfor (const toolName of unique(input.requestedTools)) {\n\t\t\tconst manifest = manifestsByName.get(toolName);\n\t\t\tif (!manifest) {\n\t\t\t\ttoolReasonCodes.push(`unknown_tool:${toolName}`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!manifest.roles.includes(input.role)) {\n\t\t\t\ttoolReasonCodes.push(`tool_role_denied:${toolName}`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!manifest.capabilities.every((capability) => granted.includes(capability))) {\n\t\t\t\ttoolReasonCodes.push(`tool_capability_denied:${toolName}`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst canonicalPolicy = getToolCapabilityPolicy(toolName);\n\t\t\tif (\n\t\t\t\tcanonicalPolicy &&\n\t\t\t\t!canonicalPolicy.enforcements.every((enforcement) => manifest.enforcements.includes(enforcement))\n\t\t\t) {\n\t\t\t\ttoolReasonCodes.push(`tool_enforcement_missing:${toolName}`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (\n\t\t\t\t!manifest.capabilities.every((capability) => {\n\t\t\t\t\tconst enforcement = CAPABILITY_ENFORCEMENT.get(capability);\n\t\t\t\t\treturn enforcement !== undefined && manifest.enforcements.includes(enforcement);\n\t\t\t\t})\n\t\t\t) {\n\t\t\t\ttoolReasonCodes.push(`tool_enforcement_missing:${toolName}`);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tallowedManifests.push(structuredClone(manifest));\n\t\t}\n\n\t\tif (toolReasonCodes.length > 0) {\n\t\t\treturn { outcome: \"deny\", decisions, reasonCodes: toolReasonCodes };\n\t\t}\n\n\t\tconst readPaths = unique(input.readPaths ?? []);\n\t\tconst writePaths = unique(input.writePaths ?? []);\n\t\tconst deniedPaths = unique(input.deniedPaths ?? []);\n\t\tif ((granted.includes(\"filesystem.read\") || granted.includes(\"worktree.read\")) && readPaths.length === 0) {\n\t\t\treturn { outcome: \"deny\", decisions, reasonCodes: [\"read_capability_missing_positive_path_scope\"] };\n\t\t}\n\t\tif ((granted.includes(\"filesystem.write\") || granted.includes(\"worktree.mutate\")) && writePaths.length === 0) {\n\t\t\treturn { outcome: \"deny\", decisions, reasonCodes: [\"write_capability_missing_positive_path_scope\"] };\n\t\t}\n\n\t\tconst grant = freezeGrant({\n\t\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\t\tgrantId: `grant-${this.createId()}`,\n\t\t\tobjectiveId: input.objectiveId,\n\t\t\ttaskId: input.taskId,\n\t\t\tattemptId: input.attemptId,\n\t\t\tsubjectId: input.subjectId,\n\t\t\trole: input.role,\n\t\t\tcapabilities: granted,\n\t\t\tallowedTools: allowedManifests.map((manifest) => manifest.toolName),\n\t\t\tresources: structuredClone(input.resources ?? []),\n\t\t\treadPaths,\n\t\t\twritePaths,\n\t\t\tdeniedPaths,\n\t\t\tbudget: intersectRiskBudgets(requestedBudget, authorityBudget),\n\t\t\tpolicyVersion: input.policyVersion,\n\t\t\tdecisionTrace: decisions,\n\t\t\tissuedAt: this.now(),\n\t\t\t...(input.expiresAt ? { expiresAt: input.expiresAt } : {}),\n\t\t});\n\t\treturn { outcome: \"allow\", grant, toolManifests: allowedManifests };\n\t}\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { describeToolCapabilityAuthority,
|
|
1
|
+
import { describeToolCapabilityAuthority, resolveProfileToolCapabilities } from "../tool-capability-policy.js";
|
|
2
2
|
import { hasOnlyKeys, isPlainRecord } from "../util/value-guards.js";
|
|
3
3
|
import { HARNESS_CAPABILITIES, MAX_ORCHESTRATION_AGENT_BINDINGS, MAX_ORCHESTRATION_AGENT_DEPTH, MAX_ORCHESTRATION_COLLECTION_LENGTH, MAX_ORCHESTRATION_DESCRIPTION_LENGTH, MAX_ORCHESTRATION_DIRECT_CHILDREN, MAX_ORCHESTRATION_DISPATCH_INSTRUCTIONS_LENGTH, MAX_ORCHESTRATION_IDENTIFIER_LENGTH, MAX_ORCHESTRATION_MODEL_ID_LENGTH, MAX_ORCHESTRATION_MODEL_PROVIDER_LENGTH, MAX_ORCHESTRATION_PROCESS_OUTPUT_BYTES, MAX_WORKER_AUTHORITY_PATH_LENGTH, ORCHESTRATION_SCHEMA_VERSION, ORCHESTRATION_THINKING_LEVELS, toJsonObject, WORKER_ROLES, } from "./contracts.js";
|
|
4
4
|
import { ORCHESTRATION_PROFILE_TOOL_NAMES } from "./lane-tool-manifests.js";
|
|
@@ -180,7 +180,7 @@ export function validateOrchestrationProfile(profile) {
|
|
|
180
180
|
throw new OrchestrationProfileError(`Profile '${profile.profileId}' contains unclassified orchestration tools: ${unknownTools.join(", ")}.`);
|
|
181
181
|
}
|
|
182
182
|
for (const toolName of profile.toolNames) {
|
|
183
|
-
if (!
|
|
183
|
+
if (!resolveProfileToolCapabilities(profile, toolName)) {
|
|
184
184
|
throw new OrchestrationProfileError(`Profile '${profile.profileId}' tool '${toolName}' lacks ${describeToolCapabilityAuthority(toolName)} authority.`);
|
|
185
185
|
}
|
|
186
186
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"profile-registry.js","sourceRoot":"","sources":["../../../src/core/orchestration/profile-registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,+BAA+B,EAAE,4BAA4B,EAAE,MAAM,8BAA8B,CAAC;AAC7G,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAWrE,OAAO,EACN,oBAAoB,EACpB,gCAAgC,EAChC,6BAA6B,EAC7B,mCAAmC,EACnC,oCAAoC,EACpC,iCAAiC,EACjC,8CAA8C,EAC9C,mCAAmC,EACnC,iCAAiC,EACjC,uCAAuC,EACvC,sCAAsC,EACtC,gCAAgC,EAChC,4BAA4B,EAC5B,6BAA6B,EAC7B,YAAY,EACZ,YAAY,GACZ,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,gCAAgC,EAAE,MAAM,0BAA0B,CAA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,QAAQ,CAAC;IAClD,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,aAAa,EAAE,QAAQ,CAAC,aAAa,EAAE,EAAE,CAAC;AACrH,CAAC","sourcesContent":["import { describeToolCapabilityAuthority, resolveProfileToolCapability } from \"../tool-capability-policy.ts\";\nimport { hasOnlyKeys, isPlainRecord } from \"../util/value-guards.ts\";\nimport type {\n\tExecutionGrant,\n\tOrchestrationDispatchRequest,\n\tOrchestrationModelBinding,\n\tOrchestrationProfile,\n\tResourcePointer,\n\tRiskBudget,\n\tTaskContract,\n\tToolCapabilityManifest,\n} from \"./contracts.ts\";\nimport {\n\tHARNESS_CAPABILITIES,\n\tMAX_ORCHESTRATION_AGENT_BINDINGS,\n\tMAX_ORCHESTRATION_AGENT_DEPTH,\n\tMAX_ORCHESTRATION_COLLECTION_LENGTH,\n\tMAX_ORCHESTRATION_DESCRIPTION_LENGTH,\n\tMAX_ORCHESTRATION_DIRECT_CHILDREN,\n\tMAX_ORCHESTRATION_DISPATCH_INSTRUCTIONS_LENGTH,\n\tMAX_ORCHESTRATION_IDENTIFIER_LENGTH,\n\tMAX_ORCHESTRATION_MODEL_ID_LENGTH,\n\tMAX_ORCHESTRATION_MODEL_PROVIDER_LENGTH,\n\tMAX_ORCHESTRATION_PROCESS_OUTPUT_BYTES,\n\tMAX_WORKER_AUTHORITY_PATH_LENGTH,\n\tORCHESTRATION_SCHEMA_VERSION,\n\tORCHESTRATION_THINKING_LEVELS,\n\ttoJsonObject,\n\tWORKER_ROLES,\n} from \"./contracts.ts\";\nimport { ORCHESTRATION_PROFILE_TOOL_NAMES } from \"./lane-tool-manifests.ts\";\nimport {\n\ttype CompileExecutionGrantInput,\n\tDEFAULT_ROLE_CAPABILITY_CEILINGS,\n\ttype ExecutionPolicyCompiler,\n\ttype PolicyCompilationResult,\n} from \"./policy-compiler.ts\";\nimport { parseRiskBudget, validateRiskBudget } from \"./risk-budget.ts\";\n\nexport interface ModelHealthView {\n\tisHealthy(binding: OrchestrationModelBinding): boolean;\n}\n\nexport interface ProfileDispatchPlan {\n\tprofile: OrchestrationProfile;\n\tmodel: OrchestrationModelBinding;\n\tgrant: ExecutionGrant;\n\ttoolManifests: readonly ToolCapabilityManifest[];\n}\n\nexport type ProfileDispatchPlanResult =\n\t| { outcome: \"allow\"; plan: ProfileDispatchPlan }\n\t| Exclude<PolicyCompilationResult, { outcome: \"allow\" }>\n\t| { outcome: \"deny\"; decisions: readonly []; reasonCodes: readonly [\"profile_model_unavailable\"] };\n\nexport class OrchestrationProfileError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"OrchestrationProfileError\";\n\t}\n}\n\nfunction duplicateStrings(values: readonly string[]): string[] {\n\tconst seen = new Set<string>();\n\tconst duplicates = new Set<string>();\n\tfor (const value of values) {\n\t\tif (seen.has(value)) duplicates.add(value);\n\t\tseen.add(value);\n\t}\n\treturn [...duplicates];\n}\n\nexport function parseOrchestrationDispatchRequest(value: unknown): OrchestrationDispatchRequest {\n\tif (!isPlainRecord(value)) throw new OrchestrationProfileError(\"Dispatch request must be an object.\");\n\tif (!hasOnlyKeys(value, [\"taskId\", \"profileId\", \"instructions\", \"resourcePointerIds\"])) {\n\t\tthrow new OrchestrationProfileError(\"Dispatch request contains an unsupported durable metadata field.\");\n\t}\n\tif (\n\t\ttypeof value.taskId !== \"string\" ||\n\t\t!value.taskId ||\n\t\tvalue.taskId.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH ||\n\t\ttypeof value.profileId !== \"string\" ||\n\t\t!value.profileId ||\n\t\tvalue.profileId.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH ||\n\t\ttypeof value.instructions !== \"string\" ||\n\t\tvalue.instructions.length > MAX_ORCHESTRATION_DISPATCH_INSTRUCTIONS_LENGTH ||\n\t\t!value.instructions.trim() ||\n\t\t!Array.isArray(value.resourcePointerIds) ||\n\t\tvalue.resourcePointerIds.length > MAX_ORCHESTRATION_COLLECTION_LENGTH ||\n\t\t!value.resourcePointerIds.every(\n\t\t\t(entry) =>\n\t\t\t\ttypeof entry === \"string\" && entry.length > 0 && entry.length <= MAX_ORCHESTRATION_IDENTIFIER_LENGTH,\n\t\t) ||\n\t\tnew Set(value.resourcePointerIds).size !== value.resourcePointerIds.length\n\t) {\n\t\tthrow new OrchestrationProfileError(\"Dispatch request is invalid.\");\n\t}\n\treturn {\n\t\ttaskId: value.taskId,\n\t\tprofileId: value.profileId,\n\t\tinstructions: value.instructions.trim(),\n\t\tresourcePointerIds: [...value.resourcePointerIds],\n\t};\n}\n\nexport function validateOrchestrationProfile(profile: OrchestrationProfile): void {\n\tif (profile.schemaVersion !== ORCHESTRATION_SCHEMA_VERSION) {\n\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' has an unsupported schema version.`);\n\t}\n\tif (\n\t\tprofile.profileId.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH ||\n\t\t!profile.profileId.trim() ||\n\t\tprofile.description.length > MAX_ORCHESTRATION_DESCRIPTION_LENGTH ||\n\t\t!profile.description.trim()\n\t)\n\t\tthrow new OrchestrationProfileError(\"Profile id and description are required.\");\n\tif (profile.role !== \"orchestrator\" && profile.dispatchProfileIds.length > 0) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\t`Only orchestrator profiles may declare dispatchProfileIds ('${profile.profileId}').`,\n\t\t);\n\t}\n\tif (profile.dispatchProfileIds.includes(profile.profileId)) {\n\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' cannot dispatch itself.`);\n\t}\n\tif (profile.requireIndependentVerification) {\n\t\tif (profile.role === \"verifier\") {\n\t\t\tthrow new OrchestrationProfileError(\n\t\t\t\t`Verifier profile '${profile.profileId}' cannot require another verifier.`,\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\t!profile.verificationProfileId?.trim() ||\n\t\t\tprofile.verificationProfileId.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH\n\t\t) {\n\t\t\tthrow new OrchestrationProfileError(\n\t\t\t\t`Profile '${profile.profileId}' requires independent verification but has no verificationProfileId.`,\n\t\t\t);\n\t\t}\n\t} else if (profile.verificationProfileId !== undefined) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\t`Profile '${profile.profileId}' cannot declare verificationProfileId without requiring verification.`,\n\t\t);\n\t}\n\tif (profile.verificationProfileId === profile.profileId) {\n\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' cannot verify itself.`);\n\t}\n\tif (\n\t\t!profile.createdAt.trim() ||\n\t\tprofile.createdAt.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH ||\n\t\t!profile.updatedAt.trim() ||\n\t\tprofile.updatedAt.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH\n\t) {\n\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' timestamps are invalid.`);\n\t}\n\tfor (const [label, values] of [\n\t\t[\"capabilityCeiling\", profile.capabilityCeiling],\n\t\t[\"toolNames\", profile.toolNames],\n\t\t[\"resourceProfileNames\", profile.resourceProfileNames],\n\t\t[\"dispatchProfileIds\", profile.dispatchProfileIds],\n\t] as const) {\n\t\tif (\n\t\t\tvalues.length > MAX_ORCHESTRATION_COLLECTION_LENGTH ||\n\t\t\tvalues.some((value) => !value.trim() || value.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH)\n\t\t) {\n\t\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' contains an invalid ${label}.`);\n\t\t}\n\t\tconst duplicates = duplicateStrings(values);\n\t\tif (duplicates.length > 0) {\n\t\t\tthrow new OrchestrationProfileError(\n\t\t\t\t`Profile '${profile.profileId}' contains duplicate ${label}: ${duplicates.join(\", \")}.`,\n\t\t\t);\n\t\t}\n\t}\n\tconst roleCeiling = new Set(DEFAULT_ROLE_CAPABILITY_CEILINGS[profile.role]);\n\tconst outOfRoleCapabilities = profile.capabilityCeiling.filter((capability) => !roleCeiling.has(capability));\n\tif (outOfRoleCapabilities.length > 0) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\t`Profile '${profile.profileId}' exceeds the ${profile.role} role ceiling: ${outOfRoleCapabilities.join(\", \")}.`,\n\t\t);\n\t}\n\tif (\n\t\tprofile.modelPolicy.candidates.length === 0 ||\n\t\tprofile.modelPolicy.candidates.length > MAX_ORCHESTRATION_COLLECTION_LENGTH\n\t) {\n\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' must declare a model candidate.`);\n\t}\n\tif (profile.modelPolicy.mode === \"fixed\" && profile.modelPolicy.candidates.length !== 1) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\t`Fixed profile '${profile.profileId}' must declare exactly one model candidate.`,\n\t\t);\n\t}\n\tfor (const candidate of profile.modelPolicy.candidates) {\n\t\tif (\n\t\t\tcandidate.provider.length > MAX_ORCHESTRATION_MODEL_PROVIDER_LENGTH ||\n\t\t\t!candidate.provider.trim() ||\n\t\t\tcandidate.modelId.length > MAX_ORCHESTRATION_MODEL_ID_LENGTH ||\n\t\t\t!candidate.modelId.trim()\n\t\t) {\n\t\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' contains an invalid model binding.`);\n\t\t}\n\t}\n\tconst duplicateModels = duplicateStrings(\n\t\tprofile.modelPolicy.candidates.map((candidate) => `${candidate.provider}/${candidate.modelId}`),\n\t);\n\tif (duplicateModels.length > 0) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\t`Profile '${profile.profileId}' contains duplicate model candidates: ${duplicateModels.join(\", \")}.`,\n\t\t);\n\t}\n\tif (!Number.isSafeInteger(profile.maxConcurrent) || profile.maxConcurrent <= 0) {\n\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' maxConcurrent must be positive.`);\n\t}\n\tif (!Number.isSafeInteger(profile.leaseTtlMs) || profile.leaseTtlMs <= 0) {\n\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' leaseTtlMs must be positive.`);\n\t}\n\tif (\n\t\tprofile.delegationLimits &&\n\t\t(!Number.isSafeInteger(profile.delegationLimits.maxDepth) ||\n\t\t\tprofile.delegationLimits.maxDepth < 0 ||\n\t\t\tprofile.delegationLimits.maxDepth > MAX_ORCHESTRATION_AGENT_DEPTH ||\n\t\t\t!Number.isSafeInteger(profile.delegationLimits.maxChildrenPerAgent) ||\n\t\t\tprofile.delegationLimits.maxChildrenPerAgent < 0 ||\n\t\t\tprofile.delegationLimits.maxChildrenPerAgent > MAX_ORCHESTRATION_DIRECT_CHILDREN ||\n\t\t\t(profile.delegationLimits.maxNestedAgentsPerSession !== undefined &&\n\t\t\t\t(!Number.isSafeInteger(profile.delegationLimits.maxNestedAgentsPerSession) ||\n\t\t\t\t\tprofile.delegationLimits.maxNestedAgentsPerSession < 0 ||\n\t\t\t\t\tprofile.delegationLimits.maxNestedAgentsPerSession > MAX_ORCHESTRATION_AGENT_BINDINGS)))\n\t) {\n\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' delegationLimits are invalid.`);\n\t}\n\ttry {\n\t\tvalidateRiskBudget(profile.budget, `Profile '${profile.profileId}' budget`);\n\t} catch (error) {\n\t\tthrow new OrchestrationProfileError(error instanceof Error ? error.message : String(error));\n\t}\n\tif (profile.budget.maxWallClockMs !== undefined && profile.budget.maxWallClockMs <= 0) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\t`Profile '${profile.profileId}' maxWallClockMs budget must be positive when specified.`,\n\t\t);\n\t}\n\tif (profile.budget.maxWallClockMs !== undefined && profile.leaseTtlMs < profile.budget.maxWallClockMs) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\t`Profile '${profile.profileId}' leaseTtlMs must cover its maxWallClockMs budget.`,\n\t\t);\n\t}\n\tconst processCapable =\n\t\tprofile.capabilityCeiling.includes(\"process.exec\") || profile.capabilityCeiling.includes(\"tests.execute\");\n\tconst directProcessLauncher = profile.toolNames.includes(\"run_process\");\n\tif (directProcessLauncher && (!profile.executionPolicy || profile.executionPolicy.allowedExecutables.length === 0)) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\t`Profile '${profile.profileId}' must declare executionPolicy.allowedExecutables for run_process.`,\n\t\t);\n\t}\n\tif (!processCapable && profile.executionPolicy) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\t`Profile '${profile.profileId}' cannot declare executionPolicy without process capabilities.`,\n\t\t);\n\t}\n\tif (profile.executionPolicy) {\n\t\tif (\n\t\t\tprofile.executionPolicy.allowedExecutables.length > MAX_ORCHESTRATION_COLLECTION_LENGTH ||\n\t\t\tprofile.executionPolicy.allowedEnvironmentVariables.length > MAX_ORCHESTRATION_COLLECTION_LENGTH ||\n\t\t\tprofile.executionPolicy.allowedExecutables.some(\n\t\t\t\t(executable) =>\n\t\t\t\t\t!executable.trim() ||\n\t\t\t\t\texecutable.length > MAX_WORKER_AUTHORITY_PATH_LENGTH ||\n\t\t\t\t\t/[\\0\\r\\n]/.test(executable),\n\t\t\t) ||\n\t\t\tprofile.executionPolicy.allowedEnvironmentVariables.some(\n\t\t\t\t(name) => name.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name),\n\t\t\t) ||\n\t\t\t!Number.isSafeInteger(profile.executionPolicy.maxOutputBytes) ||\n\t\t\tprofile.executionPolicy.maxOutputBytes <= 0 ||\n\t\t\tprofile.executionPolicy.maxOutputBytes > MAX_ORCHESTRATION_PROCESS_OUTPUT_BYTES\n\t\t) {\n\t\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' executionPolicy is invalid.`);\n\t\t}\n\t}\n\tconst unknownTools = profile.toolNames.filter(\n\t\t(toolName) => !(ORCHESTRATION_PROFILE_TOOL_NAMES as readonly string[]).includes(toolName),\n\t);\n\tif (unknownTools.length > 0) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\t`Profile '${profile.profileId}' contains unclassified orchestration tools: ${unknownTools.join(\", \")}.`,\n\t\t);\n\t}\n\tfor (const toolName of profile.toolNames) {\n\t\tif (!resolveProfileToolCapability(profile, toolName)) {\n\t\t\tthrow new OrchestrationProfileError(\n\t\t\t\t`Profile '${profile.profileId}' tool '${toolName}' lacks ${describeToolCapabilityAuthority(toolName)} authority.`,\n\t\t\t);\n\t\t}\n\t}\n\ttoJsonObject({ profile });\n}\n\nfunction isStringArray(value: unknown, maxLength = MAX_ORCHESTRATION_IDENTIFIER_LENGTH): value is string[] {\n\treturn (\n\t\tArray.isArray(value) &&\n\t\tvalue.length <= MAX_ORCHESTRATION_COLLECTION_LENGTH &&\n\t\tvalue.every((entry) => typeof entry === \"string\" && entry.length > 0 && entry.length <= maxLength)\n\t);\n}\n\nexport function parseOrchestrationProfile(value: unknown, sourcePath?: string): OrchestrationProfile {\n\tif (!isPlainRecord(value)) throw new OrchestrationProfileError(\"Orchestration profile must be an object.\");\n\tif (\n\t\t!hasOnlyKeys(value, [\n\t\t\t\"schemaVersion\",\n\t\t\t\"profileId\",\n\t\t\t\"description\",\n\t\t\t\"role\",\n\t\t\t\"modelPolicy\",\n\t\t\t\"capabilityCeiling\",\n\t\t\t\"toolNames\",\n\t\t\t\"resourceProfileNames\",\n\t\t\t\"dispatchProfileIds\",\n\t\t\t\"executionPolicy\",\n\t\t\t\"delegationLimits\",\n\t\t\t\"budget\",\n\t\t\t\"maxConcurrent\",\n\t\t\t\"leaseTtlMs\",\n\t\t\t\"requireIndependentVerification\",\n\t\t\t\"verificationProfileId\",\n\t\t\t\"createdAt\",\n\t\t\t\"updatedAt\",\n\t\t])\n\t) {\n\t\tthrow new OrchestrationProfileError(\"Orchestration profile contains an unsupported field.\");\n\t}\n\tconst modelPolicy = value.modelPolicy;\n\tconst rawBudget = value.budget;\n\tlet budget: RiskBudget;\n\tconst executionPolicy = value.executionPolicy;\n\tconst delegationLimits = value.delegationLimits;\n\tif (\n\t\t!isPlainRecord(modelPolicy) ||\n\t\t!hasOnlyKeys(modelPolicy, [\"mode\", \"candidates\"]) ||\n\t\t!Array.isArray(modelPolicy.candidates) ||\n\t\tmodelPolicy.candidates.length > MAX_ORCHESTRATION_COLLECTION_LENGTH\n\t) {\n\t\tthrow new OrchestrationProfileError(\"Orchestration profile modelPolicy is invalid.\");\n\t}\n\ttry {\n\t\tbudget = parseRiskBudget(rawBudget, \"Orchestration profile budget\");\n\t} catch (error) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\terror instanceof Error ? error.message : \"Orchestration profile budget is invalid.\",\n\t\t);\n\t}\n\tif (\n\t\texecutionPolicy !== undefined &&\n\t\t(!isPlainRecord(executionPolicy) ||\n\t\t\t!hasOnlyKeys(executionPolicy, [\"allowedExecutables\", \"allowedEnvironmentVariables\", \"maxOutputBytes\"]) ||\n\t\t\t!isStringArray(executionPolicy.allowedExecutables, MAX_WORKER_AUTHORITY_PATH_LENGTH) ||\n\t\t\t!isStringArray(executionPolicy.allowedEnvironmentVariables) ||\n\t\t\t!Number.isSafeInteger(executionPolicy.maxOutputBytes))\n\t) {\n\t\tthrow new OrchestrationProfileError(\"Orchestration profile executionPolicy is invalid.\");\n\t}\n\tif (\n\t\tdelegationLimits !== undefined &&\n\t\t(!isPlainRecord(delegationLimits) ||\n\t\t\t!hasOnlyKeys(delegationLimits, [\"maxDepth\", \"maxChildrenPerAgent\", \"maxNestedAgentsPerSession\"]) ||\n\t\t\t!Number.isSafeInteger(delegationLimits.maxDepth) ||\n\t\t\t!Number.isSafeInteger(delegationLimits.maxChildrenPerAgent) ||\n\t\t\t(delegationLimits.maxNestedAgentsPerSession !== undefined &&\n\t\t\t\t!Number.isSafeInteger(delegationLimits.maxNestedAgentsPerSession)))\n\t) {\n\t\tthrow new OrchestrationProfileError(\"Orchestration profile delegationLimits are invalid.\");\n\t}\n\tconst candidates = modelPolicy.candidates.map((candidate) => {\n\t\tif (!isPlainRecord(candidate) || !hasOnlyKeys(candidate, [\"provider\", \"modelId\", \"thinkingLevel\"])) {\n\t\t\tthrow new OrchestrationProfileError(\"Orchestration profile model candidate is invalid.\");\n\t\t}\n\t\tif (\n\t\t\ttypeof candidate.provider !== \"string\" ||\n\t\t\tcandidate.provider.length === 0 ||\n\t\t\tcandidate.provider.length > MAX_ORCHESTRATION_MODEL_PROVIDER_LENGTH ||\n\t\t\ttypeof candidate.modelId !== \"string\" ||\n\t\t\tcandidate.modelId.length === 0 ||\n\t\t\tcandidate.modelId.length > MAX_ORCHESTRATION_MODEL_ID_LENGTH ||\n\t\t\ttypeof candidate.thinkingLevel !== \"string\" ||\n\t\t\t!ORCHESTRATION_THINKING_LEVELS.includes(\n\t\t\t\tcandidate.thinkingLevel as (typeof ORCHESTRATION_THINKING_LEVELS)[number],\n\t\t\t)\n\t\t) {\n\t\t\tthrow new OrchestrationProfileError(\"Orchestration profile model candidate is invalid.\");\n\t\t}\n\t\treturn {\n\t\t\tprovider: candidate.provider,\n\t\t\tmodelId: candidate.modelId,\n\t\t\tthinkingLevel: candidate.thinkingLevel as (typeof ORCHESTRATION_THINKING_LEVELS)[number],\n\t\t};\n\t});\n\tif (\n\t\tvalue.schemaVersion !== ORCHESTRATION_SCHEMA_VERSION ||\n\t\ttypeof value.profileId !== \"string\" ||\n\t\tvalue.profileId.length === 0 ||\n\t\tvalue.profileId.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH ||\n\t\ttypeof value.description !== \"string\" ||\n\t\tvalue.description.length === 0 ||\n\t\tvalue.description.length > MAX_ORCHESTRATION_DESCRIPTION_LENGTH ||\n\t\ttypeof value.role !== \"string\" ||\n\t\t!WORKER_ROLES.includes(value.role as (typeof WORKER_ROLES)[number]) ||\n\t\t(modelPolicy.mode !== \"fixed\" && modelPolicy.mode !== \"ordered-fallback\") ||\n\t\t!Array.isArray(value.capabilityCeiling) ||\n\t\tvalue.capabilityCeiling.length > MAX_ORCHESTRATION_COLLECTION_LENGTH ||\n\t\t!value.capabilityCeiling.every(\n\t\t\t(capability) =>\n\t\t\t\ttypeof capability === \"string\" &&\n\t\t\t\tHARNESS_CAPABILITIES.includes(capability as (typeof HARNESS_CAPABILITIES)[number]),\n\t\t) ||\n\t\t!isStringArray(value.toolNames) ||\n\t\t!isStringArray(value.resourceProfileNames) ||\n\t\t!isStringArray(value.dispatchProfileIds) ||\n\t\t!Number.isSafeInteger(value.maxConcurrent) ||\n\t\t!Number.isSafeInteger(value.leaseTtlMs) ||\n\t\ttypeof value.requireIndependentVerification !== \"boolean\" ||\n\t\t(value.verificationProfileId !== undefined &&\n\t\t\t(typeof value.verificationProfileId !== \"string\" ||\n\t\t\t\tvalue.verificationProfileId.length === 0 ||\n\t\t\t\tvalue.verificationProfileId.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH)) ||\n\t\ttypeof value.createdAt !== \"string\" ||\n\t\tvalue.createdAt.length === 0 ||\n\t\tvalue.createdAt.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH ||\n\t\ttypeof value.updatedAt !== \"string\" ||\n\t\tvalue.updatedAt.length === 0 ||\n\t\tvalue.updatedAt.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH\n\t) {\n\t\tthrow new OrchestrationProfileError(\"Orchestration profile is invalid.\");\n\t}\n\tconst profile = structuredClone({\n\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\tprofileId: value.profileId,\n\t\tdescription: value.description,\n\t\trole: value.role as OrchestrationProfile[\"role\"],\n\t\tmodelPolicy: { mode: modelPolicy.mode as OrchestrationProfile[\"modelPolicy\"][\"mode\"], candidates },\n\t\tcapabilityCeiling: value.capabilityCeiling as OrchestrationProfile[\"capabilityCeiling\"],\n\t\ttoolNames: value.toolNames,\n\t\tresourceProfileNames: value.resourceProfileNames,\n\t\tdispatchProfileIds: value.dispatchProfileIds,\n\t\t...(executionPolicy\n\t\t\t? {\n\t\t\t\t\texecutionPolicy: {\n\t\t\t\t\t\tallowedExecutables: executionPolicy.allowedExecutables as string[],\n\t\t\t\t\t\tallowedEnvironmentVariables: executionPolicy.allowedEnvironmentVariables as string[],\n\t\t\t\t\t\tmaxOutputBytes: Number(executionPolicy.maxOutputBytes),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\t...(isPlainRecord(delegationLimits)\n\t\t\t? {\n\t\t\t\t\tdelegationLimits: {\n\t\t\t\t\t\tmaxDepth: Number(delegationLimits.maxDepth),\n\t\t\t\t\t\tmaxChildrenPerAgent: Number(delegationLimits.maxChildrenPerAgent),\n\t\t\t\t\t\t...(delegationLimits.maxNestedAgentsPerSession !== undefined\n\t\t\t\t\t\t\t? { maxNestedAgentsPerSession: Number(delegationLimits.maxNestedAgentsPerSession) }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\tbudget,\n\t\tmaxConcurrent: Number(value.maxConcurrent),\n\t\tleaseTtlMs: Number(value.leaseTtlMs),\n\t\trequireIndependentVerification: value.requireIndependentVerification,\n\t\t...(typeof value.verificationProfileId === \"string\"\n\t\t\t? { verificationProfileId: value.verificationProfileId }\n\t\t\t: {}),\n\t\t...(sourcePath ? { sourcePath } : {}),\n\t\tcreatedAt: value.createdAt,\n\t\tupdatedAt: value.updatedAt,\n\t}) as OrchestrationProfile;\n\tvalidateOrchestrationProfile(profile);\n\treturn profile;\n}\n\nfunction freezeProfile(profile: OrchestrationProfile): OrchestrationProfile {\n\tconst clone = structuredClone(profile);\n\tfor (const candidate of clone.modelPolicy.candidates) Object.freeze(candidate);\n\tObject.freeze(clone.modelPolicy.candidates);\n\tObject.freeze(clone.modelPolicy);\n\tObject.freeze(clone.capabilityCeiling);\n\tObject.freeze(clone.toolNames);\n\tObject.freeze(clone.resourceProfileNames);\n\tObject.freeze(clone.dispatchProfileIds);\n\tif (clone.executionPolicy) {\n\t\tObject.freeze(clone.executionPolicy.allowedExecutables);\n\t\tObject.freeze(clone.executionPolicy.allowedEnvironmentVariables);\n\t\tObject.freeze(clone.executionPolicy);\n\t}\n\tif (clone.delegationLimits) Object.freeze(clone.delegationLimits);\n\tObject.freeze(clone.budget);\n\treturn Object.freeze(clone);\n}\n\nexport class OrchestrationProfileRegistry {\n\tprivate readonly profiles = new Map<string, OrchestrationProfile>();\n\n\tconstructor(profiles: readonly OrchestrationProfile[] = []) {\n\t\tfor (const profile of profiles) this.register(profile);\n\t\tfor (const profile of this.profiles.values()) {\n\t\t\tfor (const dispatchedProfileId of profile.dispatchProfileIds) {\n\t\t\t\tconst target = this.profiles.get(dispatchedProfileId);\n\t\t\t\tif (!target) {\n\t\t\t\t\tthrow new OrchestrationProfileError(\n\t\t\t\t\t\t`Profile '${profile.profileId}' dispatches missing profile '${dispatchedProfileId}'.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (profile.verificationProfileId) {\n\t\t\t\tconst verifier = this.profiles.get(profile.verificationProfileId);\n\t\t\t\tif (!verifier) {\n\t\t\t\t\tthrow new OrchestrationProfileError(\n\t\t\t\t\t\t`Profile '${profile.profileId}' requires missing verifier profile '${profile.verificationProfileId}'.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (verifier.role !== \"verifier\") {\n\t\t\t\t\tthrow new OrchestrationProfileError(\n\t\t\t\t\t\t`Profile '${profile.profileId}' verificationProfileId '${profile.verificationProfileId}' is not a verifier.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (profile.role === \"orchestrator\") {\n\t\t\t\tfor (const dispatchedProfileId of profile.dispatchProfileIds) {\n\t\t\t\t\tconst worker = this.profiles.get(dispatchedProfileId);\n\t\t\t\t\tif (\n\t\t\t\t\t\tworker?.verificationProfileId &&\n\t\t\t\t\t\t!profile.dispatchProfileIds.includes(worker.verificationProfileId)\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new OrchestrationProfileError(\n\t\t\t\t\t\t\t`Orchestrator '${profile.profileId}' dispatches '${worker.profileId}' but not its verifier '${worker.verificationProfileId}'.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tregister(profile: OrchestrationProfile): void {\n\t\tvalidateOrchestrationProfile(profile);\n\t\tif (this.profiles.has(profile.profileId)) {\n\t\t\tthrow new OrchestrationProfileError(`Duplicate orchestration profile '${profile.profileId}'.`);\n\t\t}\n\t\tthis.profiles.set(profile.profileId, freezeProfile(profile));\n\t}\n\n\tget(profileId: string): OrchestrationProfile | undefined {\n\t\tconst profile = this.profiles.get(profileId);\n\t\treturn profile ? structuredClone(profile) : undefined;\n\t}\n\n\tlist(): OrchestrationProfile[] {\n\t\treturn [...this.profiles.values()].map((profile) => structuredClone(profile));\n\t}\n}\n\nexport function resolveProfileModel(\n\tprofile: OrchestrationProfile,\n\thealth: ModelHealthView,\n): OrchestrationModelBinding | undefined {\n\tif (profile.modelPolicy.mode === \"fixed\") {\n\t\tconst fixed = profile.modelPolicy.candidates[0];\n\t\treturn fixed && health.isHealthy(fixed) ? structuredClone(fixed) : undefined;\n\t}\n\tconst selected = profile.modelPolicy.candidates.find((candidate) => health.isHealthy(candidate));\n\treturn selected ? structuredClone(selected) : undefined;\n}\n\nexport function planProfileDispatch(args: {\n\trequest: OrchestrationDispatchRequest;\n\ttask: TaskContract;\n\tattemptId: string;\n\tsubjectId: string;\n\tregistry: OrchestrationProfileRegistry;\n\thealth: ModelHealthView;\n\tpolicyCompiler: ExecutionPolicyCompiler;\n\ttoolManifests: readonly ToolCapabilityManifest[];\n\tresources: readonly ResourcePointer[];\n\treadPaths: readonly string[];\n\twritePaths?: readonly string[];\n\tdeniedPaths?: readonly string[];\n\tpolicyVersion: string;\n}): ProfileDispatchPlanResult {\n\tconst profile = args.registry.get(args.request.profileId);\n\tif (!profile) return { outcome: \"deny\", decisions: [], reasonCodes: [\"profile_model_unavailable\"] };\n\tif (profile.role !== args.task.role) {\n\t\treturn { outcome: \"deny\", decisions: [], reasonCodes: [\"required_capability_exceeds_role_ceiling\"] };\n\t}\n\tconst model = resolveProfileModel(profile, args.health);\n\tif (!model) return { outcome: \"deny\", decisions: [], reasonCodes: [\"profile_model_unavailable\"] };\n\tconst selectedResources = args.resources.filter((resource) => args.request.resourcePointerIds.includes(resource.id));\n\tconst manifestsByName = new Map(args.toolManifests.map((manifest) => [manifest.toolName, manifest]));\n\tconst requestedTools = profile.toolNames.filter((toolName) => {\n\t\tconst manifest = manifestsByName.get(toolName);\n\t\treturn manifest?.capabilities.every((capability) => args.task.requiredCapabilities.includes(capability)) === true;\n\t});\n\tconst policyInput: CompileExecutionGrantInput = {\n\t\tobjectiveId: args.task.objectiveId,\n\t\ttaskId: args.task.taskId,\n\t\tattemptId: args.attemptId,\n\t\tsubjectId: args.subjectId,\n\t\trole: profile.role,\n\t\trequiredCapabilities: args.task.requiredCapabilities,\n\t\trequestedCapabilities: args.task.requiredCapabilities,\n\t\tauthorityCapabilities: profile.capabilityCeiling,\n\t\trequestedTools,\n\t\ttoolManifests: args.toolManifests,\n\t\tresources: selectedResources,\n\t\treadPaths: args.readPaths,\n\t\twritePaths: args.writePaths,\n\t\tdeniedPaths: args.deniedPaths,\n\t\trequestedBudget: profile.budget,\n\t\tauthorityBudget: profile.budget,\n\t\tpolicyVersion: args.policyVersion,\n\t};\n\tconst compiled = args.policyCompiler.compile(policyInput);\n\tif (compiled.outcome !== \"allow\") return compiled;\n\treturn { outcome: \"allow\", plan: { profile, model, grant: compiled.grant, toolManifests: compiled.toolManifests } };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"profile-registry.js","sourceRoot":"","sources":["../../../src/core/orchestration/profile-registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,+BAA+B,EAAE,8BAA8B,EAAE,MAAM,8BAA8B,CAAC;AAC/G,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AAWrE,OAAO,EACN,oBAAoB,EACpB,gCAAgC,EAChC,6BAA6B,EAC7B,mCAAmC,EACnC,oCAAoC,EACpC,iCAAiC,EACjC,8CAA8C,EAC9C,mCAAmC,EACnC,iCAAiC,EACjC,uCAAuC,EACvC,sCAAsC,EACtC,gCAAgC,EA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,MAAM,QAAQ,GAAG,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;IAC1D,IAAI,QAAQ,CAAC,OAAO,KAAK,OAAO;QAAE,OAAO,QAAQ,CAAC;IAClD,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,aAAa,EAAE,QAAQ,CAAC,aAAa,EAAE,EAAE,CAAC;AACrH,CAAC","sourcesContent":["import { describeToolCapabilityAuthority, resolveProfileToolCapabilities } from \"../tool-capability-policy.ts\";\nimport { hasOnlyKeys, isPlainRecord } from \"../util/value-guards.ts\";\nimport type {\n\tExecutionGrant,\n\tOrchestrationDispatchRequest,\n\tOrchestrationModelBinding,\n\tOrchestrationProfile,\n\tResourcePointer,\n\tRiskBudget,\n\tTaskContract,\n\tToolCapabilityManifest,\n} from \"./contracts.ts\";\nimport {\n\tHARNESS_CAPABILITIES,\n\tMAX_ORCHESTRATION_AGENT_BINDINGS,\n\tMAX_ORCHESTRATION_AGENT_DEPTH,\n\tMAX_ORCHESTRATION_COLLECTION_LENGTH,\n\tMAX_ORCHESTRATION_DESCRIPTION_LENGTH,\n\tMAX_ORCHESTRATION_DIRECT_CHILDREN,\n\tMAX_ORCHESTRATION_DISPATCH_INSTRUCTIONS_LENGTH,\n\tMAX_ORCHESTRATION_IDENTIFIER_LENGTH,\n\tMAX_ORCHESTRATION_MODEL_ID_LENGTH,\n\tMAX_ORCHESTRATION_MODEL_PROVIDER_LENGTH,\n\tMAX_ORCHESTRATION_PROCESS_OUTPUT_BYTES,\n\tMAX_WORKER_AUTHORITY_PATH_LENGTH,\n\tORCHESTRATION_SCHEMA_VERSION,\n\tORCHESTRATION_THINKING_LEVELS,\n\ttoJsonObject,\n\tWORKER_ROLES,\n} from \"./contracts.ts\";\nimport { ORCHESTRATION_PROFILE_TOOL_NAMES } from \"./lane-tool-manifests.ts\";\nimport {\n\ttype CompileExecutionGrantInput,\n\tDEFAULT_ROLE_CAPABILITY_CEILINGS,\n\ttype ExecutionPolicyCompiler,\n\ttype PolicyCompilationResult,\n} from \"./policy-compiler.ts\";\nimport { parseRiskBudget, validateRiskBudget } from \"./risk-budget.ts\";\n\nexport interface ModelHealthView {\n\tisHealthy(binding: OrchestrationModelBinding): boolean;\n}\n\nexport interface ProfileDispatchPlan {\n\tprofile: OrchestrationProfile;\n\tmodel: OrchestrationModelBinding;\n\tgrant: ExecutionGrant;\n\ttoolManifests: readonly ToolCapabilityManifest[];\n}\n\nexport type ProfileDispatchPlanResult =\n\t| { outcome: \"allow\"; plan: ProfileDispatchPlan }\n\t| Exclude<PolicyCompilationResult, { outcome: \"allow\" }>\n\t| { outcome: \"deny\"; decisions: readonly []; reasonCodes: readonly [\"profile_model_unavailable\"] };\n\nexport class OrchestrationProfileError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"OrchestrationProfileError\";\n\t}\n}\n\nfunction duplicateStrings(values: readonly string[]): string[] {\n\tconst seen = new Set<string>();\n\tconst duplicates = new Set<string>();\n\tfor (const value of values) {\n\t\tif (seen.has(value)) duplicates.add(value);\n\t\tseen.add(value);\n\t}\n\treturn [...duplicates];\n}\n\nexport function parseOrchestrationDispatchRequest(value: unknown): OrchestrationDispatchRequest {\n\tif (!isPlainRecord(value)) throw new OrchestrationProfileError(\"Dispatch request must be an object.\");\n\tif (!hasOnlyKeys(value, [\"taskId\", \"profileId\", \"instructions\", \"resourcePointerIds\"])) {\n\t\tthrow new OrchestrationProfileError(\"Dispatch request contains an unsupported durable metadata field.\");\n\t}\n\tif (\n\t\ttypeof value.taskId !== \"string\" ||\n\t\t!value.taskId ||\n\t\tvalue.taskId.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH ||\n\t\ttypeof value.profileId !== \"string\" ||\n\t\t!value.profileId ||\n\t\tvalue.profileId.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH ||\n\t\ttypeof value.instructions !== \"string\" ||\n\t\tvalue.instructions.length > MAX_ORCHESTRATION_DISPATCH_INSTRUCTIONS_LENGTH ||\n\t\t!value.instructions.trim() ||\n\t\t!Array.isArray(value.resourcePointerIds) ||\n\t\tvalue.resourcePointerIds.length > MAX_ORCHESTRATION_COLLECTION_LENGTH ||\n\t\t!value.resourcePointerIds.every(\n\t\t\t(entry) =>\n\t\t\t\ttypeof entry === \"string\" && entry.length > 0 && entry.length <= MAX_ORCHESTRATION_IDENTIFIER_LENGTH,\n\t\t) ||\n\t\tnew Set(value.resourcePointerIds).size !== value.resourcePointerIds.length\n\t) {\n\t\tthrow new OrchestrationProfileError(\"Dispatch request is invalid.\");\n\t}\n\treturn {\n\t\ttaskId: value.taskId,\n\t\tprofileId: value.profileId,\n\t\tinstructions: value.instructions.trim(),\n\t\tresourcePointerIds: [...value.resourcePointerIds],\n\t};\n}\n\nexport function validateOrchestrationProfile(profile: OrchestrationProfile): void {\n\tif (profile.schemaVersion !== ORCHESTRATION_SCHEMA_VERSION) {\n\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' has an unsupported schema version.`);\n\t}\n\tif (\n\t\tprofile.profileId.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH ||\n\t\t!profile.profileId.trim() ||\n\t\tprofile.description.length > MAX_ORCHESTRATION_DESCRIPTION_LENGTH ||\n\t\t!profile.description.trim()\n\t)\n\t\tthrow new OrchestrationProfileError(\"Profile id and description are required.\");\n\tif (profile.role !== \"orchestrator\" && profile.dispatchProfileIds.length > 0) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\t`Only orchestrator profiles may declare dispatchProfileIds ('${profile.profileId}').`,\n\t\t);\n\t}\n\tif (profile.dispatchProfileIds.includes(profile.profileId)) {\n\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' cannot dispatch itself.`);\n\t}\n\tif (profile.requireIndependentVerification) {\n\t\tif (profile.role === \"verifier\") {\n\t\t\tthrow new OrchestrationProfileError(\n\t\t\t\t`Verifier profile '${profile.profileId}' cannot require another verifier.`,\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\t!profile.verificationProfileId?.trim() ||\n\t\t\tprofile.verificationProfileId.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH\n\t\t) {\n\t\t\tthrow new OrchestrationProfileError(\n\t\t\t\t`Profile '${profile.profileId}' requires independent verification but has no verificationProfileId.`,\n\t\t\t);\n\t\t}\n\t} else if (profile.verificationProfileId !== undefined) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\t`Profile '${profile.profileId}' cannot declare verificationProfileId without requiring verification.`,\n\t\t);\n\t}\n\tif (profile.verificationProfileId === profile.profileId) {\n\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' cannot verify itself.`);\n\t}\n\tif (\n\t\t!profile.createdAt.trim() ||\n\t\tprofile.createdAt.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH ||\n\t\t!profile.updatedAt.trim() ||\n\t\tprofile.updatedAt.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH\n\t) {\n\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' timestamps are invalid.`);\n\t}\n\tfor (const [label, values] of [\n\t\t[\"capabilityCeiling\", profile.capabilityCeiling],\n\t\t[\"toolNames\", profile.toolNames],\n\t\t[\"resourceProfileNames\", profile.resourceProfileNames],\n\t\t[\"dispatchProfileIds\", profile.dispatchProfileIds],\n\t] as const) {\n\t\tif (\n\t\t\tvalues.length > MAX_ORCHESTRATION_COLLECTION_LENGTH ||\n\t\t\tvalues.some((value) => !value.trim() || value.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH)\n\t\t) {\n\t\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' contains an invalid ${label}.`);\n\t\t}\n\t\tconst duplicates = duplicateStrings(values);\n\t\tif (duplicates.length > 0) {\n\t\t\tthrow new OrchestrationProfileError(\n\t\t\t\t`Profile '${profile.profileId}' contains duplicate ${label}: ${duplicates.join(\", \")}.`,\n\t\t\t);\n\t\t}\n\t}\n\tconst roleCeiling = new Set(DEFAULT_ROLE_CAPABILITY_CEILINGS[profile.role]);\n\tconst outOfRoleCapabilities = profile.capabilityCeiling.filter((capability) => !roleCeiling.has(capability));\n\tif (outOfRoleCapabilities.length > 0) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\t`Profile '${profile.profileId}' exceeds the ${profile.role} role ceiling: ${outOfRoleCapabilities.join(\", \")}.`,\n\t\t);\n\t}\n\tif (\n\t\tprofile.modelPolicy.candidates.length === 0 ||\n\t\tprofile.modelPolicy.candidates.length > MAX_ORCHESTRATION_COLLECTION_LENGTH\n\t) {\n\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' must declare a model candidate.`);\n\t}\n\tif (profile.modelPolicy.mode === \"fixed\" && profile.modelPolicy.candidates.length !== 1) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\t`Fixed profile '${profile.profileId}' must declare exactly one model candidate.`,\n\t\t);\n\t}\n\tfor (const candidate of profile.modelPolicy.candidates) {\n\t\tif (\n\t\t\tcandidate.provider.length > MAX_ORCHESTRATION_MODEL_PROVIDER_LENGTH ||\n\t\t\t!candidate.provider.trim() ||\n\t\t\tcandidate.modelId.length > MAX_ORCHESTRATION_MODEL_ID_LENGTH ||\n\t\t\t!candidate.modelId.trim()\n\t\t) {\n\t\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' contains an invalid model binding.`);\n\t\t}\n\t}\n\tconst duplicateModels = duplicateStrings(\n\t\tprofile.modelPolicy.candidates.map((candidate) => `${candidate.provider}/${candidate.modelId}`),\n\t);\n\tif (duplicateModels.length > 0) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\t`Profile '${profile.profileId}' contains duplicate model candidates: ${duplicateModels.join(\", \")}.`,\n\t\t);\n\t}\n\tif (!Number.isSafeInteger(profile.maxConcurrent) || profile.maxConcurrent <= 0) {\n\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' maxConcurrent must be positive.`);\n\t}\n\tif (!Number.isSafeInteger(profile.leaseTtlMs) || profile.leaseTtlMs <= 0) {\n\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' leaseTtlMs must be positive.`);\n\t}\n\tif (\n\t\tprofile.delegationLimits &&\n\t\t(!Number.isSafeInteger(profile.delegationLimits.maxDepth) ||\n\t\t\tprofile.delegationLimits.maxDepth < 0 ||\n\t\t\tprofile.delegationLimits.maxDepth > MAX_ORCHESTRATION_AGENT_DEPTH ||\n\t\t\t!Number.isSafeInteger(profile.delegationLimits.maxChildrenPerAgent) ||\n\t\t\tprofile.delegationLimits.maxChildrenPerAgent < 0 ||\n\t\t\tprofile.delegationLimits.maxChildrenPerAgent > MAX_ORCHESTRATION_DIRECT_CHILDREN ||\n\t\t\t(profile.delegationLimits.maxNestedAgentsPerSession !== undefined &&\n\t\t\t\t(!Number.isSafeInteger(profile.delegationLimits.maxNestedAgentsPerSession) ||\n\t\t\t\t\tprofile.delegationLimits.maxNestedAgentsPerSession < 0 ||\n\t\t\t\t\tprofile.delegationLimits.maxNestedAgentsPerSession > MAX_ORCHESTRATION_AGENT_BINDINGS)))\n\t) {\n\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' delegationLimits are invalid.`);\n\t}\n\ttry {\n\t\tvalidateRiskBudget(profile.budget, `Profile '${profile.profileId}' budget`);\n\t} catch (error) {\n\t\tthrow new OrchestrationProfileError(error instanceof Error ? error.message : String(error));\n\t}\n\tif (profile.budget.maxWallClockMs !== undefined && profile.budget.maxWallClockMs <= 0) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\t`Profile '${profile.profileId}' maxWallClockMs budget must be positive when specified.`,\n\t\t);\n\t}\n\tif (profile.budget.maxWallClockMs !== undefined && profile.leaseTtlMs < profile.budget.maxWallClockMs) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\t`Profile '${profile.profileId}' leaseTtlMs must cover its maxWallClockMs budget.`,\n\t\t);\n\t}\n\tconst processCapable =\n\t\tprofile.capabilityCeiling.includes(\"process.exec\") || profile.capabilityCeiling.includes(\"tests.execute\");\n\tconst directProcessLauncher = profile.toolNames.includes(\"run_process\");\n\tif (directProcessLauncher && (!profile.executionPolicy || profile.executionPolicy.allowedExecutables.length === 0)) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\t`Profile '${profile.profileId}' must declare executionPolicy.allowedExecutables for run_process.`,\n\t\t);\n\t}\n\tif (!processCapable && profile.executionPolicy) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\t`Profile '${profile.profileId}' cannot declare executionPolicy without process capabilities.`,\n\t\t);\n\t}\n\tif (profile.executionPolicy) {\n\t\tif (\n\t\t\tprofile.executionPolicy.allowedExecutables.length > MAX_ORCHESTRATION_COLLECTION_LENGTH ||\n\t\t\tprofile.executionPolicy.allowedEnvironmentVariables.length > MAX_ORCHESTRATION_COLLECTION_LENGTH ||\n\t\t\tprofile.executionPolicy.allowedExecutables.some(\n\t\t\t\t(executable) =>\n\t\t\t\t\t!executable.trim() ||\n\t\t\t\t\texecutable.length > MAX_WORKER_AUTHORITY_PATH_LENGTH ||\n\t\t\t\t\t/[\\0\\r\\n]/.test(executable),\n\t\t\t) ||\n\t\t\tprofile.executionPolicy.allowedEnvironmentVariables.some(\n\t\t\t\t(name) => name.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name),\n\t\t\t) ||\n\t\t\t!Number.isSafeInteger(profile.executionPolicy.maxOutputBytes) ||\n\t\t\tprofile.executionPolicy.maxOutputBytes <= 0 ||\n\t\t\tprofile.executionPolicy.maxOutputBytes > MAX_ORCHESTRATION_PROCESS_OUTPUT_BYTES\n\t\t) {\n\t\t\tthrow new OrchestrationProfileError(`Profile '${profile.profileId}' executionPolicy is invalid.`);\n\t\t}\n\t}\n\tconst unknownTools = profile.toolNames.filter(\n\t\t(toolName) => !(ORCHESTRATION_PROFILE_TOOL_NAMES as readonly string[]).includes(toolName),\n\t);\n\tif (unknownTools.length > 0) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\t`Profile '${profile.profileId}' contains unclassified orchestration tools: ${unknownTools.join(\", \")}.`,\n\t\t);\n\t}\n\tfor (const toolName of profile.toolNames) {\n\t\tif (!resolveProfileToolCapabilities(profile, toolName)) {\n\t\t\tthrow new OrchestrationProfileError(\n\t\t\t\t`Profile '${profile.profileId}' tool '${toolName}' lacks ${describeToolCapabilityAuthority(toolName)} authority.`,\n\t\t\t);\n\t\t}\n\t}\n\ttoJsonObject({ profile });\n}\n\nfunction isStringArray(value: unknown, maxLength = MAX_ORCHESTRATION_IDENTIFIER_LENGTH): value is string[] {\n\treturn (\n\t\tArray.isArray(value) &&\n\t\tvalue.length <= MAX_ORCHESTRATION_COLLECTION_LENGTH &&\n\t\tvalue.every((entry) => typeof entry === \"string\" && entry.length > 0 && entry.length <= maxLength)\n\t);\n}\n\nexport function parseOrchestrationProfile(value: unknown, sourcePath?: string): OrchestrationProfile {\n\tif (!isPlainRecord(value)) throw new OrchestrationProfileError(\"Orchestration profile must be an object.\");\n\tif (\n\t\t!hasOnlyKeys(value, [\n\t\t\t\"schemaVersion\",\n\t\t\t\"profileId\",\n\t\t\t\"description\",\n\t\t\t\"role\",\n\t\t\t\"modelPolicy\",\n\t\t\t\"capabilityCeiling\",\n\t\t\t\"toolNames\",\n\t\t\t\"resourceProfileNames\",\n\t\t\t\"dispatchProfileIds\",\n\t\t\t\"executionPolicy\",\n\t\t\t\"delegationLimits\",\n\t\t\t\"budget\",\n\t\t\t\"maxConcurrent\",\n\t\t\t\"leaseTtlMs\",\n\t\t\t\"requireIndependentVerification\",\n\t\t\t\"verificationProfileId\",\n\t\t\t\"createdAt\",\n\t\t\t\"updatedAt\",\n\t\t])\n\t) {\n\t\tthrow new OrchestrationProfileError(\"Orchestration profile contains an unsupported field.\");\n\t}\n\tconst modelPolicy = value.modelPolicy;\n\tconst rawBudget = value.budget;\n\tlet budget: RiskBudget;\n\tconst executionPolicy = value.executionPolicy;\n\tconst delegationLimits = value.delegationLimits;\n\tif (\n\t\t!isPlainRecord(modelPolicy) ||\n\t\t!hasOnlyKeys(modelPolicy, [\"mode\", \"candidates\"]) ||\n\t\t!Array.isArray(modelPolicy.candidates) ||\n\t\tmodelPolicy.candidates.length > MAX_ORCHESTRATION_COLLECTION_LENGTH\n\t) {\n\t\tthrow new OrchestrationProfileError(\"Orchestration profile modelPolicy is invalid.\");\n\t}\n\ttry {\n\t\tbudget = parseRiskBudget(rawBudget, \"Orchestration profile budget\");\n\t} catch (error) {\n\t\tthrow new OrchestrationProfileError(\n\t\t\terror instanceof Error ? error.message : \"Orchestration profile budget is invalid.\",\n\t\t);\n\t}\n\tif (\n\t\texecutionPolicy !== undefined &&\n\t\t(!isPlainRecord(executionPolicy) ||\n\t\t\t!hasOnlyKeys(executionPolicy, [\"allowedExecutables\", \"allowedEnvironmentVariables\", \"maxOutputBytes\"]) ||\n\t\t\t!isStringArray(executionPolicy.allowedExecutables, MAX_WORKER_AUTHORITY_PATH_LENGTH) ||\n\t\t\t!isStringArray(executionPolicy.allowedEnvironmentVariables) ||\n\t\t\t!Number.isSafeInteger(executionPolicy.maxOutputBytes))\n\t) {\n\t\tthrow new OrchestrationProfileError(\"Orchestration profile executionPolicy is invalid.\");\n\t}\n\tif (\n\t\tdelegationLimits !== undefined &&\n\t\t(!isPlainRecord(delegationLimits) ||\n\t\t\t!hasOnlyKeys(delegationLimits, [\"maxDepth\", \"maxChildrenPerAgent\", \"maxNestedAgentsPerSession\"]) ||\n\t\t\t!Number.isSafeInteger(delegationLimits.maxDepth) ||\n\t\t\t!Number.isSafeInteger(delegationLimits.maxChildrenPerAgent) ||\n\t\t\t(delegationLimits.maxNestedAgentsPerSession !== undefined &&\n\t\t\t\t!Number.isSafeInteger(delegationLimits.maxNestedAgentsPerSession)))\n\t) {\n\t\tthrow new OrchestrationProfileError(\"Orchestration profile delegationLimits are invalid.\");\n\t}\n\tconst candidates = modelPolicy.candidates.map((candidate) => {\n\t\tif (!isPlainRecord(candidate) || !hasOnlyKeys(candidate, [\"provider\", \"modelId\", \"thinkingLevel\"])) {\n\t\t\tthrow new OrchestrationProfileError(\"Orchestration profile model candidate is invalid.\");\n\t\t}\n\t\tif (\n\t\t\ttypeof candidate.provider !== \"string\" ||\n\t\t\tcandidate.provider.length === 0 ||\n\t\t\tcandidate.provider.length > MAX_ORCHESTRATION_MODEL_PROVIDER_LENGTH ||\n\t\t\ttypeof candidate.modelId !== \"string\" ||\n\t\t\tcandidate.modelId.length === 0 ||\n\t\t\tcandidate.modelId.length > MAX_ORCHESTRATION_MODEL_ID_LENGTH ||\n\t\t\ttypeof candidate.thinkingLevel !== \"string\" ||\n\t\t\t!ORCHESTRATION_THINKING_LEVELS.includes(\n\t\t\t\tcandidate.thinkingLevel as (typeof ORCHESTRATION_THINKING_LEVELS)[number],\n\t\t\t)\n\t\t) {\n\t\t\tthrow new OrchestrationProfileError(\"Orchestration profile model candidate is invalid.\");\n\t\t}\n\t\treturn {\n\t\t\tprovider: candidate.provider,\n\t\t\tmodelId: candidate.modelId,\n\t\t\tthinkingLevel: candidate.thinkingLevel as (typeof ORCHESTRATION_THINKING_LEVELS)[number],\n\t\t};\n\t});\n\tif (\n\t\tvalue.schemaVersion !== ORCHESTRATION_SCHEMA_VERSION ||\n\t\ttypeof value.profileId !== \"string\" ||\n\t\tvalue.profileId.length === 0 ||\n\t\tvalue.profileId.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH ||\n\t\ttypeof value.description !== \"string\" ||\n\t\tvalue.description.length === 0 ||\n\t\tvalue.description.length > MAX_ORCHESTRATION_DESCRIPTION_LENGTH ||\n\t\ttypeof value.role !== \"string\" ||\n\t\t!WORKER_ROLES.includes(value.role as (typeof WORKER_ROLES)[number]) ||\n\t\t(modelPolicy.mode !== \"fixed\" && modelPolicy.mode !== \"ordered-fallback\") ||\n\t\t!Array.isArray(value.capabilityCeiling) ||\n\t\tvalue.capabilityCeiling.length > MAX_ORCHESTRATION_COLLECTION_LENGTH ||\n\t\t!value.capabilityCeiling.every(\n\t\t\t(capability) =>\n\t\t\t\ttypeof capability === \"string\" &&\n\t\t\t\tHARNESS_CAPABILITIES.includes(capability as (typeof HARNESS_CAPABILITIES)[number]),\n\t\t) ||\n\t\t!isStringArray(value.toolNames) ||\n\t\t!isStringArray(value.resourceProfileNames) ||\n\t\t!isStringArray(value.dispatchProfileIds) ||\n\t\t!Number.isSafeInteger(value.maxConcurrent) ||\n\t\t!Number.isSafeInteger(value.leaseTtlMs) ||\n\t\ttypeof value.requireIndependentVerification !== \"boolean\" ||\n\t\t(value.verificationProfileId !== undefined &&\n\t\t\t(typeof value.verificationProfileId !== \"string\" ||\n\t\t\t\tvalue.verificationProfileId.length === 0 ||\n\t\t\t\tvalue.verificationProfileId.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH)) ||\n\t\ttypeof value.createdAt !== \"string\" ||\n\t\tvalue.createdAt.length === 0 ||\n\t\tvalue.createdAt.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH ||\n\t\ttypeof value.updatedAt !== \"string\" ||\n\t\tvalue.updatedAt.length === 0 ||\n\t\tvalue.updatedAt.length > MAX_ORCHESTRATION_IDENTIFIER_LENGTH\n\t) {\n\t\tthrow new OrchestrationProfileError(\"Orchestration profile is invalid.\");\n\t}\n\tconst profile = structuredClone({\n\t\tschemaVersion: ORCHESTRATION_SCHEMA_VERSION,\n\t\tprofileId: value.profileId,\n\t\tdescription: value.description,\n\t\trole: value.role as OrchestrationProfile[\"role\"],\n\t\tmodelPolicy: { mode: modelPolicy.mode as OrchestrationProfile[\"modelPolicy\"][\"mode\"], candidates },\n\t\tcapabilityCeiling: value.capabilityCeiling as OrchestrationProfile[\"capabilityCeiling\"],\n\t\ttoolNames: value.toolNames,\n\t\tresourceProfileNames: value.resourceProfileNames,\n\t\tdispatchProfileIds: value.dispatchProfileIds,\n\t\t...(executionPolicy\n\t\t\t? {\n\t\t\t\t\texecutionPolicy: {\n\t\t\t\t\t\tallowedExecutables: executionPolicy.allowedExecutables as string[],\n\t\t\t\t\t\tallowedEnvironmentVariables: executionPolicy.allowedEnvironmentVariables as string[],\n\t\t\t\t\t\tmaxOutputBytes: Number(executionPolicy.maxOutputBytes),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\t...(isPlainRecord(delegationLimits)\n\t\t\t? {\n\t\t\t\t\tdelegationLimits: {\n\t\t\t\t\t\tmaxDepth: Number(delegationLimits.maxDepth),\n\t\t\t\t\t\tmaxChildrenPerAgent: Number(delegationLimits.maxChildrenPerAgent),\n\t\t\t\t\t\t...(delegationLimits.maxNestedAgentsPerSession !== undefined\n\t\t\t\t\t\t\t? { maxNestedAgentsPerSession: Number(delegationLimits.maxNestedAgentsPerSession) }\n\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t\tbudget,\n\t\tmaxConcurrent: Number(value.maxConcurrent),\n\t\tleaseTtlMs: Number(value.leaseTtlMs),\n\t\trequireIndependentVerification: value.requireIndependentVerification,\n\t\t...(typeof value.verificationProfileId === \"string\"\n\t\t\t? { verificationProfileId: value.verificationProfileId }\n\t\t\t: {}),\n\t\t...(sourcePath ? { sourcePath } : {}),\n\t\tcreatedAt: value.createdAt,\n\t\tupdatedAt: value.updatedAt,\n\t}) as OrchestrationProfile;\n\tvalidateOrchestrationProfile(profile);\n\treturn profile;\n}\n\nfunction freezeProfile(profile: OrchestrationProfile): OrchestrationProfile {\n\tconst clone = structuredClone(profile);\n\tfor (const candidate of clone.modelPolicy.candidates) Object.freeze(candidate);\n\tObject.freeze(clone.modelPolicy.candidates);\n\tObject.freeze(clone.modelPolicy);\n\tObject.freeze(clone.capabilityCeiling);\n\tObject.freeze(clone.toolNames);\n\tObject.freeze(clone.resourceProfileNames);\n\tObject.freeze(clone.dispatchProfileIds);\n\tif (clone.executionPolicy) {\n\t\tObject.freeze(clone.executionPolicy.allowedExecutables);\n\t\tObject.freeze(clone.executionPolicy.allowedEnvironmentVariables);\n\t\tObject.freeze(clone.executionPolicy);\n\t}\n\tif (clone.delegationLimits) Object.freeze(clone.delegationLimits);\n\tObject.freeze(clone.budget);\n\treturn Object.freeze(clone);\n}\n\nexport class OrchestrationProfileRegistry {\n\tprivate readonly profiles = new Map<string, OrchestrationProfile>();\n\n\tconstructor(profiles: readonly OrchestrationProfile[] = []) {\n\t\tfor (const profile of profiles) this.register(profile);\n\t\tfor (const profile of this.profiles.values()) {\n\t\t\tfor (const dispatchedProfileId of profile.dispatchProfileIds) {\n\t\t\t\tconst target = this.profiles.get(dispatchedProfileId);\n\t\t\t\tif (!target) {\n\t\t\t\t\tthrow new OrchestrationProfileError(\n\t\t\t\t\t\t`Profile '${profile.profileId}' dispatches missing profile '${dispatchedProfileId}'.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (profile.verificationProfileId) {\n\t\t\t\tconst verifier = this.profiles.get(profile.verificationProfileId);\n\t\t\t\tif (!verifier) {\n\t\t\t\t\tthrow new OrchestrationProfileError(\n\t\t\t\t\t\t`Profile '${profile.profileId}' requires missing verifier profile '${profile.verificationProfileId}'.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tif (verifier.role !== \"verifier\") {\n\t\t\t\t\tthrow new OrchestrationProfileError(\n\t\t\t\t\t\t`Profile '${profile.profileId}' verificationProfileId '${profile.verificationProfileId}' is not a verifier.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (profile.role === \"orchestrator\") {\n\t\t\t\tfor (const dispatchedProfileId of profile.dispatchProfileIds) {\n\t\t\t\t\tconst worker = this.profiles.get(dispatchedProfileId);\n\t\t\t\t\tif (\n\t\t\t\t\t\tworker?.verificationProfileId &&\n\t\t\t\t\t\t!profile.dispatchProfileIds.includes(worker.verificationProfileId)\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new OrchestrationProfileError(\n\t\t\t\t\t\t\t`Orchestrator '${profile.profileId}' dispatches '${worker.profileId}' but not its verifier '${worker.verificationProfileId}'.`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tregister(profile: OrchestrationProfile): void {\n\t\tvalidateOrchestrationProfile(profile);\n\t\tif (this.profiles.has(profile.profileId)) {\n\t\t\tthrow new OrchestrationProfileError(`Duplicate orchestration profile '${profile.profileId}'.`);\n\t\t}\n\t\tthis.profiles.set(profile.profileId, freezeProfile(profile));\n\t}\n\n\tget(profileId: string): OrchestrationProfile | undefined {\n\t\tconst profile = this.profiles.get(profileId);\n\t\treturn profile ? structuredClone(profile) : undefined;\n\t}\n\n\tlist(): OrchestrationProfile[] {\n\t\treturn [...this.profiles.values()].map((profile) => structuredClone(profile));\n\t}\n}\n\nexport function resolveProfileModel(\n\tprofile: OrchestrationProfile,\n\thealth: ModelHealthView,\n): OrchestrationModelBinding | undefined {\n\tif (profile.modelPolicy.mode === \"fixed\") {\n\t\tconst fixed = profile.modelPolicy.candidates[0];\n\t\treturn fixed && health.isHealthy(fixed) ? structuredClone(fixed) : undefined;\n\t}\n\tconst selected = profile.modelPolicy.candidates.find((candidate) => health.isHealthy(candidate));\n\treturn selected ? structuredClone(selected) : undefined;\n}\n\nexport function planProfileDispatch(args: {\n\trequest: OrchestrationDispatchRequest;\n\ttask: TaskContract;\n\tattemptId: string;\n\tsubjectId: string;\n\tregistry: OrchestrationProfileRegistry;\n\thealth: ModelHealthView;\n\tpolicyCompiler: ExecutionPolicyCompiler;\n\ttoolManifests: readonly ToolCapabilityManifest[];\n\tresources: readonly ResourcePointer[];\n\treadPaths: readonly string[];\n\twritePaths?: readonly string[];\n\tdeniedPaths?: readonly string[];\n\tpolicyVersion: string;\n}): ProfileDispatchPlanResult {\n\tconst profile = args.registry.get(args.request.profileId);\n\tif (!profile) return { outcome: \"deny\", decisions: [], reasonCodes: [\"profile_model_unavailable\"] };\n\tif (profile.role !== args.task.role) {\n\t\treturn { outcome: \"deny\", decisions: [], reasonCodes: [\"required_capability_exceeds_role_ceiling\"] };\n\t}\n\tconst model = resolveProfileModel(profile, args.health);\n\tif (!model) return { outcome: \"deny\", decisions: [], reasonCodes: [\"profile_model_unavailable\"] };\n\tconst selectedResources = args.resources.filter((resource) => args.request.resourcePointerIds.includes(resource.id));\n\tconst manifestsByName = new Map(args.toolManifests.map((manifest) => [manifest.toolName, manifest]));\n\tconst requestedTools = profile.toolNames.filter((toolName) => {\n\t\tconst manifest = manifestsByName.get(toolName);\n\t\treturn manifest?.capabilities.every((capability) => args.task.requiredCapabilities.includes(capability)) === true;\n\t});\n\tconst policyInput: CompileExecutionGrantInput = {\n\t\tobjectiveId: args.task.objectiveId,\n\t\ttaskId: args.task.taskId,\n\t\tattemptId: args.attemptId,\n\t\tsubjectId: args.subjectId,\n\t\trole: profile.role,\n\t\trequiredCapabilities: args.task.requiredCapabilities,\n\t\trequestedCapabilities: args.task.requiredCapabilities,\n\t\tauthorityCapabilities: profile.capabilityCeiling,\n\t\trequestedTools,\n\t\ttoolManifests: args.toolManifests,\n\t\tresources: selectedResources,\n\t\treadPaths: args.readPaths,\n\t\twritePaths: args.writePaths,\n\t\tdeniedPaths: args.deniedPaths,\n\t\trequestedBudget: profile.budget,\n\t\tauthorityBudget: profile.budget,\n\t\tpolicyVersion: args.policyVersion,\n\t};\n\tconst compiled = args.policyCompiler.compile(policyInput);\n\tif (compiled.outcome !== \"allow\") return compiled;\n\treturn { outcome: \"allow\", plan: { profile, model, grant: compiled.grant, toolManifests: compiled.toolManifests } };\n}\n"]}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { createCustomMessage } from "@caupulican/pi-agent-core";
|
|
2
|
+
import { type DiscoverPipelineOptions } from "./discover.ts";
|
|
3
|
+
import type { PipelineRun } from "./types.ts";
|
|
4
|
+
export interface ActivePipelineContext {
|
|
5
|
+
run: PipelineRun;
|
|
6
|
+
text: string;
|
|
7
|
+
}
|
|
8
|
+
/** Resolve durable run identity, definition ownership, and bounded prompt text through one path. */
|
|
9
|
+
export declare function resolveActivePipelineContext(options: DiscoverPipelineOptions, snapshot?: PipelineRun): ActivePipelineContext | undefined;
|
|
10
|
+
/** Build the optional per-turn pipeline message without leaking discovery failures into prompt admission. */
|
|
11
|
+
export declare function createActivePipelineContextMessage(args: {
|
|
12
|
+
options: DiscoverPipelineOptions;
|
|
13
|
+
snapshot?: PipelineRun;
|
|
14
|
+
onError(message: string): void;
|
|
15
|
+
}): ReturnType<typeof createCustomMessage> | undefined;
|
|
16
|
+
//# sourceMappingURL=active-context.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"active-context.d.ts","sourceRoot":"","sources":["../../../src/core/pipelines/active-context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAEhE,OAAO,EAAE,KAAK,uBAAuB,EAAmC,MAAM,eAAe,CAAC;AAE9F,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE9C,MAAM,WAAW,qBAAqB;IACrC,GAAG,EAAE,WAAW,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;CACb;AAED,oGAAoG;AACpG,wBAAgB,4BAA4B,CAC3C,OAAO,EAAE,uBAAuB,EAChC,QAAQ,CAAC,EAAE,WAAW,GACpB,qBAAqB,GAAG,SAAS,CAOnC;AAED,6GAA6G;AAC7G,wBAAgB,kCAAkC,CAAC,IAAI,EAAE;IACxD,OAAO,EAAE,uBAAuB,CAAC;IACjC,QAAQ,CAAC,EAAE,WAAW,CAAC;IACvB,OAAO,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CAC/B,GAAG,UAAU,CAAC,OAAO,mBAAmB,CAAC,GAAG,SAAS,CAgBrD"}
|