@sema-agent/core 7.58.0 → 7.59.0
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 +776 -0
- package/README.md +6 -4
- package/dist/agents/cc-peer-directory.js +8 -8
- package/dist/agents/child-model-seat.d.ts +4 -2
- package/dist/agents/child-model-seat.js +5 -3
- package/dist/agents/peer-directory.d.ts +9 -0
- package/dist/agents/peer-directory.js +6 -2
- package/dist/agents/send-message-tool.js +21 -12
- package/dist/agents/subagent.js +33 -34
- package/dist/brain/anthropic.js +161 -45
- package/dist/brain/errors.d.ts +9 -3
- package/dist/brain/errors.js +7 -1
- package/dist/brain/failover.js +2 -1
- package/dist/brain/open-responses.js +3 -3
- package/dist/brain/openai.js +103 -53
- package/dist/brain/provider-dialect.d.ts +11 -0
- package/dist/brain/provider-dialect.js +5 -2
- package/dist/brain/reasoning-request.js +5 -4
- package/dist/brain/reasoning.d.ts +19 -0
- package/dist/brain/reasoning.js +17 -2
- package/dist/brain/request-route.d.ts +4 -1
- package/dist/brain/request-route.js +4 -1
- package/dist/brain/route-adjudicator.d.ts +84 -18
- package/dist/brain/route-adjudicator.js +87 -21
- package/dist/brain/route-conformance.js +1 -1
- package/dist/brain/stream-engine.js +84 -49
- package/dist/brain/stream-shared.d.ts +30 -0
- package/dist/brain/stream-shared.js +34 -1
- package/dist/brain/timeout.d.ts +62 -5
- package/dist/brain/timeout.js +93 -6
- package/dist/core/account-row.d.ts +61 -0
- package/dist/core/account-row.js +51 -0
- package/dist/core/advisor-verdict.d.ts +2 -1
- package/dist/core/advisor-verdict.js +1 -1
- package/dist/core/allow-entry.d.ts +18 -6
- package/dist/core/allow-entry.js +16 -8
- package/dist/core/approval-object.d.ts +29 -15
- package/dist/core/approval-object.js +47 -19
- package/dist/core/auto-compaction.js +1 -1
- package/dist/core/background-agent-store.d.ts +16 -3
- package/dist/core/checkpoint-requirements.d.ts +13 -1
- package/dist/core/checkpoint-requirements.js +3 -1
- package/dist/core/checkpoint-store.d.ts +58 -12
- package/dist/core/checkpoint-store.js +18 -6
- package/dist/core/child-clamp-seats.d.ts +29 -0
- package/dist/core/child-clamp-seats.js +56 -1
- package/dist/core/compliance.d.ts +2 -2
- package/dist/core/compliance.js +1 -1
- package/dist/core/effective-path-target.d.ts +8 -2
- package/dist/core/effective-path-target.js +8 -3
- package/dist/core/engine-notice.d.ts +98 -8
- package/dist/core/engine-notice.js +19 -5
- package/dist/core/gate-fold.js +1 -1
- package/dist/core/gate-lanes.js +8 -4
- package/dist/core/gate-outcome.d.ts +32 -3
- package/dist/core/gate-outcome.js +19 -1
- package/dist/core/governance-codes.d.ts +9 -1
- package/dist/core/governance-codes.js +13 -0
- package/dist/core/hooks.d.ts +31 -3
- package/dist/core/hooks.js +5 -6
- package/dist/core/image-admission.d.ts +6 -5
- package/dist/core/image-admission.js +18 -14
- package/dist/core/locked-config.d.ts +5 -2
- package/dist/core/locked-config.js +2 -1
- package/dist/core/mailbox-store.d.ts +45 -1
- package/dist/core/mailbox-store.js +53 -9
- package/dist/core/mcp-failure.d.ts +114 -18
- package/dist/core/mcp-failure.js +63 -5
- package/dist/core/mcp-server-link.d.ts +22 -1
- package/dist/core/mcp-server-link.js +25 -1
- package/dist/core/mcp.d.ts +12 -8
- package/dist/core/mcp.js +42 -25
- package/dist/core/memory-engine/consolidation-driver.d.ts +2 -4
- package/dist/core/memory-engine/consolidation-driver.js +3 -3
- package/dist/core/memory-engine/consolidation.d.ts +4 -0
- package/dist/core/memory-engine/consolidation.js +1 -0
- package/dist/core/memory-engine/delegation-settlement.js +5 -12
- package/dist/core/memory-engine/distiller.js +2 -2
- package/dist/core/memory-engine/dual-root.d.ts +50 -1
- package/dist/core/memory-engine/dual-root.js +44 -1
- package/dist/core/memory-engine/engine.d.ts +67 -14
- package/dist/core/memory-engine/engine.js +384 -212
- package/dist/core/memory-engine/export-bundle.d.ts +23 -0
- package/dist/core/memory-engine/export-bundle.js +23 -4
- package/dist/core/memory-engine/file-backend.d.ts +128 -55
- package/dist/core/memory-engine/file-backend.js +290 -117
- package/dist/core/memory-engine/index.d.ts +1 -1
- package/dist/core/memory-engine/layout.d.ts +59 -11
- package/dist/core/memory-engine/layout.js +190 -40
- package/dist/core/memory-engine/memory-backend-contract.d.ts +1 -1
- package/dist/core/memory-engine/memory-backend-contract.js +39 -2
- package/dist/core/memory-engine/sync-client.d.ts +9 -1
- package/dist/core/memory-engine/sync-client.js +31 -8
- package/dist/core/memory-engine/sync.d.ts +5 -0
- package/dist/core/memory-engine/types.d.ts +6 -0
- package/dist/core/mods/classic-events.d.ts +5 -1
- package/dist/core/mods/kernel/dispatch.js +2 -1
- package/dist/core/mods/kernel/events.d.ts +2 -1
- package/dist/core/mods/kernel/events.js +2 -2
- package/dist/core/mods/kernel/registration.d.ts +4 -0
- package/dist/core/mods/kernel/registration.js +3 -0
- package/dist/core/mods/stations.d.ts +31 -10
- package/dist/core/mods/stations.js +44 -10
- package/dist/core/mods/tool-call.js +1 -1
- package/dist/core/parent-spec-seat.d.ts +8 -3
- package/dist/core/parent-spec-seat.js +2 -0
- package/dist/core/park-selfcheck.js +6 -0
- package/dist/core/peer-seat.d.ts +70 -8
- package/dist/core/peer-seat.js +143 -11
- package/dist/core/permission-rule-consent.js +10 -4
- package/dist/core/permission-rule-model.d.ts +16 -0
- package/dist/core/permission-rule-model.js +1 -1
- package/dist/core/present-plan-tool.d.ts +11 -3
- package/dist/core/present-plan-tool.js +2 -2
- package/dist/core/resume-startup-cause.js +1 -0
- package/dist/core/rewrite-rejudge.d.ts +1 -0
- package/dist/core/rewrite-rejudge.js +2 -2
- package/dist/core/roles.d.ts +34 -2
- package/dist/core/roles.js +43 -4
- package/dist/core/runner/announce-once-ledger.d.ts +5 -4
- package/dist/core/runner/announce-once-ledger.js +4 -2
- package/dist/core/runner/call-hook-stations.js +2 -2
- package/dist/core/runner/contracts.d.ts +20 -16
- package/dist/core/runner/credential-origin-seat.js +4 -3
- package/dist/core/runner/cwd-alignment-probe.d.ts +20 -0
- package/dist/core/runner/cwd-alignment-probe.js +21 -0
- package/dist/core/runner/decide-continuation.d.ts +2 -2
- package/dist/core/runner/gate-exit.d.ts +12 -4
- package/dist/core/runner/gate-exit.js +10 -7
- package/dist/core/runner/image-removed-seat.d.ts +12 -0
- package/dist/core/runner/image-removed-seat.js +19 -0
- package/dist/core/runner/inline-image.js +1 -1
- package/dist/core/runner/memory-consolidation-driver.js +3 -3
- package/dist/core/runner/park-commit.d.ts +1 -1
- package/dist/core/runner/park-commit.js +3 -0
- package/dist/core/runner/prepare-ask-lane.d.ts +1 -1
- package/dist/core/runner/prepare-ask-lane.js +2 -1
- package/dist/core/runner/prepare-boundary-parks.js +2 -2
- package/dist/core/runner/prepare-caps-and-workflow.d.ts +3 -5
- package/dist/core/runner/prepare-caps-and-workflow.js +2 -0
- package/dist/core/runner/prepare-config-doors.js +2 -0
- package/dist/core/runner/prepare-context-lane.js +2 -0
- package/dist/core/runner/prepare-delegation-surface.d.ts +4 -0
- package/dist/core/runner/prepare-delegation-surface.js +1 -0
- package/dist/core/runner/prepare-hands-readface.d.ts +4 -0
- package/dist/core/runner/prepare-hands-readface.js +5 -0
- package/dist/core/runner/prepare-inherited-gate.d.ts +1 -3
- package/dist/core/runner/prepare-inherited-gate.js +14 -27
- package/dist/core/runner/prepare-memory.js +10 -17
- package/dist/core/runner/prepare-park-ask.d.ts +1 -1
- package/dist/core/runner/prepare-park-ask.js +2 -1
- package/dist/core/runner/prepare-policy-chain.d.ts +3 -3
- package/dist/core/runner/prepare-policy-chain.js +16 -13
- package/dist/core/runner/prepare-project-context.d.ts +2 -2
- package/dist/core/runner/prepare-project-context.js +2 -2
- package/dist/core/runner/prepare-prompt-inputs.d.ts +1 -1
- package/dist/core/runner/prepare-prompt-inputs.js +8 -19
- package/dist/core/runner/prepare-protocol-tools.js +9 -1
- package/dist/core/runner/prepare-run-refs.d.ts +2 -3
- package/dist/core/runner/prepare-run-refs.js +4 -1
- package/dist/core/runner/prepare-task.js +4 -2
- package/dist/core/runner/prepare-wiring-manifest.d.ts +1 -1
- package/dist/core/runner/prepare-wiring-manifest.js +2 -1
- package/dist/core/runner/reply-pricing.d.ts +30 -0
- package/dist/core/runner/reply-pricing.js +19 -0
- package/dist/core/runner/resume-admission.js +4 -2
- package/dist/core/runner/resume-apply.js +6 -1
- package/dist/core/runner/resume-policy-outcome.js +5 -5
- package/dist/core/runner/role-seat-defaulted.d.ts +44 -0
- package/dist/core/runner/role-seat-defaulted.js +40 -0
- package/dist/core/runner/run-brain-sinks.js +2 -0
- package/dist/core/runner/run-identity-wiring.d.ts +2 -5
- package/dist/core/runner/run-identity-wiring.js +5 -4
- package/dist/core/runner/run-leg.d.ts +2 -0
- package/dist/core/runner/run-leg.js +37 -28
- package/dist/core/runner/run-stop-and-final-verify.js +2 -2
- package/dist/core/runner/run-terminal-adoption.d.ts +2 -5
- package/dist/core/runner/run-terminal-adoption.js +9 -3
- package/dist/core/runner/run-turn-boundary.js +77 -70
- package/dist/core/runner/runtask.d.ts +1 -1
- package/dist/core/runner/runtask.js +2 -2
- package/dist/core/runner/side-call-account.d.ts +1 -1
- package/dist/core/runner/side-call-account.js +3 -18
- package/dist/core/runner/sub-agent-deny-lists.d.ts +24 -0
- package/dist/core/runner/sub-agent-deny-lists.js +10 -0
- package/dist/core/runner/tool-end-body.js +2 -2
- package/dist/core/runner/tool-occurrence.d.ts +1 -1
- package/dist/core/runner/tool-occurrence.js +2 -2
- package/dist/core/runner/turn-attachments.d.ts +26 -22
- package/dist/core/runner/turn-attachments.js +24 -26
- package/dist/core/runner-deps.d.ts +1 -1
- package/dist/core/secret-env.d.ts +32 -2
- package/dist/core/secret-env.js +65 -3
- package/dist/core/sensitive-path-policy.js +3 -3
- package/dist/core/session-policy-store.d.ts +3 -1
- package/dist/core/session-policy-store.js +13 -9
- package/dist/core/session-store.d.ts +2 -5
- package/dist/core/side-query.d.ts +11 -1
- package/dist/core/side-query.js +9 -0
- package/dist/core/skill-grant-binding.d.ts +31 -2
- package/dist/core/skill-grant-binding.js +31 -1
- package/dist/core/skill-grant.d.ts +8 -5
- package/dist/core/skill-grant.js +6 -6
- package/dist/core/store-contracts/background-agent-store-contract.js +27 -0
- package/dist/core/store-contracts/checkpoint-store-contract.js +3 -2
- package/dist/core/store-contracts/mailbox-store-contract.js +31 -1
- package/dist/core/synthetic-read-verdict.js +2 -1
- package/dist/core/task-event.d.ts +32 -8
- package/dist/core/task-notification.js +16 -10
- package/dist/core/task-registry-agent.js +1 -0
- package/dist/core/task-registry-shared.d.ts +5 -0
- package/dist/core/task-spec.d.ts +12 -1
- package/dist/core/terminal-cause.d.ts +10 -0
- package/dist/core/tool-check-reading.d.ts +1 -0
- package/dist/core/tool-check-reading.js +3 -3
- package/dist/core/tool-policy.d.ts +16 -0
- package/dist/core/tool-roster.d.ts +112 -5
- package/dist/core/tool-roster.js +42 -1
- package/dist/core/tool-spec.d.ts +3 -1
- package/dist/core/types.d.ts +2 -2
- package/dist/core/types.js +1 -1
- package/dist/core/user-attachment.js +1 -1
- package/dist/core/wiring-manifest.d.ts +6 -3
- package/dist/engine/compaction/compaction.js +29 -3
- package/dist/engine/execution-env/node-execution-env.d.ts +4 -3
- package/dist/engine/execution-env/node-execution-env.js +9 -12
- package/dist/engine/harness/agent-harness.d.ts +25 -2
- package/dist/engine/harness/agent-harness.js +41 -12
- package/dist/engine/harness/messages.d.ts +3 -1
- package/dist/engine/harness/messages.js +3 -2
- package/dist/engine/harness/types.d.ts +8 -0
- package/dist/engine/llm/rejected-images.d.ts +46 -0
- package/dist/engine/llm/rejected-images.js +54 -0
- package/dist/engine/llm/tool-turns.d.ts +2 -1
- package/dist/engine/llm/types.d.ts +18 -7
- package/dist/engine/loop/agent-loop.d.ts +8 -0
- package/dist/engine/loop/agent-loop.js +52 -15
- package/dist/engine/loop/types.d.ts +3 -1
- package/dist/engine/session/path-to-root.d.ts +38 -0
- package/dist/engine/session/path-to-root.js +39 -0
- package/dist/engine/session/storage-base.js +4 -21
- package/dist/index.d.ts +16 -10
- package/dist/index.js +11 -7
- package/dist/internal/harness-types.d.ts +1 -1
- package/dist/internal/harness.d.ts +1 -0
- package/dist/internal/llm.d.ts +1 -0
- package/dist/orchestration/workflow-observe.d.ts +17 -1
- package/dist/orchestration/workflow-observe.js +20 -0
- package/dist/orchestration/workflow-types.d.ts +32 -7
- package/dist/orchestration/workflow.js +739 -489
- package/dist/shell/counting-pass.d.ts +50 -0
- package/dist/shell/counting-pass.js +502 -0
- package/dist/shell/lex.d.ts +4 -2
- package/dist/shell/lex.js +93 -34
- package/dist/shell/shell-words.d.ts +1 -1
- package/dist/shell/shell-words.js +7 -6
- package/dist/stores/file/mailbox-store.js +6 -10
- package/dist/tools/fs/fs-bash.d.ts +6 -0
- package/dist/tools/fs/fs-bash.js +6 -3
- package/dist/tools/fs/index.js +6 -2
- package/dist/tools/fs/program-read-model.d.ts +13 -0
- package/dist/tools/fs/program-read-model.js +15 -0
- package/dist/tools/fs/program-read-model.rows.js +1 -1
- package/dist/tools/fs/read-deny.d.ts +13 -10
- package/dist/tools/fs/read-deny.js +25 -5
- package/dist/tools/fs/read-floor.d.ts +19 -0
- package/dist/tools/fs/read-floor.js +23 -0
- package/dist/tools/fs/shell-read-check.d.ts +1 -1
- package/dist/tools/fs/shell-read-check.js +2 -1
- package/dist/tools/fs/shell-read-judge.d.ts +16 -8
- package/dist/tools/fs/shell-read-judge.js +10 -6
- package/dist/tools/fs/shell-read-plan.d.ts +6 -1
- package/dist/tools/fs/shell-read-plan.js +22 -15
- package/dist/tools/fs/shell-read-start.js +1 -0
- package/dist/tools/fs/shell-reentry-text.d.ts +15 -1
- package/dist/tools/fs/shell-reentry-text.js +25 -3
- package/dist/tools/monitor.d.ts +4 -0
- package/dist/tools/monitor.js +2 -0
- package/package.json +3 -2
- package/test/export-surface.snapshot.json +87 -1
- package/wire-changes/core-stores-sql@7.59.0.json +29 -0
- package/wire-changes/core@7.59.0.json +2459 -0
- package/wire-changes/mods-kernel@7.59.0.json +29 -0
- package/wire-changes/primitives@7.59.0.json +29 -0
|
@@ -137,9 +137,7 @@ export interface PrepareInheritedGateInput {
|
|
|
137
137
|
/** borrowed-readonly — the worktree-isolation helper (ctx seat; absent ⇒ no key). */
|
|
138
138
|
worktreeIsolation: SubagentWorktreeIsolation | undefined;
|
|
139
139
|
/** borrowed-readonly — the three run-ref primitives the ctx exposes (plan mode only under `enablePlanMode`). */
|
|
140
|
-
requestReview: (opts?:
|
|
141
|
-
reason?: string;
|
|
142
|
-
}) => void;
|
|
140
|
+
requestReview: (opts?: import("../present-plan-tool.js").ReviewRequest) => void;
|
|
143
141
|
/** borrowed-readonly — see `requestReview`. */
|
|
144
142
|
requestStopAfterTurn: () => void;
|
|
145
143
|
/** borrowed-readonly — see `requestReview`; a steer of the leg's mode seat into `plan`. */
|
|
@@ -138,37 +138,21 @@ export function prepareInheritedGate(input) {
|
|
|
138
138
|
const contentMandate = input.runtimeCaps()?.forceDurableGate === true ||
|
|
139
139
|
(spec.durableApproval !== undefined && !isLiveQuestionFace(frozenOnQuestion));
|
|
140
140
|
const ownInstallation = { chain: input.ownModChain, onAsk: frozenOnAsk, durableMandate, contentMandate, hookEnv: hookEnvSource, decider: autoModeDecider };
|
|
141
|
+
const regime = {
|
|
142
|
+
...(frozenOnAsk !== undefined ? { onAsk: frozenOnAsk } : {}),
|
|
143
|
+
...(durableMandate ? { durableMandate: true } : {}),
|
|
144
|
+
...(contentMandate ? { contentMandate: true } : {}),
|
|
145
|
+
...(autoModeDecider !== undefined
|
|
146
|
+
? { autoMode: { decider: autoModeDecider, ...(autoModeDenialTracking !== undefined ? { denialTracking: autoModeDenialTracking } : {}), ...(autoModeArming !== undefined ? { arming: autoModeArming } : {}), liveMode: legModeCeiling } }
|
|
147
|
+
: {}),
|
|
148
|
+
};
|
|
141
149
|
const hookConstraint = chainJudges(input.modBus) && !(inheritedParentConstraints ?? []).some((pc) => sameInstallation(pc, ownInstallation))
|
|
142
|
-
? [
|
|
143
|
-
{
|
|
144
|
-
policy: createPreToolUseConstraintPolicy(input.modBus, input.hookEnvFace()),
|
|
145
|
-
mods: input.ownModChain,
|
|
146
|
-
...(hookEnvSource !== undefined ? { hookEnv: hookEnvSource } : {}),
|
|
147
|
-
...(frozenOnAsk !== undefined ? { onAsk: frozenOnAsk } : {}),
|
|
148
|
-
...(durableMandate ? { durableMandate: true } : {}),
|
|
149
|
-
...(contentMandate ? { contentMandate: true } : {}),
|
|
150
|
-
...(autoModeDecider !== undefined
|
|
151
|
-
? { autoMode: { decider: autoModeDecider, ...(autoModeDenialTracking !== undefined ? { denialTracking: autoModeDenialTracking } : {}), ...(autoModeArming !== undefined ? { arming: autoModeArming } : {}), liveMode: legModeCeiling } }
|
|
152
|
-
: {}),
|
|
153
|
-
},
|
|
154
|
-
]
|
|
150
|
+
? [{ policy: createPreToolUseConstraintPolicy(input.modBus, input.hookEnvFace()), mods: input.ownModChain, ...(hookEnvSource !== undefined ? { hookEnv: hookEnvSource } : {}), ...regime }]
|
|
155
151
|
: [];
|
|
156
152
|
const parentConstraints = [
|
|
157
153
|
...(inheritedParentConstraints ?? []),
|
|
158
154
|
...hookConstraint,
|
|
159
|
-
...(ownCallerPolicy !== undefined
|
|
160
|
-
? [
|
|
161
|
-
{
|
|
162
|
-
policy: ownCallerPolicy,
|
|
163
|
-
...(frozenOnAsk !== undefined ? { onAsk: frozenOnAsk } : {}),
|
|
164
|
-
...(durableMandate ? { durableMandate: true } : {}),
|
|
165
|
-
...(contentMandate ? { contentMandate: true } : {}),
|
|
166
|
-
...(autoModeDecider !== undefined
|
|
167
|
-
? { autoMode: { decider: autoModeDecider, ...(autoModeDenialTracking !== undefined ? { denialTracking: autoModeDenialTracking } : {}), ...(autoModeArming !== undefined ? { arming: autoModeArming } : {}), liveMode: legModeCeiling } }
|
|
168
|
-
: {}),
|
|
169
|
-
},
|
|
170
|
-
]
|
|
171
|
-
: []),
|
|
155
|
+
...(ownCallerPolicy !== undefined ? [{ policy: ownCallerPolicy, ...regime }] : []),
|
|
172
156
|
];
|
|
173
157
|
return {
|
|
174
158
|
...(ancestorRules.length > 0 ? { ancestorRules } : {}),
|
|
@@ -290,7 +274,10 @@ export function prepareInheritedGate(input) {
|
|
|
290
274
|
...(internals?.insideFork === true ? { insideFork: true } : {}),
|
|
291
275
|
...(agentForkDenial !== undefined ? { forkAccess: { denied: agentForkDenial } } : {}),
|
|
292
276
|
...(observersActive ? { observersAllowed: true } : {}),
|
|
293
|
-
requestReview
|
|
277
|
+
requestReview: (opts) => requestReview({
|
|
278
|
+
...(opts?.reason !== undefined ? { reason: opts.reason } : {}),
|
|
279
|
+
...(ctx.reviveClaim === undefined && typeof ctx.toolCallId === "string" && ctx.toolCallId !== "" ? { requestedByCallId: ctx.toolCallId } : {}),
|
|
280
|
+
}),
|
|
294
281
|
requestStopAfterTurn,
|
|
295
282
|
...(spec.enablePlanMode === true ? { enterPlanMode } : {}),
|
|
296
283
|
};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { isAbsolute, sep } from "node:path";
|
|
2
2
|
import { deliverEngineNotice } from "../types.js";
|
|
3
3
|
import { admitMemoryScopes } from "../memory-admission.js";
|
|
4
|
-
import { adoptLegacyRepoDirs, canonicalize, deriveRepoControlPlaneDir, deriveProjectControlDir, deriveProjectMemoryDir, deriveRepoKey, deriveRepoMemoryDir,
|
|
5
|
-
import {
|
|
4
|
+
import { adoptLegacyRepoDirs, canonicalize, deriveRepoControlPlaneDir, deriveProjectControlDir, deriveProjectMemoryDir, deriveRepoKey, deriveRepoMemoryDir, effectiveControlRootOf, isContainedIn, lookupProjectIdHint, recordProjectIdHint, resolveMemoryEngineRoot, transferMemoryAnnouncements } from "../memory-engine/layout.js";
|
|
5
|
+
import { derivePersonalControlDir, derivePersonalMemoryDir, directoryPinOf, memoryPlaneStore, mergeHarvestReports, mergeInjections, needsDualRoots, parsedProjectPlane, scopePlanesOf } from "../memory-engine/dual-root.js";
|
|
6
6
|
import { memoryProjectScopeAbsentNotice, normalizeMemorySpec } from "../memory.js";
|
|
7
7
|
import { deriveSupersededSet } from "../memory-engine/consolidation.js";
|
|
8
8
|
import { shadowNamesOf } from "../memory-engine/shadowing.js";
|
|
@@ -12,7 +12,6 @@ import { readSessionCaptureOptOut } from "../memory-engine/layout.js";
|
|
|
12
12
|
import { sessionIncarnationResolver } from "../memory-engine/session-incarnation.js";
|
|
13
13
|
import { createMemoryEngineTools } from "../memory-engine/tools.js";
|
|
14
14
|
import { assertScopeContractPlacement, parseScopeKey } from "../memory-engine/scope-contract.js";
|
|
15
|
-
import { FileMemoryEngineBackend } from "../memory-engine/file-backend.js";
|
|
16
15
|
import { writableRootOf } from "../memory-engine/types.js";
|
|
17
16
|
import { catalogText } from "../../prompt-assembly/catalog/index.js";
|
|
18
17
|
import { asThrownError, thrownText } from "../thrown-value.js";
|
|
@@ -101,7 +100,7 @@ export async function prepareMemory(input) {
|
|
|
101
100
|
const backend = deps.memoryBackend;
|
|
102
101
|
const lineageTokens = new Map(input.captureForkOrigin !== undefined && input.captureForkOriginIncarnation !== undefined ? [[input.captureForkOrigin, input.captureForkOriginIncarnation]] : []);
|
|
103
102
|
const incarnationOpt = { sessionIncarnation: sessionIncarnationResolver(sessionId, input.sessionIncarnation, lineageTokens) };
|
|
104
|
-
const pinned = backend
|
|
103
|
+
const pinned = directoryPinOf(backend);
|
|
105
104
|
const engineRoot = resolveMemoryEngineRoot(deps.memoryEngineDir);
|
|
106
105
|
const repoRoot = deps.rootPath ?? taskRootPath;
|
|
107
106
|
if (repoRoot) {
|
|
@@ -134,11 +133,10 @@ export async function prepareMemory(input) {
|
|
|
134
133
|
try {
|
|
135
134
|
const oldCtl = deriveRepoControlPlaneDir(engineRoot, repoRoot);
|
|
136
135
|
const newCtl = deriveProjectControlDir(engineRoot, marker.projectId);
|
|
137
|
-
|
|
138
|
-
for (const ann of drained.queue)
|
|
139
|
-
enqueueMemoryAnnouncement(newCtl, ann);
|
|
136
|
+
transferMemoryAnnouncements(oldCtl, newCtl);
|
|
140
137
|
}
|
|
141
|
-
catch {
|
|
138
|
+
catch (err) {
|
|
139
|
+
deps.onError?.(asThrownError(err), { phase: "config", sessionId });
|
|
142
140
|
}
|
|
143
141
|
}
|
|
144
142
|
}
|
|
@@ -151,13 +149,9 @@ export async function prepareMemory(input) {
|
|
|
151
149
|
}
|
|
152
150
|
}
|
|
153
151
|
}
|
|
154
|
-
const memoryDir =
|
|
155
|
-
? pinned
|
|
156
|
-
: identityKey !== undefined
|
|
157
|
-
? deriveProjectMemoryDir(engineRoot, identityKey)
|
|
158
|
-
: deriveRepoMemoryDir(engineRoot, repoRoot);
|
|
152
|
+
const memoryDir = pinned ?? (identityKey !== undefined ? deriveProjectMemoryDir(engineRoot, identityKey) : deriveRepoMemoryDir(engineRoot, repoRoot));
|
|
159
153
|
const projectControlDir = identityKey !== undefined ? deriveProjectControlDir(engineRoot, identityKey) : deriveRepoControlPlaneDir(engineRoot, repoRoot);
|
|
160
|
-
const planes = memorySpec.
|
|
154
|
+
const planes = scopePlanesOf(memorySpec.scopes, memorySpec.writeScope, memorySpec.scopeContract);
|
|
161
155
|
const dual = planes !== undefined && needsDualRoots(planes);
|
|
162
156
|
const personalOnly = planes !== undefined && !dual && planes.project.length === 0 && planes.writePlane !== "project" && (planes.personal.length > 0 || planes.writePlane === "personal");
|
|
163
157
|
if (memorySpec.scopeContract === "v2" && !personalOnly) {
|
|
@@ -172,7 +166,6 @@ export async function prepareMemory(input) {
|
|
|
172
166
|
const personalMemoryDir = derivePersonalMemoryDir(engineRoot);
|
|
173
167
|
const personalControlDir = derivePersonalControlDir(engineRoot);
|
|
174
168
|
const captureStoreOpt = (dir, b, configured) => deps.memoryCaptureRecordStore !== undefined ? { captureRecordStore: deps.memoryCaptureRecordStore({ controlDir: effectiveControlRootOf(dir, { pinnedBy: b, controlDir: configured }) }) } : {};
|
|
175
|
-
const choosePersonalBackend = () => typeof pinned === "string" && pinned ? new FileMemoryEngineBackend(personalMemoryDir, { controlDir: personalControlDir }) : backend;
|
|
176
169
|
const createPersonalEngine = (personalBackend) => {
|
|
177
170
|
return {
|
|
178
171
|
engine: new MemoryEngine({ backend: personalBackend, memoryDir: personalMemoryDir, controlDir: personalControlDir, onIncident: onEngineIncident, provenance: input.memoryProvenance, ...captureStoreOpt(personalMemoryDir, personalBackend, personalControlDir), ...incarnationOpt, ...(input.deps.memoryConsolidation !== undefined ? { consolidation: input.deps.memoryConsolidation } : {}) }),
|
|
@@ -336,7 +329,7 @@ export async function prepareMemory(input) {
|
|
|
336
329
|
return {};
|
|
337
330
|
};
|
|
338
331
|
if (dual) {
|
|
339
|
-
const personalBackendChosen =
|
|
332
|
+
const personalBackendChosen = memoryPlaneStore("personal", backend, engineRoot);
|
|
340
333
|
{
|
|
341
334
|
const projCtl = effectiveControlRootOf(memoryDir, { pinnedBy: backend, controlDir: projectControlDir });
|
|
342
335
|
const persCtl = effectiveControlRootOf(personalMemoryDir, { pinnedBy: personalBackendChosen, controlDir: personalControlDir });
|
|
@@ -443,7 +436,7 @@ export async function prepareMemory(input) {
|
|
|
443
436
|
};
|
|
444
437
|
}
|
|
445
438
|
else if (personalOnly) {
|
|
446
|
-
const personal = createPersonalEngine(
|
|
439
|
+
const personal = createPersonalEngine(memoryPlaneStore("personal", backend, engineRoot));
|
|
447
440
|
const personalEngine = personal.engine;
|
|
448
441
|
await armCaptureOptOut(personalEngine);
|
|
449
442
|
const handle = await personalEngine.materialize(memorySpec.scopes, memorySpec.writeScope, { adoptionRestricted: adoptionRestricted || captureOptedOut || captureIndeterminate, sessionId });
|
|
@@ -23,7 +23,7 @@ import type { AgentHarness, AgentMessage, AgentTool, ExecutionEnv } from "../../
|
|
|
23
23
|
import { type CallTargetStamp } from "../effective-path-target.js";
|
|
24
24
|
import { type OnQuestion } from "../ask-question.js";
|
|
25
25
|
import { type CheckpointStore } from "../checkpoint-store.js";
|
|
26
|
-
import type
|
|
26
|
+
import { type GrantBindingOf } from "../skill-grant-binding.js";
|
|
27
27
|
import type { SessionStore } from "../session.js";
|
|
28
28
|
import { type OnAsk, type ToolCallRequest, type ToolPolicy } from "../tool-policy.js";
|
|
29
29
|
import { type ToolResultStore } from "../tool-result-store.js";
|
|
@@ -8,6 +8,7 @@ import { boundInputHashOf, exactBoundInputHashOf } from "../canonical-json.js";
|
|
|
8
8
|
import { buildRiskDescriptor, debitLedger, encodeAtFidelity, mintCheckpointId, mintCheckpointToken, resolveDeclaredFidelity, } from "../checkpoint-store.js";
|
|
9
9
|
import { pauseOf } from "../pause-registry.js";
|
|
10
10
|
import { samePlainValue } from "../same-plain-value.js";
|
|
11
|
+
import { requestGrantBinding } from "../skill-grant-binding.js";
|
|
11
12
|
import { askCarryRowMembers } from "../hooks.js";
|
|
12
13
|
import { askMandateMember, ownedClearanceFacts } from "../ask-origin.js";
|
|
13
14
|
import { defaultTaskRegistry } from "../task-registry.js";
|
|
@@ -171,7 +172,7 @@ export function prepareParkAsk(input) {
|
|
|
171
172
|
...callFaceSeat(req.face),
|
|
172
173
|
...(handsCwdRef !== undefined ? { cwd: handsCwdRef.current } : {}), ...(handsRoot !== undefined ? { root: handsRoot } : {}),
|
|
173
174
|
...advertisedWritableRootsSeat(advertisedWritableDirs),
|
|
174
|
-
...exemptRootsSeat(exemptRoots),
|
|
175
|
+
...exemptRootsSeat(exemptRoots), ...requestGrantBinding(grantBindingOf, req, presented.value),
|
|
175
176
|
});
|
|
176
177
|
const withReading = stampCallTarget?.(reprojectedReq(), cutSignal);
|
|
177
178
|
const reprojectedRaced = await raceSettlementAgainstSignal(withReading === undefined ? Promise.resolve(basePolicyForResumeEdit.check(reprojectedReq(), cutSignal)) : withReading.then((r) => basePolicyForResumeEdit.check(r, cutSignal)), cutSignal);
|
|
@@ -33,7 +33,7 @@ import type { RunnerDeps, RuntimeCaps, TaskSpec, ToolEffect } from "../types.js"
|
|
|
33
33
|
import type { CwdRef } from "../../tools/fs/fs-shared.js";
|
|
34
34
|
import type { ReadDenyMatcher } from "../../tools/fs/read-deny.js";
|
|
35
35
|
import { type SkillGrantLane, type SkillGrantSource, type SkillGrantTable } from "../skill-grant.js";
|
|
36
|
-
import type
|
|
36
|
+
import { type GrantBindingOf } from "../skill-grant-binding.js";
|
|
37
37
|
import type { ToolSelector } from "../tool-face.js";
|
|
38
38
|
import { type AllowEntryLane, type AllowEntryTable } from "../allow-entry.js";
|
|
39
39
|
import type { InheritedGate, IrreversibilityTier, PrepareResume, RunInternals, StopForDenialLimit } from "./contracts.js";
|
|
@@ -48,8 +48,8 @@ export interface PreparePolicyChainInput {
|
|
|
48
48
|
hostFloor: HostFloor | undefined;
|
|
49
49
|
/** borrowed-readonly — the REBOUND spec. Read: `sessionId` / `principal` (the session-rule read and the lanes' identity),
|
|
50
50
|
* `durableApproval` / `checkpointStore` (the mandate-park facility test and the sandbox arming's park prerequisites), `taskId` (the late-ask observer's detail),
|
|
51
|
-
* `tools` (the names the caller mounted, for the name audit). Never mutated. */
|
|
52
|
-
spec: Pick<TaskSpec, "sessionId" | "principal" | "durableApproval" | "taskId" | "checkpointStore" | "tools" | "excludeAllTools">;
|
|
51
|
+
* `tools` (the names the caller mounted, for the name audit), `classifyAllShell` (every allow member's auto strip). Never mutated. */
|
|
52
|
+
spec: Pick<TaskSpec, "sessionId" | "principal" | "durableApproval" | "taskId" | "checkpointStore" | "tools" | "excludeAllTools" | "classifyAllShell">;
|
|
53
53
|
/** borrowed-readonly — the deployment seats: `sessionPolicyStore` (the rule reads),
|
|
54
54
|
* `permissionRuleStore` / `localOwnerRules` (the lanes and the offer factory), `onError` / `onNotice` (the advisories,
|
|
55
55
|
* the refusal disclosures, the late-ask observer), `tracer` (the admission and rule-store frames), `checkpointStore` (the park facility). Receiver preserved;
|
|
@@ -15,10 +15,11 @@ import { approvalCardMemberOf } from "../tool-roster.js";
|
|
|
15
15
|
import { NAMESPACED_NAME_SHAPES } from "../protocol-table.js";
|
|
16
16
|
import { emitTrace } from "../trace.js";
|
|
17
17
|
import { skillGrantBindingMembers } from "../skill-grant.js";
|
|
18
|
+
import { withArgsBinding } from "../skill-grant-binding.js";
|
|
18
19
|
import { SKILL_TOOL_NAME } from "./synthetic-tools.js";
|
|
19
|
-
import { delegationPoolReading } from "./sub-agent-deny-lists.js";
|
|
20
|
+
import { delegationPoolReading, policyNameRefusal, POLICY_NAME_REFUSAL_CODE } from "./sub-agent-deny-lists.js";
|
|
20
21
|
import { valveLeaves } from "../../agents/tool-filter.js";
|
|
21
|
-
import { autoStrippedRule, cardDisclosureOf, rootFacingToolNames } from "../allow-entry.js";
|
|
22
|
+
import { autoStrippedRule, cardDisclosureOf, classifiesAllShell, rootFacingToolNames } from "../allow-entry.js";
|
|
22
23
|
import { arbitrateByMode, askClassMembersOf, askFaceOf, askMandateMember } from "../ask-origin.js";
|
|
23
24
|
import { createModeGatePolicy, mountedToolDeclaresReadOnly } from "../mode-policy.js";
|
|
24
25
|
const ancestorFacts = (ask) => ({ ...(ask ?? {}), ancestorResolved: true });
|
|
@@ -44,7 +45,8 @@ export async function preparePolicyChain(input) {
|
|
|
44
45
|
return { action: "deny", message: `refused by the ${verdict.mode} permission mode at an inherited ancestor layer (${verdict.askClass})`, decisionReason: "mode" };
|
|
45
46
|
};
|
|
46
47
|
const policy = lockedPreflight.toolPolicy;
|
|
47
|
-
const auditPolicyNames = (auditee,
|
|
48
|
+
const auditPolicyNames = (auditee, layer = "caller_policy") => {
|
|
49
|
+
const refused = [];
|
|
48
50
|
const nameGroups = toolPolicyNameSets(auditee);
|
|
49
51
|
if (nameGroups.length > 0) {
|
|
50
52
|
const known = mountedToolNames(tools);
|
|
@@ -58,7 +60,7 @@ export async function preparePolicyChain(input) {
|
|
|
58
60
|
for (const [kind, list] of [["deny", g.deny], ["ask", g.ask], ["allow", g.allow]]) {
|
|
59
61
|
for (const n of list ?? []) {
|
|
60
62
|
const verdict = judgeRuleToolName(n, known, kind);
|
|
61
|
-
const twin = verdict.kind === "current" &&
|
|
63
|
+
const twin = verdict.kind === "current" && layer !== "ancestor_session_rules" ? nearMissSpellingOf(n, rootFacing) : undefined;
|
|
62
64
|
const stale = verdict.kind !== "current" ? verdict : twin !== undefined ? { kind: "case_twin", twin, carrier: known.has(twin) || callerNames.has(twin) ? "run" : pool.names.has(twin) ? "pool" : "catalog" } : undefined;
|
|
63
65
|
if (stale !== undefined) {
|
|
64
66
|
const entry = `tool policy ${kind}-list entry "${n}"`;
|
|
@@ -81,9 +83,8 @@ export async function preparePolicyChain(input) {
|
|
|
81
83
|
return exhaustive;
|
|
82
84
|
}
|
|
83
85
|
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
throw err;
|
|
86
|
+
refused.push({ message, problem: { code: POLICY_NAME_REFUSAL_CODE, field: kind, entry: n, reason: stale.kind === "case_twin" ? "near_miss" : stale.kind, layer } });
|
|
87
|
+
continue;
|
|
87
88
|
}
|
|
88
89
|
if (known.has(n))
|
|
89
90
|
continue;
|
|
@@ -93,6 +94,8 @@ export async function preparePolicyChain(input) {
|
|
|
93
94
|
}
|
|
94
95
|
}
|
|
95
96
|
}
|
|
97
|
+
if (refused[0] !== undefined)
|
|
98
|
+
throw policyNameRefusal(refused[0], refused.slice(1));
|
|
96
99
|
const dedupeKey = [...unmatched].sort().join("|");
|
|
97
100
|
const advised = advisedPolicyNames.get(deps) ?? new Set();
|
|
98
101
|
if (unmatched.size > 0 && !advised.has(dedupeKey)) {
|
|
@@ -162,9 +165,9 @@ export async function preparePolicyChain(input) {
|
|
|
162
165
|
check: (creq) => checkToolPolicyProjection(entry, creq) ?? { action: "allow" },
|
|
163
166
|
}));
|
|
164
167
|
const narrowingLayers = [hostFloor !== undefined ? hostFloorPolicy(hostFloor) : undefined, sessionRulePolicy, ...ancestorRulePolicies, ...frozenConstraintLayers].filter((p) => p !== undefined);
|
|
165
|
-
auditPolicyNames(sessionRulePolicy);
|
|
168
|
+
auditPolicyNames(sessionRulePolicy, "session_rules");
|
|
166
169
|
for (const layer of ancestorRulePolicies)
|
|
167
|
-
auditPolicyNames(layer,
|
|
170
|
+
auditPolicyNames(layer, "ancestor_session_rules");
|
|
168
171
|
const denyNarrowingPolicy = narrowingLayers.length === 0 ? undefined : narrowingLayers.length === 1 ? narrowingLayers[0] : combinePolicies(...narrowingLayers);
|
|
169
172
|
const basePolicyForResumeEdit = lockedPreflight.basePolicyForResumeEdit ?? lockedPreflight.toolPolicy;
|
|
170
173
|
const ownChainJudges = chainJudges(modBus);
|
|
@@ -316,7 +319,7 @@ export async function preparePolicyChain(input) {
|
|
|
316
319
|
};
|
|
317
320
|
};
|
|
318
321
|
const inheritedAskEvidence = inheritedAskRuleEvidence(deps.permissionRuleStore);
|
|
319
|
-
const listFacts = { root: taskRootFinal, sessionId, liveCwd: () => handsCwdRef?.current, anchors: pathRuleAnchors.leg };
|
|
322
|
+
const listFacts = { root: taskRootFinal, sessionId, liveCwd: () => handsCwdRef?.current, anchors: pathRuleAnchors.leg, classifyAllShell: classifiesAllShell(spec) };
|
|
320
323
|
const skillGrantLane = skillGrants.lane(listFacts);
|
|
321
324
|
const allowEntryLanes = { request: allowedToolTables.request.lane(listFacts), deployment: allowedToolTables.deployment.lane(listFacts) };
|
|
322
325
|
const ruleLaneFacts = {
|
|
@@ -331,7 +334,7 @@ export async function preparePolicyChain(input) {
|
|
|
331
334
|
questionToolName: ASK_USER_QUESTION_TOOL_NAME,
|
|
332
335
|
onRevisionDefect: (message) => deps.onError?.(new Error(message), { phase: "config", sessionId }),
|
|
333
336
|
onDisclosure: (message) => emitTrace(deps.tracer, () => ({ kind: "permission.rule_store_unreadable", version: 1, taskId: hostTaskId, message, ts: Date.now() })),
|
|
334
|
-
stripsAllow: (rule, req) =>
|
|
337
|
+
stripsAllow: (rule, req) => autoStrippedRule(rule, req, permissionMode.current, listFacts.classifyAllShell),
|
|
335
338
|
};
|
|
336
339
|
const { personal: permissionRuleLane, org: permissionRuleOrgLane } = createPermissionRuleLanes({ provider: deps.permissionRuleStore, localOwnerDeclared: deps.localOwnerRules === true, principal: spec.principal, ...ruleLaneFacts, rows: personRows });
|
|
337
340
|
const ruleOffersOf = createRuleOffersOf({
|
|
@@ -382,7 +385,7 @@ export async function preparePolicyChain(input) {
|
|
|
382
385
|
else if (re.action === "allow") {
|
|
383
386
|
return onApproval(withAttestation({ action: "allow", updatedInput: editArgs, decisionReason: "mode" }, re.attestation));
|
|
384
387
|
}
|
|
385
|
-
const judged = await judgeInheritedClassifier({ liveMode: () => permissionMode.current, autoMode: read.kind === "rewritten" ? undefined : ancestorAutoMode, ask: re, req:
|
|
388
|
+
const judged = await judgeInheritedClassifier({ liveMode: () => permissionMode.current, autoMode: read.kind === "rewritten" ? undefined : ancestorAutoMode, ask: re, req: withArgsBinding(creq, editArgs), signal: csignal ?? abortController.signal, subject: "the approved edit", allowRewrite: editArgs, facts: inheritedStationFacts(creq), unavailableSeat: classifierUnavailableSeat({ station: "ancestor", ...(ancestorDecider?.timeoutMs !== undefined ? { budgetMs: ancestorDecider.timeoutMs } : {}), route: frozenApproverRoute(onAskOf), onNotice: deps.onNotice, sessionId, runId }) });
|
|
386
389
|
if (judged.kind === "allow") {
|
|
387
390
|
return onApproval(judged.result);
|
|
388
391
|
}
|
|
@@ -439,7 +442,7 @@ export async function preparePolicyChain(input) {
|
|
|
439
442
|
return settledAs(mandateUnreconstructibleDeny(creq));
|
|
440
443
|
}
|
|
441
444
|
const presentedArgs = decision.updatedInput !== undefined ? argsAsTheToolReads(creq, decision.updatedInput) : creq.args;
|
|
442
|
-
const judged = await judgeInheritedClassifier({ liveMode: () => permissionMode.current, autoMode: pc.autoMode, ask: decision, req:
|
|
445
|
+
const judged = await judgeInheritedClassifier({ liveMode: () => permissionMode.current, autoMode: pc.autoMode, ask: decision, req: withArgsBinding(creq, presentedArgs), signal: csignal ?? abortController.signal, subject: "this call", allowRewrite: decision.updatedInput, facts: inheritedStationFacts(creq), unavailableSeat: classifierUnavailableSeat({ station: "ancestor", ...(pc.autoMode?.decider.timeoutMs !== undefined ? { budgetMs: pc.autoMode.decider.timeoutMs } : {}), route: frozenApproverRoute(pc.onAsk), onNotice: deps.onNotice, sessionId, runId }) });
|
|
443
446
|
if (judged.kind === "allow")
|
|
444
447
|
return settledAs(judged.result);
|
|
445
448
|
if (judged.kind === "deny")
|
|
@@ -14,8 +14,8 @@ export interface PrepareProjectContextInput {
|
|
|
14
14
|
/** borrowed-readonly — the REBOUND spec (`spec′`). Read: `sessionId` (phase derivation + the
|
|
15
15
|
* continuation projections), `skills` (the roster), `userInvokedSkills` (the person's invoked skills — their
|
|
16
16
|
* rows are written here), `principal` (the shared-memory tools' trusted identity), `projectMemory` (the request's
|
|
17
|
-
* off switch for the seam — the config door's one reading). Never mutated. */
|
|
18
|
-
spec: Pick<TaskSpec, "sessionId" | "skills" | "userInvokedSkills" | "principal" | "excludeAllTools" | "projectMemory">;
|
|
17
|
+
* off switch for the seam — the config door's one reading), `classifyAllShell` (the Skill card's auto strip). Never mutated. */
|
|
18
|
+
spec: Pick<TaskSpec, "sessionId" | "skills" | "userInvokedSkills" | "principal" | "excludeAllTools" | "projectMemory" | "classifyAllShell">;
|
|
19
19
|
/** borrowed-readonly — trusted internals: `agentName` (seam ctx), `inheritedSkillGrants` (the parent's captured
|
|
20
20
|
* skill grant rows, seeded as `inherited`), `inheritedAllowedTools` (the parent's request entries, seeded as this leg's
|
|
21
21
|
* own). `undefined` on a standalone prepare. */
|
|
@@ -6,7 +6,7 @@ import { createSharedMemoryTools } from "../shared-memory/tools.js";
|
|
|
6
6
|
import { SHARED_MEMORY_TOOL_NAMES } from "../shared-memory/types.js";
|
|
7
7
|
import { defineTool } from "../tools.js";
|
|
8
8
|
import { readFrozenSkillGrants, seedSkillGrants, skillSeatReader } from "../skill-grant.js";
|
|
9
|
-
import { allowedToolsNotGrantedNotice, seedAllowEntryTables } from "../allow-entry.js";
|
|
9
|
+
import { allowedToolsNotGrantedNotice, classifiesAllShell, seedAllowEntryTables } from "../allow-entry.js";
|
|
10
10
|
import { deliverEngineNotice } from "../engine-notice.js";
|
|
11
11
|
import { announceMemoryNotMounted } from "./announce-once-ledger.js";
|
|
12
12
|
import { SKILL_CONTENT_MAX_CHARS, SKILL_TOOL_NAME, createSkillTool, normalizeSkills } from "./synthetic-tools.js";
|
|
@@ -110,7 +110,7 @@ export async function prepareProjectContext(input) {
|
|
|
110
110
|
}
|
|
111
111
|
roster.mount(createSkillTool(skillSpecs, skillGrants), { source: "builtin", mountedBy: "optional" });
|
|
112
112
|
}
|
|
113
|
-
const skillSeatOf = skillSeatReader(skillSpecs, mounted);
|
|
113
|
+
const skillSeatOf = skillSeatReader(skillSpecs, classifiesAllShell(spec), mounted);
|
|
114
114
|
const sharedMemoryProvider = deps.sharedMemoryStores;
|
|
115
115
|
let sharedMemoryPairMounted = false;
|
|
116
116
|
if (sharedMemoryProvider !== undefined) {
|
|
@@ -55,7 +55,7 @@ export interface PreparePromptInputsInput {
|
|
|
55
55
|
* workflow tool): drives the orchestration prompt flags. */
|
|
56
56
|
selfOrchestrationActive: boolean;
|
|
57
57
|
/** borrowed-readonly — the task's execution env: `isIsolated` for the isolation flag, `exec` for the
|
|
58
|
-
* one batched probe
|
|
58
|
+
* one batched probe (which also carries the cwd-alignment question). Never re-bound, never destroyed here. */
|
|
59
59
|
executionEnv: ExecutionEnv;
|
|
60
60
|
/** borrowed-readonly — the session's reminder mark (rides the prompt facts for the declaration). */
|
|
61
61
|
reminderMark: string;
|
|
@@ -6,6 +6,7 @@ import { isIsolated } from "../remote-env.js";
|
|
|
6
6
|
import { readDateAnchor } from "./conversation-segment.js";
|
|
7
7
|
import { probeGitStatusLane } from "./git-status-frame.js";
|
|
8
8
|
import { renderMcpInstructionsEntry } from "./turn-attachments.js";
|
|
9
|
+
import { cwdAlignmentProbe, cwdMisalignmentMessage, readCwdAlignment } from "./cwd-alignment-probe.js";
|
|
9
10
|
const ULTRA_REASONING_TIERS = new Set(["xhigh", "max"]);
|
|
10
11
|
import { compactionEnabled } from "../context-settings.js";
|
|
11
12
|
export async function preparePromptInputs(input) {
|
|
@@ -83,7 +84,7 @@ export async function preparePromptInputs(input) {
|
|
|
83
84
|
envFacts.additionalReadDirectories = [...additionalReadRootsCanonical];
|
|
84
85
|
}
|
|
85
86
|
try {
|
|
86
|
-
const probe = await executionEnv.exec('uname -s; uname -r; (git rev-parse --is-inside-work-tree 2>/dev/null || echo false); (git symbolic-ref --short -q HEAD 2>/dev/null || echo "HEAD (detached)"); (git rev-parse --show-toplevel 2>/dev/null || echo); (test -n "$(git status --porcelain 2>/dev/null | head -1)" && echo dirty || echo clean); (s=$(ps -p $$ -o comm= 2>/dev/null); s=${s##*/}; echo "${s#-}"); (test "$(git rev-parse --git-dir 2>/dev/null)" != "$(git rev-parse --git-common-dir 2>/dev/null)" && echo linked || echo main);
|
|
87
|
+
const probe = await executionEnv.exec('uname -s; uname -r; (git rev-parse --is-inside-work-tree 2>/dev/null || echo false); (git symbolic-ref --short -q HEAD 2>/dev/null || echo "HEAD (detached)"); (git rev-parse --show-toplevel 2>/dev/null || echo); (test -n "$(git status --porcelain 2>/dev/null | head -1)" && echo dirty || echo clean); (s=$(ps -p $$ -o comm= 2>/dev/null); s=${s##*/}; echo "${s#-}"); (test "$(git rev-parse --git-dir 2>/dev/null)" != "$(git rev-parse --git-common-dir 2>/dev/null)" && echo linked || echo main); ' + cwdAlignmentProbe(taskRootFinal), { cwd: envFacts.cwd, timeout: 10 });
|
|
87
88
|
if (probe.ok && probe.value.exitCode === 0) {
|
|
88
89
|
const lines = probe.value.stdout.split("\n");
|
|
89
90
|
if (lines.length >= 6) {
|
|
@@ -109,24 +110,12 @@ export async function preparePromptInputs(input) {
|
|
|
109
110
|
envFacts.shell = sh;
|
|
110
111
|
if (envFacts.isGitRepo && (lines[7] ?? "").trim() === "linked")
|
|
111
112
|
envFacts.isLinkedWorktree = true;
|
|
112
|
-
const
|
|
113
|
-
if (
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
}
|
|
119
|
-
catch {
|
|
120
|
-
return p;
|
|
121
|
-
}
|
|
122
|
-
};
|
|
123
|
-
const canonicalProbed = await canonOf(probedPwd);
|
|
124
|
-
if (canonicalProbed !== (await canonOf(envFacts.cwd))) {
|
|
125
|
-
try {
|
|
126
|
-
deps.onError?.(new Error(`execution-env cwd misalignment: task root is "${envFacts.cwd}" but the env's shell reports pwd "${canonicalProbed}" — per-exec cwd injection may be ignored on this lane (execs/artifacts can land outside the workspace root)`), { phase: "config", sessionId });
|
|
127
|
-
}
|
|
128
|
-
catch {
|
|
129
|
-
}
|
|
113
|
+
const alignment = readCwdAlignment(lines);
|
|
114
|
+
if (alignment?.verdict === "differ") {
|
|
115
|
+
try {
|
|
116
|
+
deps.onError?.(new Error(cwdMisalignmentMessage(taskRootFinal, alignment.shellPwd)), { phase: "config", sessionId });
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
130
119
|
}
|
|
131
120
|
}
|
|
132
121
|
}
|
|
@@ -4,6 +4,7 @@ import { applyMcpRosterDelta, commitMcpRosterChanges, redialMcpServer, rosterHol
|
|
|
4
4
|
import { valveLeaves, valveLeavesPeer } from "../../agents/tool-filter.js";
|
|
5
5
|
import { resourceFacesLeft } from "../mounted-mcp.js";
|
|
6
6
|
import { materializeA2aTools } from "../a2a.js";
|
|
7
|
+
import { whereToAuthorize } from "../mcp-failure.js";
|
|
7
8
|
import { deliverEngineNotice } from "../types.js";
|
|
8
9
|
import { RosterBuilder } from "../tool-roster.js";
|
|
9
10
|
import { TOOL_WIRE_NAME_MAX_CHARS } from "../tool-face.js";
|
|
@@ -30,7 +31,7 @@ export async function prepareProtocolTools(input) {
|
|
|
30
31
|
const leaves = valveLeaves(spec, toolFaceSnapshot.selector);
|
|
31
32
|
const resourcesReached = resourceFacesLeft(leaves);
|
|
32
33
|
const mcp = lockedPreflight.mcp?.length
|
|
33
|
-
? await materializeLegMcpTools(input.mcpRequestMeta, lockedPreflight.mcp, spec.principal, deps.onElicit, deps.mcpImageResizer, { reminderMark, counts: reminderDisclosureCounts }, mcpRevocationWiring(deps, runId), mcpPool === undefined ? undefined : { pool: mcpPool.pool, ownsPool: mcpPool.owned }, sectionDisposerOf(input.modBus, abortController.signal), (entry) => resourcesReached || serverReached(mintNamespacePrefix(MCP_NAMESPACE, entry.name)), AbortSignal.any([abortController.signal, ...(spec.signal !== undefined ? [spec.signal] : [])]), hostFloor, deps.peerSeat)
|
|
34
|
+
? await materializeLegMcpTools(input.mcpRequestMeta, lockedPreflight.mcp, spec.principal, deps.onElicit, deps.mcpImageResizer, { reminderMark, counts: reminderDisclosureCounts }, mcpRevocationWiring(deps, runId), mcpPool === undefined ? undefined : { pool: mcpPool.pool, ownsPool: mcpPool.owned }, sectionDisposerOf(input.modBus, abortController.signal), (entry) => resourcesReached || serverReached(mintNamespacePrefix(MCP_NAMESPACE, entry.name)), AbortSignal.any([abortController.signal, ...(spec.signal !== undefined ? [spec.signal] : [])]), hostFloor, deps.peerSeat, mcpAuthorizationNotice(deps, sessionId, runId, spec.principal))
|
|
34
35
|
:
|
|
35
36
|
{ tools: [], toolAxes: [], warnings: [], serverInstructions: [], instructionsDelta: { pendingAdds: [], pendingRemovals: [] }, droppedTools: [], statuses: [], refresh: async () => [], reconnect: async (server) => ({ server, prefix: mintNamespacePrefix(MCP_NAMESPACE, server), outcome: "not_declared", reason: "this task declared no MCP servers", toolCount: 0, added: [], removed: [] }), dispose: async () => { } };
|
|
36
37
|
if (lockedPreflight.mcp?.length)
|
|
@@ -187,6 +188,13 @@ export async function prepareProtocolTools(input) {
|
|
|
187
188
|
foldProtocolAxes(a2a.toolAxes, "A2A");
|
|
188
189
|
return { mcp, a2a, rebuildHarnessToolsRef, contentOriginWrapRef, toolCallGateArmedRef, ...(mcpRedial !== undefined ? { mcpRedial } : {}) };
|
|
189
190
|
}
|
|
191
|
+
function mcpAuthorizationNotice(deps, sessionId, runId, principal) {
|
|
192
|
+
return (server, { reason, authorizeUrl }) => deliverEngineNotice(deps.onNotice, {
|
|
193
|
+
code: "mcp.authorization_required",
|
|
194
|
+
message: `MCP server "${server}" needs the user's authorization before it serves them (${reason}) — authorize it ${whereToAuthorize(authorizeUrl)}; its tools are unavailable until then.`,
|
|
195
|
+
detail: { server, reason, ...(authorizeUrl !== undefined ? { authorizeUrl } : {}), ...(principal !== undefined ? { principal } : {}), sessionId, runId },
|
|
196
|
+
});
|
|
197
|
+
}
|
|
190
198
|
function mcpRevocationWiring(deps, runId) {
|
|
191
199
|
if (deps.mcpRevocations === undefined)
|
|
192
200
|
return undefined;
|
|
@@ -21,6 +21,7 @@ import { SubagentRetainLedger } from "../../agents/retain-ledger.js";
|
|
|
21
21
|
import type { TaskEvent, TaskSpec } from "../types.js";
|
|
22
22
|
import { SkillGrantTable } from "../skill-grant.js";
|
|
23
23
|
import type { Prepared, RunInternals, ToolProgressLane } from "./contracts.js";
|
|
24
|
+
import type { ReviewRequest } from "../present-plan-tool.js";
|
|
24
25
|
import type { PermissionModeController } from "../mode-policy.js";
|
|
25
26
|
import { type EditedFilesLedger } from "./edited-files-ledger.js";
|
|
26
27
|
import { type ToolOccurrenceTable } from "./tool-occurrence.js";
|
|
@@ -78,9 +79,7 @@ export interface PrepareRunRefsResult {
|
|
|
78
79
|
* `plan_review` checkpoint is minted. */
|
|
79
80
|
reviewRequestRef: Prepared["reviewRequestRef"];
|
|
80
81
|
/** owned — the ctx primitive that arms `reviewRequestRef`. */
|
|
81
|
-
requestReview: (opts?:
|
|
82
|
-
reason?: string;
|
|
83
|
-
}) => void;
|
|
82
|
+
requestReview: (opts?: ReviewRequest) => void;
|
|
84
83
|
/** borrowed-mutable — the stop-after-turn latch (`Prepared.stopRequestedRef`). Writers: `requestStopAfterTurn`
|
|
85
84
|
* here, and nothing else; the run loop reads it at a turn boundary. */
|
|
86
85
|
stopRequestedRef: Prepared["stopRequestedRef"];
|
|
@@ -30,7 +30,10 @@ export function prepareRunRefs(input) {
|
|
|
30
30
|
const reviewRequestRef = {};
|
|
31
31
|
const requestReview = (opts) => {
|
|
32
32
|
if (reviewRequestRef.pending === undefined) {
|
|
33
|
-
reviewRequestRef.pending =
|
|
33
|
+
reviewRequestRef.pending = {
|
|
34
|
+
...(opts?.reason !== undefined ? { reason: opts.reason } : {}),
|
|
35
|
+
...(opts?.requestedByCallId !== undefined ? { requestedByCallId: opts.requestedByCallId } : {}),
|
|
36
|
+
};
|
|
34
37
|
}
|
|
35
38
|
};
|
|
36
39
|
const stopRequestedRef = { current: false };
|
|
@@ -77,6 +77,7 @@ export { DEFAULT_IRREVERSIBLE_SCOPE, checkpointScopeOf, placementValueOrAbsent }
|
|
|
77
77
|
export { mcpManifestEntries } from "./prepare-wiring-manifest.js";
|
|
78
78
|
import { compactionSummaryFallback, compactionSummaryIsDerived } from "./derived-route-fallback.js";
|
|
79
79
|
import { prepareAdvisor } from "./prepare-advisor.js";
|
|
80
|
+
import { announceRoleSeatsDefaulted } from "./role-seat-defaulted.js";
|
|
80
81
|
import { prepareProtocolTools } from "./prepare-protocol-tools.js";
|
|
81
82
|
import { prepareQuestionFace } from "./prepare-question-face.js";
|
|
82
83
|
import { prepareLsp } from "./prepare-lsp.js";
|
|
@@ -350,6 +351,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
|
|
|
350
351
|
await holdSessionLock?.(sessionId);
|
|
351
352
|
const onceLedger = await loadAnnounceOnceLedger(session, resume?.seed.announcedListings, deps.onError);
|
|
352
353
|
const hostTaskId = spec.taskId ?? sessionId;
|
|
354
|
+
announceRoleSeatsDefaulted({ spec, deps, onceLedger, rootLeg: !delegation.isDelegatedChild, sessionId, runId });
|
|
353
355
|
const placementRootResolved = (internals = restorePlacementRoot(internals, resume?.seed.placementRootSessionId))?.placementRoot ?? internals?.rootSessionId ?? sessionId;
|
|
354
356
|
const effectiveCompModel = compactionSummaryIsDerived(spec.compactionModel !== undefined, compModel) ? await compactionSummaryFallback({ derived: compModel, primary: model, brain: deps.brain, getApiKeyAndHeaders: spec.getApiKeyAndHeaders, onNotice: deps.onNotice, sessionId, runId }) : compModel;
|
|
355
357
|
warnCompactionWindowHazard(deps.tracer, spec, model, effectiveCompModel, hostTaskId, runnerSelf?.contextOverlayOf?.(resolvedRole.modelRef));
|
|
@@ -634,7 +636,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
|
|
|
634
636
|
const modelFileReaderSeat = {};
|
|
635
637
|
const handsReadFaceInput = { permissionMode, denyRuleRows: effectivePathDenyRules, headLeads, writeTargetJudge: () => writeTargetJudgeRef.current, personRows, handsEnabled, executionEnv, taskRootFinal, taskRootCanonical, rebaseRestoredPath, resume, session, sessionId, hostTaskId, taskScope, fullShellReachable, effectiveShellGate, toolFaceSnapshot, model, spec, deps, internals, memoryWriteGate, ...(advertisedWritableDirs !== undefined ? { advertisedWritableDirs } : {}), firstPartyOffload, roster, egressTools, irreversibilityTier, irreversibleTools, reversibilityProbes, reminderMark, reminderDisclosureCounts, modelFileReaderSeat, ...(trackFileEdit !== undefined ? { trackFileEdit } : {}), onFileEdited: noteFileEdited, harnessRef, toolProgressRef, toolOccurrences, writeLocation };
|
|
636
638
|
const handsReadFace = handsEnabled ? await prepareHandsMount(handsReadFaceInput) : resolveHandsLessReadFace(handsReadFaceInput);
|
|
637
|
-
const { readFileStateForCheckpoint, seedContextFiles, handsCwdRef, workspaceStateSettle, wsSnapshot, rebaseWsPath, backgroundTaskToolsActive, shellReadCheck, shellReadAdmission, shellReadLandings, additionalRootsCanonical, attachmentRootCanonical, readDenyMatcher, readRoots, pathTables, envHandToolNames, sealReadStateSeat } = handsReadFace;
|
|
639
|
+
const { readFileStateForCheckpoint, seedContextFiles, handsCwdRef, workspaceStateSettle, wsSnapshot, rebaseWsPath, backgroundTaskToolsActive, shellReadCheck, shellReadAdmission, shellReadFloor, shellReadLandings, additionalRootsCanonical, attachmentRootCanonical, readDenyMatcher, readRoots, pathTables, envHandToolNames, sealReadStateSeat } = handsReadFace;
|
|
638
640
|
resolvedReadFace = handsReadFace.resolvedReadFace;
|
|
639
641
|
resolvedWriteFace = handsReadFace.resolvedWriteFace;
|
|
640
642
|
readDenyAdditionsNormalized = handsReadFace.readDenyAdditionsNormalized;
|
|
@@ -642,7 +644,7 @@ export async function prepareTask(request, deps, sessions, resume, internals, ru
|
|
|
642
644
|
handsLessResolvedWriteFace = handsReadFace.handsLessResolvedWriteFace;
|
|
643
645
|
shellGatedTools = handsReadFace.shellGatedTools;
|
|
644
646
|
await armAutoMode();
|
|
645
|
-
const { worktreeSessionRef } = prepareDelegationSurface({ spec, deps, internals, resume, sessionId, hostTaskId, taskScope, taskRootFinal, taskRootCanonical, executionEnv, runnerSelf, backgroundTaskToolsActive, shellReadAdmission, workflowToolsActive, peerLaneActive, peerSendMessageBuiltIn, peerLaneRefs, sessionBox, roster, toolEffects, axisExplicitNegatives, envHandToolNames, toolFaceSnapshot, firstPartyOffload, offloadStore, subagentRetain, enrichSpecToolCtx, checkpointSeat, handsCwdRef, wsSnapshot, rebaseWsPath, rebaseRestoredPath, workspaceStateSettle, worktreeSeat });
|
|
647
|
+
const { worktreeSessionRef } = prepareDelegationSurface({ spec, deps, internals, resume, sessionId, hostTaskId, taskScope, taskRootFinal, taskRootCanonical, executionEnv, runnerSelf, backgroundTaskToolsActive, shellReadAdmission, shellReadFloor, workflowToolsActive, peerLaneActive, peerSendMessageBuiltIn, peerLaneRefs, sessionBox, roster, toolEffects, axisExplicitNegatives, envHandToolNames, toolFaceSnapshot, firstPartyOffload, offloadStore, subagentRetain, enrichSpecToolCtx, checkpointSeat, handsCwdRef, wsSnapshot, rebaseWsPath, rebaseRestoredPath, workspaceStateSettle, worktreeSeat });
|
|
646
648
|
const { liveQuestionFace, contentAskBindings, contentAskRoutable, lateStrandedAnswers, discloseStrandedAnswers, settleContentAskBindings, durableQuestionFace, questionToolMounted, mountedQuestionTool } = prepareQuestionFace({ frozenOnQuestion, spec, deps, checkpointStore, runtimeCaps, resolvedInteractionPosture, resume, sessionId, roster, toolFaceSnapshot, inheritedUnavailableAsks: () => inheritedUnavailableAsks });
|
|
647
649
|
if (spec.handsReadOnly !== true) {
|
|
648
650
|
const sessionScope = sessionId ?? spec.principal ?? spec.taskId ?? "default";
|
|
@@ -217,7 +217,7 @@ export interface PrepareWiringManifestResult {
|
|
|
217
217
|
* · a status `connected` ⇒ `connected` with the server's tools among `rosterNames` — the names of the roster the row is read
|
|
218
218
|
* against: a run's (the valve and the deployment's overlay applied), or the no-run probe's own dials (no run, so no lists apply);
|
|
219
219
|
* · a status `failed` ⇒ `failed` with the failure record the materialization stamped (`errorCode`/`delivered`/
|
|
220
|
-
* `httpStatus` = the MCP vocabulary's `McpFailure` spread flat) and the remote text SECRET-REDACTED (an HTTP endpoint's error body rides the SDK's message
|
|
220
|
+
* `httpStatus`/`authorization` = the MCP vocabulary's `McpFailure` spread flat, copied by its one projection `failureFields`) and the remote text SECRET-REDACTED (an HTTP endpoint's error body rides the SDK's message
|
|
221
221
|
* verbatim, and a body that echoes the bearer it rejected must not reach a stream consumer),
|
|
222
222
|
* then neutralized + bounded to the reminder's own 240 (the same bound the once-per-session
|
|
223
223
|
* ledger applies to that text — one face, one width);
|
|
@@ -3,6 +3,7 @@ import { teamRoleOf } from "../../agents/team-role.js";
|
|
|
3
3
|
import { resolveCheckpointStore } from "../checkpoint-store.js";
|
|
4
4
|
import { createHookEnvCapabilities, mintHookInvocationIdentity } from "../hooks.js";
|
|
5
5
|
import { chainJudges } from "../mods/stations.js";
|
|
6
|
+
import { failureFields } from "../mcp-failure.js";
|
|
6
7
|
import { toolNamesOfServer } from "../mounted-mcp.js";
|
|
7
8
|
import { isRemoteExecutionEnv, missingRestoreSurface } from "../remote-env.js";
|
|
8
9
|
import { isVolatileOffloadStore } from "../tool-result-store.js";
|
|
@@ -28,7 +29,7 @@ export function mcpManifestEntries(entries, statuses, rosterNames) {
|
|
|
28
29
|
...source,
|
|
29
30
|
status: "failed",
|
|
30
31
|
...liveness,
|
|
31
|
-
...(status
|
|
32
|
+
...failureFields(status),
|
|
32
33
|
...(status.error !== undefined ? { error: inlineUntrusted(status.error, 240) } : {}),
|
|
33
34
|
toolCount: 0,
|
|
34
35
|
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Model, Usage } from "../../internal/llm.js";
|
|
2
|
+
import { type ModelPricing } from "../pricing.js";
|
|
3
|
+
import type { RunnerDeps } from "../types.js";
|
|
4
|
+
/** One reply's usage priced by the engine: the model that served it, its price table, whether a table exists at all, and the
|
|
5
|
+
* re-priced figures. */
|
|
6
|
+
export interface PricedReply {
|
|
7
|
+
readonly served: Model | undefined;
|
|
8
|
+
readonly modelId: string;
|
|
9
|
+
readonly price: ModelPricing;
|
|
10
|
+
/** A price table EXISTS for the serving model (`isModelPriced`'s predicate): `false` ⇒ `costMicroUsd` is a fabricated 0 — unknown, not free. */
|
|
11
|
+
readonly priced: boolean;
|
|
12
|
+
readonly totalInputTokens: number;
|
|
13
|
+
readonly uncachedInputTokens: number;
|
|
14
|
+
readonly costMicroUsd: number;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* THE one place a model call made BESIDE the main loop is priced — the run's side-call lanes (`recordSideCallUsage`) and
|
|
18
|
+
* `Runner.sideQuery`'s account line both read it, so a run's reported cost and a side query's cost are the same arithmetic. The
|
|
19
|
+
* call's model prices independently of the main loop's telemetry state. A degrading brain may have served the reply from its
|
|
20
|
+
* fallback: the model that ANSWERED is the one priced (the main loop re-points its pricing at it the same way). A fallback the
|
|
21
|
+
* catalog does not know prices from the deployment's table by id when that has one, else as unpriced spend, and takes the cache
|
|
22
|
+
* family that never undercounts.
|
|
23
|
+
*/
|
|
24
|
+
export declare function priceReply(usage: Usage, call: {
|
|
25
|
+
readonly model: Model;
|
|
26
|
+
readonly servedBy?: string;
|
|
27
|
+
}, seats: {
|
|
28
|
+
readonly pricing: RunnerDeps["pricing"];
|
|
29
|
+
readonly catalog: RunnerDeps["models"];
|
|
30
|
+
}): PricedReply;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { isModelPriced, modelCostToPricing } from "../pricing.js";
|
|
2
|
+
import { cacheFamilyOf, usageCostMicroUsd } from "./usage-accounting.js";
|
|
3
|
+
function catalogModel(id, catalog) {
|
|
4
|
+
if (catalog === undefined)
|
|
5
|
+
return undefined;
|
|
6
|
+
for (const m of Object.values(catalog))
|
|
7
|
+
if (m.id === id)
|
|
8
|
+
return m;
|
|
9
|
+
return Object.hasOwn(catalog, id) ? catalog[id] : undefined;
|
|
10
|
+
}
|
|
11
|
+
export function priceReply(usage, call, seats) {
|
|
12
|
+
const { pricing, catalog } = seats;
|
|
13
|
+
const served = call.servedBy === undefined ? call.model : catalogModel(call.servedBy, catalog);
|
|
14
|
+
const modelId = served?.id ?? call.servedBy ?? call.model.id;
|
|
15
|
+
const price = pricing?.[modelId] ?? modelCostToPricing(served?.cost);
|
|
16
|
+
const priced = served !== undefined ? isModelPriced(served, pricing) : pricing?.[modelId] !== undefined;
|
|
17
|
+
const family = served !== undefined ? cacheFamilyOf(served) : "input-excludes-cached";
|
|
18
|
+
return { served, modelId, price, priced, ...usageCostMicroUsd(family, usage, price) };
|
|
19
|
+
}
|