@full-self-browsing/lattice 1.4.0 → 1.5.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.
Files changed (108) hide show
  1. package/dist/agent-run-C6miAzwI.d.ts +45 -0
  2. package/dist/agent-run-C6miAzwI.d.ts.map +1 -0
  3. package/dist/agent-run-CgPVFl0Z.js +47 -0
  4. package/dist/agent-run-CgPVFl0Z.js.map +1 -0
  5. package/dist/agents.d.ts +5 -0
  6. package/dist/agents.js +6 -0
  7. package/dist/artifact-Bg6mJGnm.d.ts +125 -0
  8. package/dist/artifact-Bg6mJGnm.d.ts.map +1 -0
  9. package/dist/artifact-DOfpeXLb.js +140 -0
  10. package/dist/artifact-DOfpeXLb.js.map +1 -0
  11. package/dist/artifacts.d.ts +2 -0
  12. package/dist/artifacts.js +2 -0
  13. package/dist/audit.d.ts +3 -0
  14. package/dist/audit.js +4 -0
  15. package/dist/catalog-CAfYwB_-.js +91 -0
  16. package/dist/catalog-CAfYwB_-.js.map +1 -0
  17. package/dist/context-pack-Bz3GXmjv.js +99 -0
  18. package/dist/context-pack-Bz3GXmjv.js.map +1 -0
  19. package/dist/context.d.ts +2 -0
  20. package/dist/context.js +2 -0
  21. package/dist/contract-S3oJGlc9.d.ts +74 -0
  22. package/dist/contract-S3oJGlc9.d.ts.map +1 -0
  23. package/dist/core.d.ts +48 -0
  24. package/dist/core.d.ts.map +1 -0
  25. package/dist/core.js +95 -0
  26. package/dist/core.js.map +1 -0
  27. package/dist/errors-eEuEIx6X.js +407 -0
  28. package/dist/errors-eEuEIx6X.js.map +1 -0
  29. package/dist/eval.d.ts +2 -0
  30. package/dist/eval.js +2 -0
  31. package/dist/fingerprint-DodDbQKN.js +34 -0
  32. package/dist/fingerprint-DodDbQKN.js.map +1 -0
  33. package/dist/index-DpnHGHVL.d.ts +53 -0
  34. package/dist/index-DpnHGHVL.d.ts.map +1 -0
  35. package/dist/index.d.ts +90 -3533
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +26 -15968
  38. package/dist/index.js.map +1 -1
  39. package/dist/infer-DLqp5QIM.d.ts +96 -0
  40. package/dist/infer-DLqp5QIM.d.ts.map +1 -0
  41. package/dist/lineage-DBgoPWAZ.js +137 -0
  42. package/dist/lineage-DBgoPWAZ.js.map +1 -0
  43. package/dist/local-CXOGPJ1f.js +139 -0
  44. package/dist/local-CXOGPJ1f.js.map +1 -0
  45. package/dist/local-Dy--7peL.d.ts +10 -0
  46. package/dist/local-Dy--7peL.d.ts.map +1 -0
  47. package/dist/memory-CkQEW6m5.js +62 -0
  48. package/dist/memory-CkQEW6m5.js.map +1 -0
  49. package/dist/memory-DRig5EHV.d.ts +10 -0
  50. package/dist/memory-DRig5EHV.d.ts.map +1 -0
  51. package/dist/negotiate-ClD88hkc.js +10967 -0
  52. package/dist/negotiate-ClD88hkc.js.map +1 -0
  53. package/dist/otel-BgM4e55_.d.ts +421 -0
  54. package/dist/otel-BgM4e55_.d.ts.map +1 -0
  55. package/dist/permission-context-CUKMo79F.js +134 -0
  56. package/dist/permission-context-CUKMo79F.js.map +1 -0
  57. package/dist/plan-DFm8Llep.js +125 -0
  58. package/dist/plan-DFm8Llep.js.map +1 -0
  59. package/dist/preflight-DNHWuJ46.d.ts +64 -0
  60. package/dist/preflight-DNHWuJ46.d.ts.map +1 -0
  61. package/dist/provider-C2IfKsvz.d.ts +1178 -0
  62. package/dist/provider-C2IfKsvz.d.ts.map +1 -0
  63. package/dist/providers.d.ts +4 -0
  64. package/dist/providers.js +4 -0
  65. package/dist/rate-limit-group-nDsBJqSu.d.ts +235 -0
  66. package/dist/rate-limit-group-nDsBJqSu.d.ts.map +1 -0
  67. package/dist/receipt-FYouoPHv.js +205 -0
  68. package/dist/receipt-FYouoPHv.js.map +1 -0
  69. package/dist/replay-CtIhpLek.js +964 -0
  70. package/dist/replay-CtIhpLek.js.map +1 -0
  71. package/dist/result-DLEx2WvU.d.ts +38 -0
  72. package/dist/result-DLEx2WvU.d.ts.map +1 -0
  73. package/dist/router-DU4Z3pTd.js +314 -0
  74. package/dist/router-DU4Z3pTd.js.map +1 -0
  75. package/dist/router-Yo1-aDOv.d.ts +42 -0
  76. package/dist/router-Yo1-aDOv.d.ts.map +1 -0
  77. package/dist/routing.d.ts +6 -0
  78. package/dist/routing.js +4 -0
  79. package/dist/{run-crew-CKdBjh5P.js → run-crew-B2fQLmgB.js} +7 -136
  80. package/dist/run-crew-B2fQLmgB.js.map +1 -0
  81. package/dist/run-crew-Bnve5dyI.d.ts +721 -0
  82. package/dist/run-crew-Bnve5dyI.d.ts.map +1 -0
  83. package/dist/{runtime-D25ehzCj.js → runtime-Dxiet5YS.js} +98 -641
  84. package/dist/runtime-Dxiet5YS.js.map +1 -0
  85. package/dist/scaffolds-DKQrCRqh.d.ts +535 -0
  86. package/dist/scaffolds-DKQrCRqh.d.ts.map +1 -0
  87. package/dist/scaffolds-ekPIlBeU.js +3139 -0
  88. package/dist/scaffolds-ekPIlBeU.js.map +1 -0
  89. package/dist/schema-CNfa_VEy.d.ts +15 -0
  90. package/dist/schema-CNfa_VEy.d.ts.map +1 -0
  91. package/dist/storage-DJKmsaEI.d.ts +26 -0
  92. package/dist/storage-DJKmsaEI.d.ts.map +1 -0
  93. package/dist/storage.d.ts +10 -0
  94. package/dist/storage.d.ts.map +1 -0
  95. package/dist/storage.js +4 -0
  96. package/dist/tool-call-validation-BFoXkwbf.js +107 -0
  97. package/dist/tool-call-validation-BFoXkwbf.js.map +1 -0
  98. package/dist/tools-C4wHgGKQ.js +49 -0
  99. package/dist/tools-C4wHgGKQ.js.map +1 -0
  100. package/dist/tools.d.ts +46 -0
  101. package/dist/tools.d.ts.map +1 -0
  102. package/dist/tools.js +106 -0
  103. package/dist/tools.js.map +1 -0
  104. package/dist/validate-c7EL5uuH.js +224 -0
  105. package/dist/validate-c7EL5uuH.js.map +1 -0
  106. package/package.json +99 -2
  107. package/dist/run-crew-CKdBjh5P.js.map +0 -1
  108. package/dist/runtime-D25ehzCj.js.map +0 -1
@@ -0,0 +1,421 @@
1
+ import { Bt as ContextSummarizer, Qt as ExecutionPlan, T as Usage, Tt as TripwireEvidence, W as TrainingClass, bn as RunEventSink, ct as ToolDefinition, d as ProviderRunRequest, ln as UsageRecord, mn as OutputContractMap, qt as SessionRef, sn as RouteRejectReason, vn as RunEvent } from "./provider-C2IfKsvz.js";
2
+ import { F as LatticeConfig, f as AgentIntent, h as DefaultAgentOutputs, n as CrewResult, p as AgentResult, r as RunAgentCrewOptions } from "./run-crew-Bnve5dyI.js";
3
+ import { r as ArtifactInput, s as ArtifactRef, x as PolicySpec } from "./artifact-Bg6mJGnm.js";
4
+ import { a as KeyEntry, c as ReceiptEnvelope, d as ReceiptRoute, i as ContractVerdict, l as ReceiptModel, n as InferOutputMap, o as KeySet, p as ReceiptSigner, y as VerifyResult } from "./infer-DLqp5QIM.js";
5
+ import { n as CapabilityContract } from "./contract-S3oJGlc9.js";
6
+ import { n as RunResult } from "./result-DLEx2WvU.js";
7
+
8
+ //#region src/receipts/receipt.d.ts
9
+ /**
10
+ * Public input to createReceipt. Mirrors CapabilityReceiptBody minus:
11
+ * - `version` (forced to "lattice-receipt/v1.3" per Phase 46)
12
+ * - `kid` (forced from signer.kid — caller cannot mismatch)
13
+ * - `redactions[]` (populated by redactReceiptBody)
14
+ * - `usage.costUsd` (converted to canonical string by usageToCanonical)
15
+ *
16
+ * receiptId and issuedAt default to runtime-generated values when omitted.
17
+ * redactionPolicyId defaults to DEFAULT_REDACTION_POLICY_ID.
18
+ */
19
+ interface CreateReceiptInput {
20
+ readonly runId: string;
21
+ readonly issuedAt?: string;
22
+ readonly receiptId?: string;
23
+ readonly model: ReceiptModel;
24
+ readonly route: ReceiptRoute;
25
+ readonly modelClass?: TrainingClass;
26
+ readonly parentReceiptCid?: string;
27
+ readonly lineageMerkleRoot?: string;
28
+ readonly usage: Usage;
29
+ readonly contractVerdict: ContractVerdict;
30
+ readonly contractHash: string | null;
31
+ readonly inputHashes: readonly string[];
32
+ readonly outputHash: string | null;
33
+ readonly redactionPolicyId?: string;
34
+ readonly noRouteReasons?: readonly RouteRejectReason[];
35
+ readonly tripwireEvidence?: TripwireEvidence;
36
+ readonly stepName?: string;
37
+ readonly stepIndex?: number;
38
+ readonly parentStepName?: string;
39
+ readonly previousStepName?: string;
40
+ readonly sessionId?: string;
41
+ readonly timestamp?: string;
42
+ }
43
+ /**
44
+ * Build, redact, canonicalize, sign, and envelope a CapabilityReceipt.
45
+ *
46
+ * Ordering INVARIANT (09-CONTEXT.md, PITFALLS.md Pitfall #1):
47
+ * redact -> canonicalize -> PAE -> sign -> encode
48
+ *
49
+ * The signed digest commits to canonicalize(redact(body)). The function
50
+ * structure makes any other ordering impossible to write by accident —
51
+ * canonicalizeReceiptBody is ONLY called on the output of redactReceiptBody.
52
+ *
53
+ * Defense in depth:
54
+ * - body.kid is assigned from signer.kid, never from input (input has no
55
+ * kid field). The signed body and the envelope keyid CANNOT disagree by
56
+ * construction.
57
+ * - signer.kid is also written to envelope.signatures[0].keyid, so the
58
+ * verifier can cross-check (Step 7 of verifyReceipt).
59
+ *
60
+ * I-JSON guarantees: usage.costUsd is converted to string (or null) via
61
+ * usageToCanonical. Receipts NEVER carry raw floats in the canonical form.
62
+ */
63
+ declare function createReceipt(input: CreateReceiptInput, signer: ReceiptSigner): Promise<ReceiptEnvelope>;
64
+ //#endregion
65
+ //#region src/runtime/create-ai.d.ts
66
+ interface RuntimeOverrides {
67
+ readonly provider?: string;
68
+ readonly model?: string;
69
+ readonly routingPolicy?: PolicySpec;
70
+ readonly tokenBudget?: number;
71
+ readonly summarizer?: ContextSummarizer;
72
+ readonly transforms?: readonly RuntimeArtifactTransform[];
73
+ readonly hooks?: RuntimeHooks;
74
+ }
75
+ interface RuntimeArtifactTransform {
76
+ readonly name: string;
77
+ transform(input: {
78
+ readonly task: string;
79
+ readonly artifacts: readonly ArtifactInput[];
80
+ }): Promise<ArtifactInput | readonly ArtifactInput[]> | ArtifactInput | readonly ArtifactInput[];
81
+ }
82
+ interface RuntimeHooks {
83
+ readonly beforeProviderCall?: (input: {
84
+ readonly plan: ExecutionPlan;
85
+ readonly request: ProviderRunRequest;
86
+ }) => void | Promise<void>;
87
+ readonly afterProviderCall?: (input: {
88
+ readonly plan: ExecutionPlan;
89
+ readonly response: unknown;
90
+ }) => void | Promise<void>;
91
+ }
92
+ interface RunIntent<TOutputs extends OutputContractMap> {
93
+ readonly task: string;
94
+ readonly artifacts?: readonly ArtifactInput[];
95
+ readonly outputs: TOutputs;
96
+ readonly policy?: PolicySpec;
97
+ readonly session?: SessionRef;
98
+ readonly signal?: AbortSignal;
99
+ readonly overrides?: RuntimeOverrides;
100
+ readonly tools?: readonly ToolDefinition<any>[];
101
+ readonly toolInputs?: Record<string, unknown>;
102
+ readonly contract?: CapabilityContract;
103
+ }
104
+ interface AI {
105
+ session(id: string): SessionRef;
106
+ plan<const TOutputs extends OutputContractMap>(intent: RunIntent<TOutputs>): Promise<ExecutionPlan>;
107
+ run<const TOutputs extends OutputContractMap>(intent: RunIntent<TOutputs>): Promise<RunResult<TOutputs>>;
108
+ /**
109
+ * Phase 19 (v1.2): single-agent execution loop. Drives multiple provider
110
+ * iterations under one call, dispatching tool requests between iterations.
111
+ * Composes with the v1.2 hook pipeline (SAFETY-band veto, OBSERVABILITY-band
112
+ * checkpoint receipts) and the v1.2 capability receipts (when
113
+ * `intent.signer` is provided + `intent.autoRegisterCheckpoint !== false`).
114
+ *
115
+ * See `packages/lattice/src/agent/runtime.ts` for orchestration details.
116
+ */
117
+ runAgent<const TOutputs extends OutputContractMap = DefaultAgentOutputs>(intent: AgentIntent<TOutputs>): Promise<AgentResult<TOutputs>>;
118
+ /**
119
+ * Phase 39 (v1.3): opt-in multi-agent crew execution. Runs a literal
120
+ * `AgentSpec` tree through the existing single-agent loop plus the crew
121
+ * dispatcher, with shared budget/rate-limit coordination and chained
122
+ * completion receipts.
123
+ *
124
+ * See `packages/lattice/src/agent/crew/run-crew.ts` for orchestration details.
125
+ */
126
+ runAgentCrew(options: RunAgentCrewOptions): Promise<CrewResult>;
127
+ }
128
+ declare function createAI(config?: LatticeConfig): AI;
129
+ //#endregion
130
+ //#region src/replay/replay.d.ts
131
+ interface ReplayEnvelope<TOutputs extends OutputContractMap = OutputContractMap> {
132
+ readonly kind: "replay-envelope";
133
+ readonly version: 1;
134
+ readonly runtimeVersion: string;
135
+ readonly catalogVersion: string;
136
+ readonly createdAt: string;
137
+ readonly plan: ExecutionPlan;
138
+ readonly artifacts: readonly ArtifactRef[];
139
+ readonly outputs?: InferOutputMap<TOutputs>;
140
+ readonly warnings: readonly string[];
141
+ readonly errors: readonly string[];
142
+ readonly usage?: UsageRecord;
143
+ readonly events: readonly RunEvent[];
144
+ /**
145
+ * Phase 10 — optional signed receipt recorded alongside the envelope so a
146
+ * single artifact is sufficient to materialize an offline replay session
147
+ * deterministically. Type-only import — replay.ts stays runtime-import-free
148
+ * of the receipts builder.
149
+ */
150
+ readonly receipt?: ReceiptEnvelope;
151
+ /**
152
+ * Phase 10 — optional contract recorded so replays can re-run pre-flight
153
+ * checks deterministically.
154
+ */
155
+ readonly contract?: CapabilityContract;
156
+ }
157
+ declare function createReplayEnvelope<TOutputs extends OutputContractMap>(result: RunResult<TOutputs>): ReplayEnvelope<TOutputs>;
158
+ declare function replayOffline<TOutputs extends OutputContractMap>(envelope: ReplayEnvelope<TOutputs>): Promise<RunResult<TOutputs>>;
159
+ declare function rerunLive<TOutputs extends OutputContractMap>(ai: AI, envelope: ReplayEnvelope<TOutputs>, intent: RunIntent<TOutputs>): Promise<RunResult<TOutputs>>;
160
+ declare function redactReplayEnvelope<TOutputs extends OutputContractMap>(envelope: ReplayEnvelope<TOutputs>): ReplayEnvelope<TOutputs>;
161
+ declare function redactPlan(plan: ExecutionPlan): ExecutionPlan;
162
+ declare function redactArtifactRef(ref: ArtifactRef): ArtifactRef;
163
+ //#endregion
164
+ //#region src/audit/external-execution.d.ts
165
+ type ExternalExecutionSidecarOutputSpec = "text" | {
166
+ readonly kind: "citations";
167
+ } | {
168
+ readonly kind: "artifacts";
169
+ };
170
+ interface ExternalExecutionUsage {
171
+ readonly promptTokens: number;
172
+ readonly completionTokens: number;
173
+ readonly costUsd: number | null;
174
+ }
175
+ interface ExternalExecutionAuditInput<TOutputs extends Record<string, unknown> = Record<string, unknown>> {
176
+ readonly task: string;
177
+ readonly artifacts?: readonly ArtifactInput[];
178
+ readonly outputSpecs?: Record<string, ExternalExecutionSidecarOutputSpec>;
179
+ readonly outputs?: TOutputs;
180
+ readonly policy: PolicySpec;
181
+ readonly contract: CapabilityContract;
182
+ readonly model: ReceiptModel;
183
+ readonly route: ReceiptRoute;
184
+ readonly usage: ExternalExecutionUsage;
185
+ readonly rawRequest?: unknown;
186
+ readonly rawResponse?: unknown;
187
+ readonly contractVerdict?: ContractVerdict;
188
+ readonly runId?: string;
189
+ readonly receiptId?: string;
190
+ readonly issuedAt?: string;
191
+ readonly catalogVersion?: string;
192
+ readonly metadata?: Record<string, unknown>;
193
+ }
194
+ interface ExternalExecutionMetadata {
195
+ readonly kind: "external-execution";
196
+ readonly model: ReceiptModel;
197
+ readonly route: ReceiptRoute;
198
+ readonly usage: ExternalExecutionUsage;
199
+ readonly rawRequest?: unknown;
200
+ readonly rawResponse?: unknown;
201
+ readonly rawRequestHash?: string;
202
+ readonly rawResponseHash?: string;
203
+ readonly inputHashes: readonly string[];
204
+ readonly outputHash: string | null;
205
+ readonly metadata?: Record<string, unknown>;
206
+ }
207
+ interface ExternalExecutionSidecar<TOutputs extends Record<string, unknown> = Record<string, unknown>> {
208
+ readonly version: "lattice-sidecar/v1";
209
+ readonly task: string;
210
+ readonly outputs: Record<string, ExternalExecutionSidecarOutputSpec>;
211
+ readonly policy: PolicySpec;
212
+ readonly contract: CapabilityContract;
213
+ readonly rawOutputs?: TOutputs;
214
+ readonly externalExecution: ExternalExecutionMetadata;
215
+ }
216
+ interface ExternalExecutionAuditResult<TOutputs extends Record<string, unknown> = Record<string, unknown>> {
217
+ readonly receipt: ReceiptEnvelope;
218
+ readonly sidecar: ExternalExecutionSidecar<TOutputs>;
219
+ readonly replayEnvelope: ReplayEnvelope<OutputContractMap>;
220
+ readonly inputHashes: readonly string[];
221
+ readonly outputHash: string | null;
222
+ }
223
+ declare function createExternalExecutionAudit<TOutputs extends Record<string, unknown> = Record<string, unknown>>(input: ExternalExecutionAuditInput<TOutputs>, signer: ReceiptSigner): Promise<ExternalExecutionAuditResult<TOutputs>>;
224
+ //#endregion
225
+ //#region src/receipts/keyset.d.ts
226
+ /**
227
+ * In-memory KeySet factory.
228
+ *
229
+ * Verification flow (plan 09-03):
230
+ * - keySet.lookup(kid) returns undefined → VerifyError {kind: "key-not-found"}
231
+ * - entry.state === "revoked" → VerifyError {kind: "key-revoked"}
232
+ * - entry.state === "retired" → VerifyOk + keyState: "retired" (caller may warn)
233
+ * - entry.state === "active" → VerifyOk + keyState: "active"
234
+ *
235
+ * Duplicate kids: last write wins (deterministic — callers control entry order).
236
+ * Empty entries array is legal — every lookup returns undefined.
237
+ * Returned KeySet exposes only `lookup` — no enumeration.
238
+ *
239
+ * See 09-CONTEXT.md "Key Management (UNRETROFITTABLE)".
240
+ */
241
+ declare function createMemoryKeySet(entries: readonly KeyEntry[]): KeySet;
242
+ //#endregion
243
+ //#region src/receipts/remote-signer.d.ts
244
+ type RemoteReceiptSignerProvider = "aws-kms" | "gcp-kms" | "external-kms" | (string & {});
245
+ type RemoteReceiptPayloadFormat = "dsse-pae";
246
+ interface RemoteReceiptSignRequest {
247
+ readonly kid: string;
248
+ readonly publicKeyJwk: JsonWebKey;
249
+ readonly bytes: Uint8Array;
250
+ readonly payloadFormat: RemoteReceiptPayloadFormat;
251
+ readonly algorithm: "Ed25519";
252
+ readonly provider?: RemoteReceiptSignerProvider;
253
+ readonly keyRef?: string;
254
+ readonly metadata?: Record<string, unknown>;
255
+ }
256
+ interface RemoteReceiptSignResult {
257
+ readonly signature: Uint8Array;
258
+ }
259
+ interface RemoteReceiptSignerOptions {
260
+ readonly kid: string;
261
+ readonly publicKeyJwk: JsonWebKey;
262
+ readonly provider?: RemoteReceiptSignerProvider;
263
+ readonly keyRef?: string;
264
+ readonly metadata?: Record<string, unknown>;
265
+ sign(request: RemoteReceiptSignRequest): Promise<Uint8Array | RemoteReceiptSignResult>;
266
+ }
267
+ /**
268
+ * Adapt a remote signing service to Lattice's existing ReceiptSigner contract.
269
+ *
270
+ * The callback receives the exact DSSE PAE bytes that createReceipt signs.
271
+ * Cloud-specific request construction, hashing choices, credentials, retries,
272
+ * and audit logging stay outside core.
273
+ */
274
+ declare function createRemoteReceiptSigner(options: RemoteReceiptSignerOptions): ReceiptSigner;
275
+ //#endregion
276
+ //#region src/receipts/sign.d.ts
277
+ interface GeneratedEd25519KeyPair {
278
+ readonly privateKeyJwk: JsonWebKey;
279
+ readonly publicKeyJwk: JsonWebKey;
280
+ }
281
+ declare function generateEd25519KeyPairJwk(): Promise<GeneratedEd25519KeyPair>;
282
+ declare function createInMemorySigner(privateKeyJwk: JsonWebKey, options: {
283
+ readonly kid: string;
284
+ readonly publicKeyJwk: JsonWebKey;
285
+ }): ReceiptSigner;
286
+ //#endregion
287
+ //#region src/receipts/verify.d.ts
288
+ /**
289
+ * Pure receipt verifier.
290
+ *
291
+ * Returns a typed VerifyResult — never throws across the verification
292
+ * boundary (PITFALLS.md security: "Verifier panics on malformed receipts
293
+ * -> DoS via crafted input"). All parsing failures become typed errors.
294
+ *
295
+ * Decision tree (first match wins):
296
+ * 1. decodeEnvelope throws OR signatures[] empty -> envelope-malformed
297
+ * 2. payload bytes are not valid JSON -> envelope-malformed
298
+ * 3. body shape check fails OR version unknown literal -> version-mismatch
299
+ * 4. body.version === undefined OR "lattice-receipt/v1"-> schema-version-too-low (CRYPTO-01)
300
+ * 5. keySet.lookup(keyid) === undefined -> key-not-found
301
+ * 6. entry.state === "revoked" -> key-revoked
302
+ * 7. re-canonicalized body != signed payloadBytes -> canonicalization-mismatch
303
+ * 8. Ed25519 verification of PAE fails -> signature-invalid
304
+ * 9. body.kid !== entry.kid (defense in depth) -> signature-invalid
305
+ * 10. otherwise -> ok + keyState
306
+ */
307
+ declare function verifyReceipt(envelope: ReceiptEnvelope, keySet: KeySet): Promise<VerifyResult>;
308
+ //#endregion
309
+ //#region src/receipts/cid.d.ts
310
+ /**
311
+ * Derive the content-addressed CID of a receipt envelope.
312
+ *
313
+ * Returns `sha256:<hex>` where `<hex>` is the 64-char lowercase SHA-256
314
+ * digest of the decoded DSSE payload bytes. No KeySet, signer, or other
315
+ * key material is required — callers chaining receipts (parentReceiptCid)
316
+ * compute this from the parent envelope alone.
317
+ */
318
+ declare function receiptCid(envelope: ReceiptEnvelope): Promise<string>;
319
+ //#endregion
320
+ //#region src/replay/materialize.d.ts
321
+ /**
322
+ * Discriminated union of materialization failure modes.
323
+ *
324
+ * - "verify-failed" — receipt failed verifyReceipt (signature, key
325
+ * missing/revoked, canonicalization mismatch).
326
+ * - "artifact-load-failed" — the artifactLoader callback rejected for at
327
+ * least one input hash.
328
+ * - "envelope-malformed" — receipt verified but the verified body is
329
+ * structurally unusable (should never happen
330
+ * under verifyReceipt invariants, but kept as a
331
+ * defensive third branch).
332
+ */
333
+ interface MaterializationError {
334
+ readonly kind: "verify-failed" | "artifact-load-failed" | "envelope-malformed";
335
+ readonly message: string;
336
+ }
337
+ /**
338
+ * Async callback that resolves an artifact body from its sha256 hex digest.
339
+ * Phase 10 ships only the in-memory variant for tests. Phase 11's CLI plugs
340
+ * in a filesystem-backed loader reading from `.lattice/fixtures/<sha256>.bin`.
341
+ */
342
+ type ArtifactLoader = (hash: string) => Promise<ArtifactInput>;
343
+ interface MaterializeReplayEnvelopeOptions<TOutputs extends OutputContractMap = OutputContractMap> {
344
+ readonly artifactLoader: ArtifactLoader;
345
+ readonly keySet: KeySet;
346
+ /** Optional original task string. Defaults to "" when omitted. */
347
+ readonly task?: string;
348
+ /**
349
+ * Optional caller-supplied outputs map. When provided, the resulting
350
+ * `ReplayEnvelope.outputs` is populated and `replayOffline` will return
351
+ * an `ok: true` result. When omitted, `replayOffline` reports an
352
+ * `execution_unavailable` failure (current Phase 5 semantics).
353
+ */
354
+ readonly outputs?: InferOutputMap<TOutputs>;
355
+ readonly policy?: PolicySpec;
356
+ readonly contract?: CapabilityContract;
357
+ }
358
+ /**
359
+ * Pure async function that reconstructs a `ReplayEnvelope` from a receipt.
360
+ *
361
+ * Verify-FIRST ordering: `verifyReceipt` runs before `artifactLoader` is
362
+ * touched. Tampered receipts MUST NOT cause loader side effects.
363
+ */
364
+ declare function materializeReplayEnvelope<TOutputs extends OutputContractMap = OutputContractMap>(receipt: ReceiptEnvelope, options: MaterializeReplayEnvelopeOptions<TOutputs>): Promise<ReplayEnvelope<TOutputs>>;
365
+ //#endregion
366
+ //#region src/observability/otel.d.ts
367
+ type OtelAttributeValue = string | number | boolean | readonly string[] | readonly number[] | readonly boolean[];
368
+ type OtelAttributes = Record<string, OtelAttributeValue>;
369
+ interface OtelSpanStatus {
370
+ readonly code: number;
371
+ readonly message?: string;
372
+ }
373
+ interface OtelSpanLike {
374
+ setAttribute?(key: string, value: OtelAttributeValue): unknown;
375
+ setAttributes?(attributes: OtelAttributes): unknown;
376
+ addEvent?(name: string, attributes?: OtelAttributes): unknown;
377
+ setStatus?(status: OtelSpanStatus): unknown;
378
+ recordException?(error: Error | string | Record<string, unknown>): unknown;
379
+ end?(endTime?: Date | number): unknown;
380
+ }
381
+ interface OtelTracerLike {
382
+ startSpan(name: string, options?: {
383
+ readonly attributes?: OtelAttributes;
384
+ readonly startTime?: Date | number;
385
+ }): OtelSpanLike;
386
+ }
387
+ type OtelContentCaptureMode = "none" | "metadata";
388
+ interface OtelSanitizerOptions {
389
+ readonly contentCapture?: OtelContentCaptureMode;
390
+ }
391
+ interface OtelRunEventSinkOptions extends OtelSanitizerOptions {
392
+ readonly tracer: OtelTracerLike;
393
+ readonly spanName?: string;
394
+ }
395
+ interface OtelHttpTraceConfig {
396
+ readonly endpoint: string;
397
+ readonly headers: Record<string, string>;
398
+ }
399
+ interface LangfuseOtlpConfigOptions {
400
+ readonly baseUrl?: string;
401
+ readonly publicKey?: string;
402
+ readonly secretKey?: string;
403
+ readonly authString?: string;
404
+ readonly ingestionVersion?: string;
405
+ readonly headers?: Record<string, string>;
406
+ }
407
+ interface PhoenixOtlpConfigOptions {
408
+ readonly baseUrl?: string;
409
+ readonly endpoint?: string;
410
+ readonly apiKey?: string;
411
+ readonly projectName?: string;
412
+ readonly headers?: Record<string, string>;
413
+ }
414
+ declare function createOtelRunEventSink(options: OtelRunEventSinkOptions): RunEventSink;
415
+ declare function sanitizeRunEventAttributes(event: RunEvent, options?: OtelSanitizerOptions): OtelAttributes;
416
+ declare function createOtelReceiptAttributes(envelope: ReceiptEnvelope): Promise<OtelAttributes>;
417
+ declare function createLangfuseOtlpConfig(options?: LangfuseOtlpConfigOptions): OtelHttpTraceConfig;
418
+ declare function createPhoenixOtlpConfig(options?: PhoenixOtlpConfigOptions): OtelHttpTraceConfig;
419
+ //#endregion
420
+ export { RemoteReceiptSignerProvider as A, ReplayEnvelope as B, GeneratedEd25519KeyPair as C, RemoteReceiptSignRequest as D, RemoteReceiptPayloadFormat as E, ExternalExecutionMetadata as F, replayOffline as G, redactArtifactRef as H, ExternalExecutionSidecar as I, RunIntent as J, rerunLive as K, ExternalExecutionSidecarOutputSpec as L, createMemoryKeySet as M, ExternalExecutionAuditInput as N, RemoteReceiptSignResult as O, ExternalExecutionAuditResult as P, ExternalExecutionUsage as R, verifyReceipt as S, generateEd25519KeyPairJwk as T, redactPlan as U, createReplayEnvelope as V, redactReplayEnvelope as W, CreateReceiptInput as X, createAI as Y, createReceipt as Z, ArtifactLoader as _, OtelHttpTraceConfig as a, materializeReplayEnvelope as b, OtelSpanLike as c, PhoenixOtlpConfigOptions as d, createLangfuseOtlpConfig as f, sanitizeRunEventAttributes as g, createPhoenixOtlpConfig as h, OtelContentCaptureMode as i, createRemoteReceiptSigner as j, RemoteReceiptSignerOptions as k, OtelSpanStatus as l, createOtelRunEventSink as m, OtelAttributeValue as n, OtelRunEventSinkOptions as o, createOtelReceiptAttributes as p, AI as q, OtelAttributes as r, OtelSanitizerOptions as s, LangfuseOtlpConfigOptions as t, OtelTracerLike as u, MaterializationError as v, createInMemorySigner as w, receiptCid as x, MaterializeReplayEnvelopeOptions as y, createExternalExecutionAudit as z };
421
+ //# sourceMappingURL=otel-BgM4e55_.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"otel-BgM4e55_.d.ts","names":[],"sources":["../src/receipts/receipt.ts","../src/runtime/create-ai.ts","../src/replay/replay.ts","../src/audit/external-execution.ts","../src/receipts/keyset.ts","../src/receipts/remote-signer.ts","../src/receipts/sign.ts","../src/receipts/verify.ts","../src/receipts/cid.ts","../src/replay/materialize.ts","../src/observability/otel.ts"],"mappings":";;;;;;;;;;;AAgCA;;;;;;;UAAiB,kBAAA;EAAA,SACN,KAAA;EAAA,SACA,QAAA;EAAA,SACA,SAAA;EAAA,SACA,KAAA,EAAO,YAAA;EAAA,SACP,KAAA,EAAO,YAAA;EAAA,SACP,UAAA,GAAa,aAAA;EAAA,SAIb,gBAAA;EAAA,SACA,iBAAA;EAAA,SACA,KAAA,EAAO,KAAA;EAAA,SACP,eAAA,EAAiB,eAAA;EAAA,SACjB,YAAA;EAAA,SACA,WAAA;EAAA,SACA,UAAA;EAAA,SACA,iBAAA;EAAA,SACA,cAAA,YAA0B,iBAAA;EAAA,SAC1B,gBAAA,GAAmB,gBAAA;EAAA,SAKnB,QAAA;EAAA,SACA,SAAA;EAAA,SACA,cAAA;EAAA,SACA,gBAAA;EAAA,SACA,SAAA;EAAA,SACA,SAAA;AAAA;;;;;;;;;;;;;AAuBX;;;;;;;;iBAAsB,aAAA,CACpB,KAAA,EAAO,kBAAA,EACP,MAAA,EAAQ,aAAA,GACP,OAAA,CAAQ,eAAA;;;UChCM,gBAAA;EAAA,SACN,QAAA;EAAA,SACA,KAAA;EAAA,SACA,aAAA,GAAg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,oBAAA;EAAA,SACN,cAAA,GAAiB,sBAAA;AAAA;AAAA,UAGX,uBAAA,SAAgC,oBAAA;EAAA,SACtC,MAAA,EAAQ,cAAA;EAAA,SACR,QAAA;AAAA;AAAA,UAGM,mBAAA;EAAA,SACN,QAAA;EAAA,SACA,OAAA,EAAS,MAAA;AAAA;AAAA,UAGH,yBAAA;EAAA,SACN,OAAA;EAAA,SACA,SAAA;EAAA,SACA,SAAA;EAAA,SACA,UAAA;EAAA,SACA,gBAAA;EAAA,SACA,OAAA,GAAU,MAAA;AAAA;AAAA,UAGJ,wBAAA;EAAA,SACN,OAAA;EAAA,SACA,QAAA;EAAA,SACA,MAAA;EAAA,SACA,WAAA;EAAA,SACA,OAAA,GAAU,MAAA;AAAA;AAAA,iBAWL,sBAAA,CACd,OAAA,EAAS,uBAAA,GACR,YAAA;AAAA,iBAsCa,0BAAA,CACd,KAAA,EAAO,QAAA,EACP,OAAA,GAAS,oBAAA,GACR,cAAA;AAAA,iBA4CmB,2BAAA,CACpB,QAAA,EAAU,eAAA,GACT,OAAA,CAAQ,cAAA;AAAA,iBAaK,wBAAA,CACd,OAAA,GAAS,yBAAA,GACR,mBAAA;AAAA,iBAYa,uBAAA,CACd,OAAA,GAAS,wBAAA,GACR,mBAAA"}
@@ -0,0 +1,134 @@
1
+ import { f as BAND } from "./runtime-Dxiet5YS.js";
2
+ //#region src/agent/crew/agent-spec.ts
3
+ /**
4
+ * Factory for `AgentSpec` values. Mirrors `defineTool` exactly: spread
5
+ * preserves input identity (no cloning, no mutation) and absent optional
6
+ * members stay absent (`exactOptionalPropertyTypes`-safe).
7
+ */
8
+ function defineAgent(definition) {
9
+ return {
10
+ kind: "agent",
11
+ ...definition
12
+ };
13
+ }
14
+ //#endregion
15
+ //#region src/agent/infra/transcript-store.ts
16
+ const DEFAULT_TOKEN_ESTIMATOR = (text) => Math.ceil(text.length / 4);
17
+ function createTranscriptStore() {
18
+ const turns = [];
19
+ function firstUserTurn() {
20
+ for (const turn of turns) if (turn.role === "user") return turn;
21
+ return null;
22
+ }
23
+ return {
24
+ kind: "transcript-store",
25
+ append(turn) {
26
+ turns.push(turn);
27
+ },
28
+ all() {
29
+ return Object.freeze([...turns]);
30
+ },
31
+ tail(limit) {
32
+ if (limit <= 0) return Object.freeze([]);
33
+ if (turns.length <= limit) return Object.freeze([...turns]);
34
+ const start = turns.length - limit;
35
+ const tail = turns.slice(start);
36
+ const first = firstUserTurn();
37
+ if (first === null || tail.includes(first)) return Object.freeze(tail);
38
+ return Object.freeze([first, ...tail]);
39
+ },
40
+ tailByTokens(maxTokens, estimator = DEFAULT_TOKEN_ESTIMATOR) {
41
+ if (maxTokens <= 0) return Object.freeze([]);
42
+ const reversed = [...turns].reverse();
43
+ const selected = [];
44
+ let used = 0;
45
+ for (const turn of reversed) {
46
+ const cost = estimator(turn.content);
47
+ if (used + cost > maxTokens) break;
48
+ selected.unshift(turn);
49
+ used += cost;
50
+ }
51
+ const first = firstUserTurn();
52
+ if (first !== null && !selected.includes(first)) selected.unshift(first);
53
+ return Object.freeze(selected);
54
+ }
55
+ };
56
+ }
57
+ //#endregion
58
+ //#region src/agent/infra/goal-progress.ts
59
+ function createGoalProgressTracker(options = {}) {
60
+ const windowSize = options.windowSize ?? 3;
61
+ const stallThreshold = options.stallThreshold ?? .02;
62
+ const regressionThreshold = options.regressionThreshold ?? .1;
63
+ const steps = [];
64
+ return {
65
+ kind: "goal-progress-tracker",
66
+ recordStep(step) {
67
+ steps.push(step);
68
+ },
69
+ status() {
70
+ if (steps.length < windowSize) return "progressing";
71
+ const window = steps.slice(-windowSize);
72
+ const latest = window[window.length - 1];
73
+ const earlierMax = steps.slice(0, -1).reduce((m, s) => s.goalSatisfaction > m ? s.goalSatisfaction : m, -Infinity);
74
+ if (latest.goalSatisfaction < earlierMax - regressionThreshold) return "regressed";
75
+ const min = window.reduce((m, s) => s.goalSatisfaction < m ? s.goalSatisfaction : m, Infinity);
76
+ if (window.reduce((m, s) => s.goalSatisfaction > m ? s.goalSatisfaction : m, -Infinity) - min <= stallThreshold) return "stalled";
77
+ return "progressing";
78
+ }
79
+ };
80
+ }
81
+ //#endregion
82
+ //#region src/agent/infra/permission-context.ts
83
+ /**
84
+ * PermissionContext — Phase 21 (v1.2).
85
+ *
86
+ * Gates tool execution per-tool / per-iteration / per-resource. Includes
87
+ * a SAFETY-band hook helper that wires the context into the agent loop's
88
+ * BEFORE_TOOL pipeline via the Phase 19 `controls.deny(reason)` veto.
89
+ */
90
+ function matches(matcher, value) {
91
+ if (matcher === void 0) return true;
92
+ if (value === void 0) return false;
93
+ if (typeof matcher === "string") return matcher === value;
94
+ return matcher.test(value);
95
+ }
96
+ function createPermissionContext(rules) {
97
+ return {
98
+ kind: "permission-context",
99
+ decide(input) {
100
+ for (const rule of rules) {
101
+ if (!matches(rule.toolName, input.toolName)) continue;
102
+ if (rule.resource !== void 0 && !matches(rule.resource, input.resource)) continue;
103
+ if (rule.verdict === "allow") return { allow: true };
104
+ return {
105
+ allow: false,
106
+ reason: rule.reason ?? `denied by permission rule for ${input.toolName}`
107
+ };
108
+ }
109
+ return { allow: true };
110
+ }
111
+ };
112
+ }
113
+ function createPermissionGuardHook(context) {
114
+ return (ctx, controls) => {
115
+ const verdict = context.decide({
116
+ iterationIndex: ctx.iterationIndex,
117
+ toolName: ctx.toolName,
118
+ ...ctx.resource !== void 0 ? { resource: ctx.resource } : {},
119
+ ...ctx.args !== void 0 ? { args: ctx.args } : {}
120
+ });
121
+ if (!verdict.allow) controls?.deny(verdict.reason);
122
+ };
123
+ }
124
+ /**
125
+ * Convenience: returns RegisterOptions for the SAFETY-band registration.
126
+ * Callers do `pipeline.register("BEFORE_TOOL", hook, permissionGuardRegisterOptions())`.
127
+ */
128
+ function permissionGuardRegisterOptions() {
129
+ return { band: BAND.SAFETY };
130
+ }
131
+ //#endregion
132
+ export { createTranscriptStore as a, createGoalProgressTracker as i, createPermissionGuardHook as n, defineAgent as o, permissionGuardRegisterOptions as r, createPermissionContext as t };
133
+
134
+ //# sourceMappingURL=permission-context-CUKMo79F.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"permission-context-CUKMo79F.js","names":[],"sources":["../src/agent/crew/agent-spec.ts","../src/agent/infra/transcript-store.ts","../src/agent/infra/goal-progress.ts","../src/agent/infra/permission-context.ts"],"sourcesContent":["/**\n * AgentSpec — Phase 39 (v1.3). Sibling of defineTool; crew member\n * specification composing by value as a tree (D-03).\n *\n * `defineAgent(spec)` mirrors `defineTool` (tools/tools.ts) literally:\n * an `Omit<…, \"kind\">` factory that spreads the definition under the\n * `kind: \"agent\"` discriminant. The runtime (CrewDispatcher, 39-05)\n * branches on `kind` to route dispatch through the crew chokepoint\n * instead of `runTool` (D-01).\n *\n * `childAgents` composes by value — a crew is a literal tree of specs,\n * not a registry of ids. `summaryReturnSchema` validates the child's\n * `{ summary, artifacts, receipts }` return envelope (Standard Schema,\n * Zod-compatible). `contract` carries an optional per-agent sub-budget\n * (D-07): the effective child budget is `min(spec.contract.budget,\n * remaining crew pool)`.\n */\n\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\";\n\nimport type { CapabilityContract } from \"../../contract/contract.js\";\nimport type { ToolDefinition } from \"../../tools/tools.js\";\n\n/**\n * Crew member specification. A literal sibling of `ToolDefinition`\n * discriminated by `kind: \"agent\"` (D-03).\n */\nexport interface AgentSpec {\n readonly kind: \"agent\";\n readonly id: string;\n readonly intent: string;\n readonly tools: ReadonlyArray<ToolDefinition<StandardSchemaV1>>;\n readonly childAgents?: ReadonlyArray<AgentSpec>;\n readonly summaryReturnSchema: StandardSchemaV1;\n /** Optional per-agent sub-budget (D-07). */\n readonly contract?: CapabilityContract;\n}\n\n/**\n * Factory for `AgentSpec` values. Mirrors `defineTool` exactly: spread\n * preserves input identity (no cloning, no mutation) and absent optional\n * members stay absent (`exactOptionalPropertyTypes`-safe).\n */\nexport function defineAgent(definition: Omit<AgentSpec, \"kind\">): AgentSpec {\n return {\n kind: \"agent\",\n ...definition,\n };\n}\n","/**\n * TranscriptStore — Phase 21 (v1.2).\n *\n * Records the running conversation log with filtered tail reads sized for\n * context-window management. Always preserves the FIRST user turn (the\n * original task) in tail reads so the model retains its mission.\n */\n\nimport type { ConversationTurn } from \"../format-tools.js\";\n\n/**\n * Token estimator used by `tailByTokens`. The default ~4 chars / token is\n * the OpenAI rule of thumb for English text. Callers with provider-specific\n * tokenizers can supply their own.\n */\nexport type TokenEstimator = (text: string) => number;\n\nconst DEFAULT_TOKEN_ESTIMATOR: TokenEstimator = (text) => Math.ceil(text.length / 4);\n\nexport interface TranscriptStore {\n readonly kind: \"transcript-store\";\n append(turn: ConversationTurn): void;\n all(): readonly ConversationTurn[];\n /** Returns the first user turn (if any) + the most-recent `limit` turns. */\n tail(limit: number): readonly ConversationTurn[];\n /**\n * Returns the first user turn (if any) + the most-recent turns whose\n * combined token estimate fits within `maxTokens`. The default estimator\n * is the ~4 chars / token rule; callers can override for provider-\n * specific tokenizers.\n */\n tailByTokens(maxTokens: number, estimator?: TokenEstimator): readonly ConversationTurn[];\n}\n\nexport function createTranscriptStore(): TranscriptStore {\n const turns: ConversationTurn[] = [];\n\n function firstUserTurn(): ConversationTurn | null {\n for (const turn of turns) {\n if (turn.role === \"user\") return turn;\n }\n return null;\n }\n\n return {\n kind: \"transcript-store\" as const,\n append(turn: ConversationTurn): void {\n turns.push(turn);\n },\n all(): readonly ConversationTurn[] {\n return Object.freeze([...turns]);\n },\n tail(limit: number): readonly ConversationTurn[] {\n if (limit <= 0) return Object.freeze([]);\n if (turns.length <= limit) return Object.freeze([...turns]);\n const start = turns.length - limit;\n const tail = turns.slice(start);\n const first = firstUserTurn();\n if (first === null || tail.includes(first)) {\n return Object.freeze(tail);\n }\n return Object.freeze([first, ...tail]);\n },\n tailByTokens(\n maxTokens: number,\n estimator: TokenEstimator = DEFAULT_TOKEN_ESTIMATOR,\n ): readonly ConversationTurn[] {\n if (maxTokens <= 0) return Object.freeze([]);\n const reversed = [...turns].reverse();\n const selected: ConversationTurn[] = [];\n let used = 0;\n for (const turn of reversed) {\n const cost = estimator(turn.content);\n if (used + cost > maxTokens) break;\n selected.unshift(turn);\n used += cost;\n }\n const first = firstUserTurn();\n if (first !== null && !selected.includes(first)) {\n selected.unshift(first);\n }\n return Object.freeze(selected);\n },\n };\n}\n","/**\n * GoalProgressTracker — Phase 21 (v1.2).\n *\n * Stuck-detection primitive. The caller declares a goal-satisfaction\n * score per iteration (0..1); the tracker reports a coarse status the\n * agent loop can use to back off or surface to the human.\n */\n\nexport type ProgressStatus = \"progressing\" | \"stalled\" | \"regressed\";\n\nexport interface GoalProgressOptions {\n /**\n * Window of recent steps used for stall + regression detection.\n * Default 3. The tracker waits until it has at least this many steps\n * before reporting anything other than \"progressing\".\n */\n readonly windowSize?: number;\n /** Max satisfaction delta across the window to count as \"stalled\". Default 0.02. */\n readonly stallThreshold?: number;\n /** Min drop from prior max to count as \"regressed\". Default 0.1. */\n readonly regressionThreshold?: number;\n}\n\nexport interface GoalProgressStep {\n readonly iterationIndex: number;\n readonly goalSatisfaction: number;\n}\n\nexport interface GoalProgressTracker {\n readonly kind: \"goal-progress-tracker\";\n recordStep(step: GoalProgressStep): void;\n status(): ProgressStatus;\n}\n\nexport function createGoalProgressTracker(\n options: GoalProgressOptions = {},\n): GoalProgressTracker {\n const windowSize = options.windowSize ?? 3;\n const stallThreshold = options.stallThreshold ?? 0.02;\n const regressionThreshold = options.regressionThreshold ?? 0.1;\n const steps: GoalProgressStep[] = [];\n\n return {\n kind: \"goal-progress-tracker\" as const,\n recordStep(step: GoalProgressStep): void {\n steps.push(step);\n },\n status(): ProgressStatus {\n if (steps.length < windowSize) return \"progressing\";\n const window = steps.slice(-windowSize);\n const latest = window[window.length - 1]!;\n const earlierMax = steps\n .slice(0, -1)\n .reduce((m, s) => (s.goalSatisfaction > m ? s.goalSatisfaction : m), -Infinity);\n if (latest.goalSatisfaction < earlierMax - regressionThreshold) {\n return \"regressed\";\n }\n const min = window.reduce((m, s) => (s.goalSatisfaction < m ? s.goalSatisfaction : m), Infinity);\n const max = window.reduce((m, s) => (s.goalSatisfaction > m ? s.goalSatisfaction : m), -Infinity);\n if (max - min <= stallThreshold) {\n return \"stalled\";\n }\n return \"progressing\";\n },\n };\n}\n","/**\n * PermissionContext — Phase 21 (v1.2).\n *\n * Gates tool execution per-tool / per-iteration / per-resource. Includes\n * a SAFETY-band hook helper that wires the context into the agent loop's\n * BEFORE_TOOL pipeline via the Phase 19 `controls.deny(reason)` veto.\n */\n\nimport { BAND, type HookHandler, type RegisterOptions } from \"../../contract/bands.js\";\n\nexport interface PermissionRule {\n /** Match on tool name. String = exact match; RegExp = test. Both undefined = match-any. */\n readonly toolName?: string | RegExp;\n /**\n * Optional resource matcher. The caller passes `resource` on each\n * decide() invocation; this rule fires only when the rule's resource\n * matches.\n */\n readonly resource?: string | RegExp;\n readonly verdict: \"allow\" | \"deny\";\n readonly reason?: string;\n}\n\nexport interface PermissionDecisionInput {\n readonly toolName: string;\n readonly iterationIndex: number;\n readonly resource?: string;\n readonly args?: unknown;\n}\n\nexport type PermissionVerdict =\n | { readonly allow: true }\n | { readonly allow: false; readonly reason: string };\n\nexport interface PermissionContext {\n readonly kind: \"permission-context\";\n decide(input: PermissionDecisionInput): PermissionVerdict;\n}\n\nfunction matches(matcher: string | RegExp | undefined, value: string | undefined): boolean {\n if (matcher === undefined) return true;\n if (value === undefined) return false;\n if (typeof matcher === \"string\") return matcher === value;\n return matcher.test(value);\n}\n\nexport function createPermissionContext(\n rules: readonly PermissionRule[],\n): PermissionContext {\n return {\n kind: \"permission-context\" as const,\n decide(input: PermissionDecisionInput): PermissionVerdict {\n for (const rule of rules) {\n if (!matches(rule.toolName, input.toolName)) continue;\n if (rule.resource !== undefined && !matches(rule.resource, input.resource)) continue;\n if (rule.verdict === \"allow\") return { allow: true };\n return { allow: false, reason: rule.reason ?? `denied by permission rule for ${input.toolName}` };\n }\n // Default: allow when no rule matches.\n return { allow: true };\n },\n };\n}\n\n/**\n * Hook handler shape suitable for registering on `BEFORE_TOOL` at\n * BAND.SAFETY. Reads `toolName` and `iterationIndex` from the agent\n * runtime's BEFORE_TOOL context shape (`{ iterationIndex, toolName,\n * args }`) and translates a deny verdict into `controls.deny(reason)`.\n */\nexport interface PermissionHookContext {\n readonly iterationIndex: number;\n readonly toolName: string;\n readonly resource?: string;\n readonly args?: unknown;\n}\n\nexport function createPermissionGuardHook(\n context: PermissionContext,\n): HookHandler<PermissionHookContext> {\n return (ctx, controls) => {\n const verdict = context.decide({\n iterationIndex: ctx.iterationIndex,\n toolName: ctx.toolName,\n ...(ctx.resource !== undefined ? { resource: ctx.resource } : {}),\n ...(ctx.args !== undefined ? { args: ctx.args } : {}),\n });\n if (!verdict.allow) {\n controls?.deny(verdict.reason);\n }\n };\n}\n\n/**\n * Convenience: returns RegisterOptions for the SAFETY-band registration.\n * Callers do `pipeline.register(\"BEFORE_TOOL\", hook, permissionGuardRegisterOptions())`.\n */\nexport function permissionGuardRegisterOptions(): RegisterOptions {\n return { band: BAND.SAFETY };\n}\n"],"mappings":";;;;;;;AA2CA,SAAgB,YAAY,YAAgD;AAC1E,QAAO;EACL,MAAM;EACN,GAAG;EACJ;;;;AC9BH,MAAM,2BAA2C,SAAS,KAAK,KAAK,KAAK,SAAS,EAAE;AAiBpF,SAAgB,wBAAyC;CACvD,MAAM,QAA4B,EAAE;CAEpC,SAAS,gBAAyC;AAChD,OAAK,MAAM,QAAQ,MACjB,KAAI,KAAK,SAAS,OAAQ,QAAO;AAEnC,SAAO;;AAGT,QAAO;EACL,MAAM;EACN,OAAO,MAA8B;AACnC,SAAM,KAAK,KAAK;;EAElB,MAAmC;AACjC,UAAO,OAAO,OAAO,CAAC,GAAG,MAAM,CAAC;;EAElC,KAAK,OAA4C;AAC/C,OAAI,SAAS,EAAG,QAAO,OAAO,OAAO,EAAE,CAAC;AACxC,OAAI,MAAM,UAAU,MAAO,QAAO,OAAO,OAAO,CAAC,GAAG,MAAM,CAAC;GAC3D,MAAM,QAAQ,M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