@tangle-network/agent-runtime 0.319.10 → 0.321.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 (62) hide show
  1. package/dist/{activation-OColGsfd.d.ts → activation-BxOOvwjo.d.ts} +2 -2
  2. package/dist/{activation-BKglRwjB.js → activation-CXFl5YVE.js} +2 -2
  3. package/dist/{activation-BKglRwjB.js.map → activation-CXFl5YVE.js.map} +1 -1
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +2 -2
  6. package/dist/candidate-execution/index.js +3 -3
  7. package/dist/{coordination-driver-CE01_us_.js → coordination-driver-Bpn05N-Y.js} +21 -4
  8. package/dist/coordination-driver-Bpn05N-Y.js.map +1 -0
  9. package/dist/{delegate-BptW384t.js → delegate-BHlcTOdK.js} +2 -2
  10. package/dist/{delegate-BptW384t.js.map → delegate-BHlcTOdK.js.map} +1 -1
  11. package/dist/durable.d.ts +1 -1
  12. package/dist/durable.js +3 -3
  13. package/dist/{graph-Bkcora6P.js → graph-DE2dLhDI.js} +4 -4
  14. package/dist/{graph-Bkcora6P.js.map → graph-DE2dLhDI.js.map} +1 -1
  15. package/dist/{improvement-cycle-0cnwWPFY.js → improvement-cycle-CyChbojL.js} +5 -5
  16. package/dist/{improvement-cycle-0cnwWPFY.js.map → improvement-cycle-CyChbojL.js.map} +1 -1
  17. package/dist/{index-Da7w2H86.d.ts → index-BxiHetnG.d.ts} +244 -3
  18. package/dist/index.d.ts +4 -4
  19. package/dist/index.js +7 -7
  20. package/dist/intelligence.d.ts +2 -2
  21. package/dist/intelligence.js +6 -6
  22. package/dist/kernel.d.ts +2 -2
  23. package/dist/kernel.js +9 -9
  24. package/dist/{loop-runner-bin-DRw76sWb.js → loop-runner-bin-CT02Vzco.js} +3 -3
  25. package/dist/{loop-runner-bin-DRw76sWb.js.map → loop-runner-bin-CT02Vzco.js.map} +1 -1
  26. package/dist/{loop-runner-bin-CbBoLC9D.d.ts → loop-runner-bin-DInJZNgs.d.ts} +2 -2
  27. package/dist/loop-runner-bin.d.ts +1 -1
  28. package/dist/loop-runner-bin.js +1 -1
  29. package/dist/mcp/bin.js +3 -3
  30. package/dist/mcp/index.d.ts +2 -2
  31. package/dist/mcp/index.js +4 -4
  32. package/dist/{openai-tools-Cu9E1Bda.d.ts → openai-tools-DLTw576v.d.ts} +2 -2
  33. package/dist/{prepare-DjCLEN-q.js → prepare-CFQLx9e3.js} +2 -2
  34. package/dist/{prepare-DjCLEN-q.js.map → prepare-CFQLx9e3.js.map} +1 -1
  35. package/dist/{profile-DmVM4Gxb.js → profile-BTbpdL9h.js} +40 -4
  36. package/dist/profile-BTbpdL9h.js.map +1 -0
  37. package/dist/profiles.d.ts +1 -1
  38. package/dist/{protected-model-port-D1fcnYdj.js → protected-model-port-f1N2f0Uq.js} +3 -3
  39. package/dist/{protected-model-port-D1fcnYdj.js.map → protected-model-port-f1N2f0Uq.js.map} +1 -1
  40. package/dist/{provision-supervisor-Bs698TqJ.js → provision-supervisor-DvgBNtoJ.js} +3 -3
  41. package/dist/{provision-supervisor-Bs698TqJ.js.map → provision-supervisor-DvgBNtoJ.js.map} +1 -1
  42. package/dist/{runtime-SioKh3r_.js → runtime-wLgjMOaj.js} +399 -11
  43. package/dist/runtime-wLgjMOaj.js.map +1 -0
  44. package/dist/{search-executor-DjKdQluM.js → search-executor-TEKWC579.js} +2 -2
  45. package/dist/{search-executor-DjKdQluM.js.map → search-executor-TEKWC579.js.map} +1 -1
  46. package/dist/{server-BfEwCD55.js → server-qYhzITTm.js} +3 -3
  47. package/dist/{server-BfEwCD55.js.map → server-qYhzITTm.js.map} +1 -1
  48. package/dist/{supervise-Bj8U345y.js → supervise-C4bLIU7J.js} +68 -16
  49. package/dist/supervise-C4bLIU7J.js.map +1 -0
  50. package/dist/{supervisor-CCtmmmOz.js → supervisor-bkq2b8k-.js} +383 -43
  51. package/dist/supervisor-bkq2b8k-.js.map +1 -0
  52. package/dist/testing.d.ts +1 -1
  53. package/dist/testing.js +13 -13
  54. package/dist/tui/index.d.ts +1 -1
  55. package/dist/tui/index.js +1 -1
  56. package/package.json +4 -4
  57. package/skills/profile-authoring/SKILL.md +1 -1
  58. package/dist/coordination-driver-CE01_us_.js.map +0 -1
  59. package/dist/profile-DmVM4Gxb.js.map +0 -1
  60. package/dist/runtime-SioKh3r_.js.map +0 -1
  61. package/dist/supervise-Bj8U345y.js.map +0 -1
  62. package/dist/supervisor-CCtmmmOz.js.map +0 -1
@@ -1,3 +1,4 @@
1
+ import { m as ValidationError } from "./errors-DodWX-cb.js";
1
2
  import { I as embeddedCandidateArtifact, L as immutableCandidateValue, M as canonicalCandidateBytes$1, N as canonicalCandidateDigest$1, P as canonicalCandidateDocument, R as omitTopLevelDigest, z as sha256Bytes$1 } from "./workspace-streams-DFAhW7hF.js";
2
3
  import { agentCandidateProfileActivationSchema, agentCandidateProfileSchema, agentProfileDiffSchema, agentProfileSchema, applyAgentProfileDiff } from "@tangle-network/agent-interface";
3
4
  import { posix } from "node:path";
@@ -221,6 +222,7 @@ const CANDIDATE_PROFILE_DIRECT_FIELDS = [
221
222
  ];
222
223
  /** Convert only behavior-preserving generic profile fields into the closed candidate contract. */
223
224
  function freezeGenericAgentCandidateProfile(input) {
225
+ refuseFieldsSandboxCannotCarry(input);
224
226
  return candidateProfileFromGenericProfile(parseExactAgentProfile(input, "profile"));
225
227
  }
226
228
  /**
@@ -258,6 +260,7 @@ function candidateProfileFromGenericProfile(profile) {
258
260
  }
259
261
  /** Prove the measured generic profile and sealed candidate profile describe the same behavior. */
260
262
  function assertCandidateProfileBinding(measuredInput, bundled) {
263
+ refuseFieldsSandboxCannotCarry(measuredInput);
261
264
  if (canonicalCandidateDigest$1(candidateProfileFromGenericProfile(parseExactAgentProfile(measuredInput, "measured agent profile"))) !== canonicalCandidateDigest$1(bundled)) throw new Error("measured agent profile does not match sealed candidate profile");
262
265
  }
263
266
  /** Parse a complete profile without silently discarding unsupported fields. */
@@ -295,6 +298,7 @@ function parseExactCandidateProfile(input) {
295
298
  /** Reject profile fields whose behavioral effect is not yet proven by candidate executors. */
296
299
  function assertCandidateProfileExecutionSupport(profile) {
297
300
  assertResolvedKnowledgeResources(profile.resources);
301
+ refuseFieldsSandboxCannotCarry(profile);
298
302
  const unsupported = [
299
303
  "tools",
300
304
  "permissions",
@@ -306,6 +310,7 @@ function assertCandidateProfileExecutionSupport(profile) {
306
310
  /** Convert the candidate profile contract into the portable interface profile it represents. */
307
311
  function agentCandidateProfileAsAgentProfile(candidate) {
308
312
  assertResolvedKnowledgeResources(candidate.resources);
313
+ refuseFieldsSandboxCannotCarry(candidate);
309
314
  const output = {};
310
315
  copyDirectProfileFields(output, candidate);
311
316
  if (candidate.model) output.model = { ...candidate.model };
@@ -367,6 +372,38 @@ function freezeMcpServers(servers) {
367
372
  function assertResolvedKnowledgeResources(resources) {
368
373
  if (resources !== null && typeof resources === "object" && "knowledge" in resources && resources.knowledge !== void 0) throw new Error("candidate profile resources.knowledge must be owner-authorized and resolved before candidate conversion or execution");
369
374
  }
375
+ /**
376
+ * Interface 5.3 admits profile `proxySecrets` and candidate secret-ref config values, but
377
+ * Sandbox still ships its own Interface 4.0.0, which carries neither. Refuse them by name
378
+ * rather than drop them; remove this once Sandbox adopts Interface 5.3.
379
+ */
380
+ function refuseFieldsSandboxCannotCarry(profile) {
381
+ if (!isRecord(profile)) return;
382
+ if (profile.proxySecrets !== void 0) refuseFieldSandboxCannotCarry("proxySecrets");
383
+ if (isRecord(profile.mcp)) for (const [name, server] of Object.entries(profile.mcp)) {
384
+ if (!isRecord(server)) continue;
385
+ refuseNonPublicConfigValues(server.args, `mcp.${name}.args`);
386
+ refuseNonPublicConfigValues(server.env, `mcp.${name}.env`);
387
+ }
388
+ if (isRecord(profile.hooks)) for (const [event, hooks] of Object.entries(profile.hooks)) {
389
+ if (!Array.isArray(hooks)) continue;
390
+ for (const [index, hook] of hooks.entries()) {
391
+ if (!isRecord(hook)) continue;
392
+ refuseNonPublicConfigValues(hook.args, `hooks.${event}[${index}].args`);
393
+ refuseNonPublicConfigValues(hook.env, `hooks.${event}[${index}].env`);
394
+ }
395
+ }
396
+ }
397
+ function refuseNonPublicConfigValues(values, path) {
398
+ const entries = Array.isArray(values) ? values.map((value, index) => [`${path}[${index}]`, value]) : isRecord(values) ? Object.entries(values).map(([name, value]) => [`${path}.${name}`, value]) : [];
399
+ for (const [field, value] of entries) if (isRecord(value) && value.kind !== "public") refuseFieldSandboxCannotCarry(`${field} (${String(value.kind)})`);
400
+ }
401
+ function refuseFieldSandboxCannotCarry(field) {
402
+ throw new ValidationError(`candidate profile field ${field} is refused: Sandbox's Interface 4.0.0 cannot carry it yet, and Runtime does not drop it`);
403
+ }
404
+ function isRecord(value) {
405
+ return value !== null && typeof value === "object" && !Array.isArray(value);
406
+ }
370
407
  function freezeResources(resources) {
371
408
  if (resources.failOnError !== true) throw new Error("candidate profile resources require failOnError: true");
372
409
  return {
@@ -412,10 +449,9 @@ function publicResource(resource) {
412
449
  };
413
450
  }
414
451
  /** Freeze one profile config value into the candidate's PUBLIC-only config
415
- * shape. A secret-ref has no candidate representation (AgentCandidateConfigValue
416
- * is public-only), so it is rejected, never silently dropped or unwrapped. */
452
+ * shape. A secret-ref is refused, never silently dropped or unwrapped. */
417
453
  function candidatePublicValue(value, path) {
418
- if (value.kind !== "public") unsupportedProfileField(`${path} (secret-ref '${value.key}')`);
454
+ if (value.kind !== "public") refuseFieldSandboxCannotCarry(`${path} (${value.kind})`);
419
455
  return {
420
456
  kind: "public",
421
457
  value: value.value
@@ -442,4 +478,4 @@ function unsupportedProfileField(path) {
442
478
  //#endregion
443
479
  export { assertCandidateProfileBinding as a, createAgentCandidateProfileActivation as c, omitUndefinedObjectFields as d, parseAgentCandidateProfileActivation as f, parseExactCandidateProfile as h, applyExactAgentProfileDiff as i, freezeGenericAgentCandidateProfile as l, parseExactAgentProfileDiff as m, PI_CANDIDATE_SESSION_DIR_ENV as n, assertCandidateProfileExecutionSupport as o, parseExactAgentProfile as p, agentCandidateProfileAsAgentProfile as r, candidateProfileAgentPaths as s, PI_CANDIDATE_AGENT_DIR_ENV as t, materializeAgentCandidateProfilePlan as u };
444
480
 
445
- //# sourceMappingURL=profile-DmVM4Gxb.js.map
481
+ //# sourceMappingURL=profile-BTbpdL9h.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"profile-BTbpdL9h.js","names":["publicValue","canonicalCandidateBytes","sha256Bytes","canonicalCandidateDigest"],"sources":["../src/candidate-execution/system-prompt.ts","../src/candidate-execution/profile.ts"],"sourcesContent":["import { posix } from 'node:path'\n\nimport type {\n AgentCandidateConfigValue,\n AgentCandidateLaunch,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentCandidateWorkspacePlan,\n HarnessId,\n} from '@tangle-network/agent-profile-materialize'\n\nconst SYSTEM_PROMPT_FILE = '.tangle/system-prompt.md'\nconst APPEND_SYSTEM_PROMPT_FILE = '.tangle/append-system-prompt.md'\n\n/**\n * One row describes the native process control for each prompt intent this adapter owns.\n * A row with no executor projection means the shared materializer already lowered the intent into\n * the signed workspace plan; this adapter still proves that the launch reaches the native binary.\n */\ninterface HarnessSystemPrompt {\n /** The native binary the launch must run for this projection to be provable. */\n readonly executable: string\n /** Apply a replacement prompt to the harness's own control. */\n readonly project: (\n plan: AgentCandidateWorkspacePlan,\n systemPrompt: string,\n systemPromptFilePath: string,\n ) => AgentCandidateWorkspacePlan\n /** Apply an addition without replacing the harness's own prompt. */\n readonly projectAppend?: (\n plan: AgentCandidateWorkspacePlan,\n appendSystemPrompt: string,\n appendSystemPromptFilePath: string,\n ) => AgentCandidateWorkspacePlan\n /** The materializer already projected replacement text into native plan files and flags. */\n readonly retainsProjectedSystemPrompt?: boolean\n /** Does caller argv already set a replacement control this projection would shadow? */\n readonly conflictsWithArgs: (values: readonly string[]) => boolean\n /** Does caller argv already set an additive control this projection would shadow? */\n readonly conflictsWithAppendArgs: (values: readonly string[]) => boolean\n}\n\nconst SYSTEM_PROMPT_FLAGS = ['--system-prompt', '--system-prompt-file'] as const\nconst APPEND_SYSTEM_PROMPT_FLAGS = [\n '--append-system-prompt',\n '--append-system-prompt-file',\n] as const\n\nfunction argsSetSystemPromptFlag(values: readonly string[]): boolean {\n return values.some((value) =>\n SYSTEM_PROMPT_FLAGS.some((flag) => value === flag || value.startsWith(`${flag}=`)),\n )\n}\n\nfunction argsSetAppendSystemPromptFlag(values: readonly string[]): boolean {\n return values.some((value) =>\n APPEND_SYSTEM_PROMPT_FLAGS.some((flag) => value === flag || value.startsWith(`${flag}=`)),\n )\n}\n\n/** Codex keys that can replace or contaminate the materializer's sealed instructions file. */\nconst CODEX_INSTRUCTION_KEYS = ['model_instructions_file', 'developer_instructions'] as const\n\nfunction argsSetCodexInstructionOverride(values: readonly string[]): boolean {\n for (let index = 0; index < values.length; index++) {\n const value = values[index]!\n const config =\n value === '-c' || value === '--config'\n ? values[index + 1]\n : value.startsWith('--config=')\n ? value.slice('--config='.length)\n : undefined\n if (\n config !== undefined &&\n CODEX_INSTRUCTION_KEYS.some((key) => config.trimStart().startsWith(`${key}=`))\n ) {\n return true\n }\n }\n return false\n}\n\nconst HARNESS_SYSTEM_PROMPTS = {\n 'claude-code': {\n executable: 'claude',\n project: (plan, systemPrompt, path) =>\n appendFlags(\n addPromptFile(plan, SYSTEM_PROMPT_FILE, systemPrompt),\n '--system-prompt-file',\n path,\n ),\n projectAppend: (plan, appendSystemPrompt, path) =>\n appendFlags(\n addPromptFile(plan, APPEND_SYSTEM_PROMPT_FILE, appendSystemPrompt),\n '--append-system-prompt-file',\n path,\n ),\n conflictsWithArgs: argsSetSystemPromptFlag,\n conflictsWithAppendArgs: argsSetAppendSystemPromptFlag,\n },\n /** OpenCode's bound primary agent is already selected by the materializer's --agent flag. */\n opencode: {\n executable: 'opencode',\n project: (plan) => plan,\n retainsProjectedSystemPrompt: true,\n conflictsWithArgs: (values) =>\n values.some((value) => value === '--agent' || value.startsWith('--agent=')),\n conflictsWithAppendArgs: argsSetAppendSystemPromptFlag,\n },\n pi: {\n executable: 'pi',\n project: (plan, systemPrompt, path) =>\n appendFlags(addPromptFile(plan, SYSTEM_PROMPT_FILE, systemPrompt), '--system-prompt', path),\n projectAppend: (plan, appendSystemPrompt, path) =>\n appendFlags(\n addPromptFile(plan, APPEND_SYSTEM_PROMPT_FILE, appendSystemPrompt),\n '--append-system-prompt',\n path,\n ),\n conflictsWithArgs: argsSetSystemPromptFlag,\n conflictsWithAppendArgs: argsSetAppendSystemPromptFlag,\n },\n prime: {\n executable: 'prime-agent',\n project: (plan, systemPrompt, path) =>\n appendFlags(addPromptFile(plan, SYSTEM_PROMPT_FILE, systemPrompt), '--system-prompt', path),\n projectAppend: (plan, appendSystemPrompt, path) =>\n appendFlags(\n addPromptFile(plan, APPEND_SYSTEM_PROMPT_FILE, appendSystemPrompt),\n '--append-system-prompt',\n path,\n ),\n conflictsWithArgs: argsSetSystemPromptFlag,\n conflictsWithAppendArgs: argsSetAppendSystemPromptFlag,\n },\n /** Gemini's file and env lowering is materializer-owned; this row supplies the launch proof. */\n gemini: {\n executable: 'gemini',\n project: (plan) => plan,\n conflictsWithArgs: argsSetSystemPromptFlag,\n conflictsWithAppendArgs: argsSetAppendSystemPromptFlag,\n },\n} as const satisfies Partial<Record<HarnessId, HarnessSystemPrompt>>\n\ninterface MaterializedPromptDelivery {\n readonly executable: string\n readonly delivered: (plan: AgentCandidateWorkspacePlan) => boolean\n readonly conflictsWithArgs: (values: readonly string[]) => boolean\n}\n\n/**\n * These controls are lowered by agent-profile-materialize into files plus launch inputs. The\n * candidate adapter does not own the spawn, so it must reject an arbitrary entrypoint even when\n * the plan has the right bytes: only the native binary can make those inputs effective.\n */\nconst MATERIALIZED_PROMPT_DELIVERIES = {\n codex: {\n executable: 'codex',\n delivered: (plan) =>\n plan.files.some((file) => file.relPath === '.codex/system-prompt.md') &&\n plan.flags.some((flag) => flag.value === 'model_instructions_file=.codex/system-prompt.md'),\n conflictsWithArgs: argsSetCodexInstructionOverride,\n },\n gemini: {\n executable: 'gemini',\n delivered: (plan) =>\n plan.files.some((file) => file.relPath === '.gemini/system.md') &&\n plan.env.GEMINI_SYSTEM_MD?.value === '1',\n conflictsWithArgs: argsSetSystemPromptFlag,\n },\n} as const satisfies Partial<Record<HarnessId, MaterializedPromptDelivery>>\n\n/** Project both prompt intents onto their distinct native process controls. */\nexport function projectCandidatePromptIntents(\n plan: AgentCandidateWorkspacePlan,\n launch: AgentCandidateLaunch,\n systemPromptFilePath: string,\n requestedSystemPrompt: string | undefined = plan.systemPrompt?.value,\n requestedAppendSystemPrompt: string | undefined = plan.appendSystemPrompt?.value,\n): AgentCandidateWorkspacePlan {\n const systemPrompt = plan.systemPrompt\n const appendSystemPrompt = plan.appendSystemPrompt\n const delivery = MATERIALIZED_PROMPT_DELIVERIES[\n plan.harness as keyof typeof MATERIALIZED_PROMPT_DELIVERIES\n ] as MaterializedPromptDelivery | undefined\n\n if (systemPrompt === undefined && delivery?.delivered(plan)) {\n assertProvableNativeLaunch(plan.harness, delivery.executable, launch, 'replacement')\n assertNoShadowingArgs(plan.harness, delivery.conflictsWithArgs, launch, 'replacement')\n if (requestedSystemPrompt === undefined) return plan\n return plan\n }\n\n if (requestedSystemPrompt === undefined && requestedAppendSystemPrompt === undefined) {\n return plan\n }\n\n const projection = HARNESS_SYSTEM_PROMPTS[plan.harness as keyof typeof HARNESS_SYSTEM_PROMPTS] as\n | HarnessSystemPrompt\n | undefined\n if (!projection) {\n throw new Error(`candidate system prompt has no native launch projection for ${plan.harness}`)\n }\n\n const requestedReplacement = requestedSystemPrompt !== undefined\n if (requestedReplacement && systemPrompt === undefined) {\n throw new Error(\n `profile materializer did not deliver the candidate system prompt for ${plan.harness}`,\n )\n }\n if (systemPrompt !== undefined && requestedSystemPrompt === undefined) {\n throw new Error(\n `profile materializer added an unexpected candidate system prompt for ${plan.harness}`,\n )\n }\n if (systemPrompt !== undefined && systemPrompt.value !== requestedSystemPrompt) {\n throw new Error('profile materializer changed the candidate system prompt')\n }\n if (\n appendSystemPrompt !== undefined &&\n appendSystemPrompt.value !== requestedAppendSystemPrompt\n ) {\n throw new Error('profile materializer changed the candidate append system prompt')\n }\n\n const intent = requestedReplacement ? 'replacement' : 'addition'\n assertProvableNativeLaunch(plan.harness, projection.executable, launch, intent)\n const launchArgs = (launch.args ?? []).map((value) => value.value)\n if (requestedReplacement && projection.conflictsWithArgs(launchArgs)) {\n throw new Error(\n `${plan.harness} launch arguments conflict with the candidate profile system prompt`,\n )\n }\n if (requestedAppendSystemPrompt !== undefined && projection.conflictsWithAppendArgs(launchArgs)) {\n throw new Error(\n `${plan.harness} launch arguments conflict with the candidate profile append system prompt`,\n )\n }\n\n let projected = plan\n if (systemPrompt !== undefined) {\n projected = projection.project(\n projection.retainsProjectedSystemPrompt\n ? projected\n : omitPromptIntent(projected, 'systemPrompt'),\n systemPrompt.value,\n systemPromptFilePath,\n )\n }\n if (appendSystemPrompt !== undefined) {\n if (!projection.projectAppend) {\n throw new Error(\n `candidate append system prompt has no native launch projection for ${plan.harness}`,\n )\n }\n projected = projection.projectAppend(\n omitPromptIntent(projected, 'appendSystemPrompt'),\n appendSystemPrompt.value,\n posix.join(posix.dirname(systemPromptFilePath), 'append-system-prompt.md'),\n )\n }\n // The source-profile digest binds authored values. Remove executor handoff fields only after\n // converting them into native controls; materializer-owned controls remain visible in the plan.\n return projected\n}\n\nfunction assertProvableNativeLaunch(\n harness: string,\n expectedExecutable: string,\n launch: AgentCandidateLaunch,\n intent: 'replacement' | 'addition',\n): asserts launch is AgentCandidateLaunch & { kind: 'container-command' } {\n if (launch.kind !== 'container-command') {\n throw new Error(`candidate-entrypoint launch cannot prove ${harness} system-prompt ${intent}`)\n }\n if (\n launch.executable !== expectedExecutable &&\n !(\n posix.isAbsolute(launch.executable) &&\n posix.basename(launch.executable) === expectedExecutable\n )\n ) {\n throw new Error(\n `${harness} system-prompt ${intent} requires the native ${expectedExecutable} executable`,\n )\n }\n}\n\nfunction assertNoShadowingArgs(\n harness: string,\n conflictsWithArgs: (values: readonly string[]) => boolean,\n launch: Extract<AgentCandidateLaunch, { kind: 'container-command' }>,\n intent: 'replacement' | 'addition',\n): void {\n if (conflictsWithArgs((launch.args ?? []).map((value) => value.value))) {\n throw new Error(\n `${harness} launch arguments conflict with the candidate profile ${intent === 'replacement' ? 'system' : 'append system'} prompt`,\n )\n }\n}\n\nfunction omitPromptIntent(\n plan: AgentCandidateWorkspacePlan,\n intent: 'systemPrompt' | 'appendSystemPrompt',\n): AgentCandidateWorkspacePlan {\n const projected = { ...plan }\n delete projected[intent]\n return projected\n}\n\nfunction appendFlags(\n plan: AgentCandidateWorkspacePlan,\n ...values: string[]\n): AgentCandidateWorkspacePlan {\n return {\n ...plan,\n flags: [...plan.flags, ...values.map(publicValue)],\n }\n}\n\nfunction publicValue(value: string): AgentCandidateConfigValue {\n return { kind: 'public', value }\n}\n\nfunction addPromptFile(\n plan: AgentCandidateWorkspacePlan,\n relPath: string,\n prompt: string,\n): AgentCandidateWorkspacePlan {\n // Candidate argv rejects control characters. Native prompt-file loading preserves multiline\n // bytes without weakening the shared process schema.\n if (plan.files.some((file) => file.relPath === relPath)) {\n throw new Error(`candidate profile conflicts with reserved ${relPath}`)\n }\n return {\n ...plan,\n files: [\n ...plan.files,\n {\n relPath,\n content: prompt,\n source: 'generated',\n },\n ],\n }\n}\n","import { posix } from 'node:path'\n\nimport type {\n AgentCandidateConfigValue,\n AgentCandidateLaunch,\n AgentCandidateProfile,\n AgentCandidateProfileActivation,\n AgentCandidateProfilePlanEvidence,\n AgentCandidateResourceRef,\n AgentProfile,\n AgentProfileConfigValue,\n AgentProfileDiff,\n AgentProfileMcpServer,\n AgentProfileResourceRef,\n HarnessType,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\nimport {\n agentCandidateProfileActivationSchema,\n agentCandidateProfileSchema,\n agentProfileDiffSchema,\n agentProfileSchema,\n applyAgentProfileDiff,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentCandidateWorkspacePlan,\n HarnessId,\n} from '@tangle-network/agent-profile-materialize'\nimport {\n isMaterializerHarness,\n materializeCandidateProfile,\n resolvePiRuntimePaths,\n} from '@tangle-network/agent-profile-materialize'\n\nimport { ValidationError } from '../errors'\nimport {\n canonicalCandidateBytes,\n canonicalCandidateDigest,\n canonicalCandidateDocument,\n embeddedCandidateArtifact,\n immutableCandidateValue,\n omitTopLevelDigest,\n sha256Bytes,\n} from './digest'\nimport { projectCandidatePromptIntents } from './system-prompt'\n\nexport function candidateMaterializerHarness(harness: HarnessType): HarnessId {\n if (!isMaterializerHarness(harness)) {\n throw new Error(\n `sealed candidate profile materialization is unsupported for harness ${harness}`,\n )\n }\n return harness\n}\n\n/** Runtime applies the materializer's launch flags to the candidate process. */\nexport const CANDIDATE_PROFILE_MATERIALIZER_BINDS = ['systemPrompt'] as const\nexport const PI_CANDIDATE_AGENT_DIR_ENV = 'PI_CODING_AGENT_DIR'\nexport const PI_CANDIDATE_SESSION_DIR_ENV = 'PI_CODING_AGENT_SESSION_DIR'\n\ninterface MaterializeAgentCandidateProfilePlanOptions {\n profile: AgentCandidateProfile\n harness: HarnessType\n launch: AgentCandidateLaunch\n workspace: 'task' | 'candidate'\n workspaces: {\n taskRoot: string\n candidateRoot?: string\n }\n resolvedResources?: ReadonlyMap<Sha256Digest, string>\n}\n\n/** Derive the exact native profile plan used by preparation and later evidence checks. */\nexport function materializeAgentCandidateProfilePlan(\n options: MaterializeAgentCandidateProfilePlanOptions,\n): AgentCandidateWorkspacePlan {\n const root =\n options.workspace === 'task' ? options.workspaces.taskRoot : options.workspaces.candidateRoot\n if (!root) throw new Error('candidate profile target is missing its execution workspace root')\n const plan = materializeCandidateProfile(\n options.profile,\n candidateMaterializerHarness(options.harness),\n {\n binds: CANDIDATE_PROFILE_MATERIALIZER_BINDS,\n resolvedResources: options.resolvedResources,\n },\n )\n return projectCandidatePromptIntents(\n plan,\n options.launch,\n posix.join(root, '.tangle/system-prompt.md'),\n options.profile.prompt?.systemPrompt,\n options.profile.prompt?.appendSystemPrompt,\n )\n}\n\n/** Resolve the private Pi roots needed by an agent-root profile plan. */\nexport function candidateProfileAgentPaths(\n plan: {\n harness: HarnessType\n files: ReadonlyArray<{ root?: 'agent' | 'workspace' }>\n },\n runtimeHome: string | undefined,\n): { agentDir: string; sessionDir: string } | undefined {\n if (!plan.files.some((file) => file.root === 'agent')) return undefined\n if (plan.harness !== 'pi') {\n throw new Error(`candidate profile agent-root files are unsupported for ${plan.harness}`)\n }\n if (runtimeHome === undefined) {\n throw new Error('candidate profile agent-root files require executionRoots.profileRoot')\n }\n return resolvePiRuntimePaths(runtimeHome)\n}\n\n/** Bind exact native profile text to the canonical plan captured during preparation. */\nexport function createAgentCandidateProfileActivation(\n plan: AgentCandidateWorkspacePlan,\n profilePlan: AgentCandidateProfilePlanEvidence,\n): AgentCandidateProfileActivation {\n const sourceByIdentity = new Map(\n plan.files.map((file) => [profileFileIdentity(file.root, file.relPath), file]),\n )\n if (sourceByIdentity.size !== plan.files.length) {\n throw new Error('candidate profile activation contains duplicate rooted native file paths')\n }\n const files = profilePlan.material.files.map((expected) => {\n const source = sourceByIdentity.get(profileFileIdentity(expected.root, expected.relPath))\n if (!source) {\n throw new Error(\n `candidate profile activation is missing ${profileFileLabel(expected.root, expected.relPath)}`,\n )\n }\n const mode = source.mode ?? 0o644\n if (!Number.isSafeInteger(mode) || mode < 0 || mode > 0o777) {\n throw new Error(\n `candidate profile activation has invalid mode for ${profileFileLabel(expected.root, expected.relPath)}`,\n )\n }\n return { path: expected.relPath, mode, content: source.content }\n })\n if (files.length !== plan.files.length) {\n throw new Error('candidate profile activation contains unplanned native files')\n }\n return parseAgentCandidateProfileActivation(\n canonicalCandidateDocument<AgentCandidateProfileActivation>({\n kind: 'agent-candidate-profile-activation',\n profilePlan,\n files,\n }).value,\n profilePlan.digest,\n )\n}\n\nfunction profileFileIdentity(root: 'agent' | 'workspace' | undefined, relPath: string): string {\n return `${root ?? 'workspace'}\\0${relPath}`\n}\n\nfunction profileFileLabel(root: 'agent' | 'workspace' | undefined, relPath: string): string {\n return root === 'agent' ? `agent:${relPath}` : relPath\n}\n\n/** Parse and check every native file hash plus both canonical document digests. */\nexport function parseAgentCandidateProfileActivation(\n input: unknown,\n expectedProfilePlanDigest?: AgentCandidateProfilePlanEvidence['digest'],\n): AgentCandidateProfileActivation {\n const activation = agentCandidateProfileActivationSchema.parse(input)\n const planBytes = canonicalCandidateBytes(activation.profilePlan.material)\n const profilePlanArtifact = activation.profilePlan.artifact\n if (\n sha256Bytes(planBytes) !== activation.profilePlan.digest ||\n profilePlanArtifact.sha256 !== activation.profilePlan.digest ||\n profilePlanArtifact.byteLength !== planBytes.byteLength ||\n ('content' in profilePlanArtifact &&\n !Buffer.from(profilePlanArtifact.content, 'base64').equals(Buffer.from(planBytes))) ||\n (expectedProfilePlanDigest !== undefined &&\n activation.profilePlan.digest !== expectedProfilePlanDigest)\n ) {\n throw new Error('candidate profile activation has an invalid canonical profile plan')\n }\n if (canonicalCandidateDigest(omitTopLevelDigest(activation)) !== activation.digest) {\n throw new Error('candidate profile activation digest does not match')\n }\n return immutableCandidateValue(activation)\n}\n\nconst CANDIDATE_PROFILE_DIRECT_FIELDS = [\n 'name',\n 'description',\n 'version',\n 'tags',\n 'prompt',\n 'harness',\n 'permissions',\n 'tools',\n 'confidential',\n] as const\n\n/** Convert only behavior-preserving generic profile fields into the closed candidate contract. */\nexport function freezeGenericAgentCandidateProfile(input: AgentProfile): AgentCandidateProfile {\n refuseFieldsSandboxCannotCarry(input)\n const profile = parseExactAgentProfile(input, 'profile')\n return candidateProfileFromGenericProfile(profile)\n}\n\n/**\n * Keep every generic-profile-to-candidate conversion in one place.\n * Callers use this both when sealing a new bundle and when proving a measured\n * profile is exactly the profile in an existing candidate.\n */\nfunction candidateProfileFromGenericProfile(profile: AgentProfile): AgentCandidateProfile {\n assertResolvedKnowledgeResources(profile.resources)\n if (profile.connections !== undefined) unsupportedProfileField('connections')\n if (profile.metadata !== undefined) unsupportedProfileField('metadata')\n if (profile.extensions !== undefined) unsupportedProfileField('extensions')\n if (profile.model?.metadata !== undefined) unsupportedProfileField('model.metadata')\n\n const candidate: Record<string, unknown> = {}\n copyDirectProfileFields(candidate, profile as Record<string, unknown>)\n if (profile.model) {\n const { metadata: _metadata, ...model } = profile.model\n candidate.model = model\n }\n if (profile.mcp) candidate.mcp = freezeMcpServers(profile.mcp)\n if (profile.subagents) {\n candidate.subagents = Object.fromEntries(\n Object.entries(profile.subagents).map(([name, subagent]) => {\n if (subagent.metadata !== undefined) unsupportedProfileField(`subagents.${name}.metadata`)\n const { metadata: _metadata, ...value } = subagent\n return [name, value]\n }),\n )\n }\n if (profile.resources) candidate.resources = freezeResources(profile.resources)\n if (profile.hooks && Object.values(profile.hooks).some((commands) => commands.length > 0)) {\n throw new Error(\n 'generic AgentProfile hooks cannot be safely tokenized; use a candidate-profile source with executable/args',\n )\n }\n if (profile.hooks) candidate.hooks = profile.hooks\n if (profile.modes) {\n candidate.modes = Object.fromEntries(\n Object.entries(profile.modes).map(([name, mode]) => {\n if (mode.metadata !== undefined) unsupportedProfileField(`modes.${name}.metadata`)\n const { metadata: _metadata, ...value } = mode\n return [name, value]\n }),\n )\n }\n const parsed = parseExactCandidateProfile(candidate)\n return parsed\n}\n\n/** Prove the measured generic profile and sealed candidate profile describe the same behavior. */\nexport function assertCandidateProfileBinding(\n measuredInput: unknown,\n bundled: AgentCandidateProfile,\n): void {\n refuseFieldsSandboxCannotCarry(measuredInput)\n const measured = parseExactAgentProfile(measuredInput, 'measured agent profile')\n const expected = candidateProfileFromGenericProfile(measured)\n if (canonicalCandidateDigest(expected) !== canonicalCandidateDigest(bundled)) {\n throw new Error('measured agent profile does not match sealed candidate profile')\n }\n}\n\n/** Parse a complete profile without silently discarding unsupported fields. */\nexport function parseExactAgentProfile(input: unknown, label: string): AgentProfile {\n let parsed: AgentProfile\n try {\n parsed = agentProfileSchema.parse(input) as AgentProfile\n } catch (cause) {\n throw new Error(`${label} contains unsupported or non-canonical fields`, { cause })\n }\n assertCanonicalParse(input, parsed, label)\n return parsed\n}\n\n/** Parse a profile diff without silently discarding unsupported fields. */\nexport function parseExactAgentProfileDiff(input: unknown, label: string): AgentProfileDiff {\n let parsed: AgentProfileDiff\n try {\n parsed = agentProfileDiffSchema.parse(input) as AgentProfileDiff\n } catch (cause) {\n throw new Error(`${label} contains unsupported or non-canonical fields`, { cause })\n }\n assertCanonicalParse(input, parsed, label)\n return parsed\n}\n\n/** Apply one exact diff and reject any value that cannot be preserved canonically. */\nexport function applyExactAgentProfileDiff(\n baseInput: unknown,\n diffInput: unknown,\n label: string,\n): AgentProfile {\n const base = parseExactAgentProfile(baseInput, `${label} base profile`)\n const diff = parseExactAgentProfileDiff(diffInput, `${label} diff`)\n const applied = omitUndefinedObjectFields(applyAgentProfileDiff(base, diff), label)\n return parseExactAgentProfile(applied, `${label} result`)\n}\n\n/** Parse a candidate profile without silently discarding unsupported or non-canonical fields. */\nexport function parseExactCandidateProfile(input: unknown): AgentCandidateProfile {\n const parsed = agentCandidateProfileSchema.parse(input)\n assertCanonicalParse(input, parsed, 'candidate profile')\n return parsed\n}\n\n/** Reject profile fields whose behavioral effect is not yet proven by candidate executors. */\nexport function assertCandidateProfileExecutionSupport(profile: AgentCandidateProfile): void {\n assertResolvedKnowledgeResources(profile.resources)\n refuseFieldsSandboxCannotCarry(profile)\n const fields = ['tools', 'permissions', 'modes', 'confidential'] as const\n const unsupported = fields.filter((field) => hasEntries(profile[field]))\n if (unsupported.length > 0) {\n throw new Error(\n `candidate execution cannot prove in-session effects for non-empty AgentProfile fields: ${unsupported.join(', ')}`,\n )\n }\n}\n\n/** Convert the candidate profile contract into the portable interface profile it represents. */\nexport function agentCandidateProfileAsAgentProfile(\n candidate: AgentCandidateProfile,\n): AgentProfile {\n assertResolvedKnowledgeResources(candidate.resources)\n refuseFieldsSandboxCannotCarry(candidate)\n const output: Record<string, unknown> = {}\n copyDirectProfileFields(output, candidate as unknown as Record<string, unknown>)\n if (candidate.model) output.model = { ...candidate.model }\n if (candidate.mcp) {\n output.mcp = Object.fromEntries(\n Object.entries(candidate.mcp).map(([name, server]) => [\n name,\n {\n ...server,\n // Candidate config values ({kind:'public', value}) are already valid\n // AgentProfileConfigValue entries under interface >=0.40 — clone them\n // rather than unwrapping to plain strings, which the 0.40 profile\n // schema rejects.\n ...(server.args ? { args: server.args.map((value) => ({ ...value })) } : {}),\n ...(server.env ? { env: cloneRecord(server.env) } : {}),\n },\n ]),\n )\n }\n if (candidate.subagents) output.subagents = cloneRecord(candidate.subagents)\n if (candidate.modes) output.modes = cloneRecord(candidate.modes)\n if (candidate.hooks) {\n output.hooks = Object.fromEntries(\n Object.entries(candidate.hooks).map(([event, hooks]) => [\n event,\n hooks.map(({ executable, args, env, ...hook }) => ({\n ...hook,\n command: [executable, ...(args ?? []).map(publicValue)].map(shellQuote).join(' '),\n // Hook env stays in config-value form: the 0.40 profile hook contract\n // types env as Record<string, AgentProfileConfigValue>.\n ...(env ? { env: cloneRecord(env) } : {}),\n })),\n ]),\n )\n }\n if (candidate.resources) {\n if (candidate.resources.failOnError !== true) {\n throw new Error('sealed candidate profile contains fields unsupported by generic profiles')\n }\n output.resources = {\n failOnError: true,\n ...(candidate.resources.files\n ? {\n files: candidate.resources.files.map((file) => ({\n ...file,\n resource: publicResource(file.resource),\n })),\n }\n : {}),\n ...(candidate.resources.tools\n ? { tools: candidate.resources.tools.map(publicResource) }\n : {}),\n ...(candidate.resources.skills\n ? { skills: candidate.resources.skills.map(publicResource) }\n : {}),\n ...(candidate.resources.agents\n ? { agents: candidate.resources.agents.map(publicResource) }\n : {}),\n ...(candidate.resources.commands\n ? { commands: candidate.resources.commands.map(publicResource) }\n : {}),\n ...(candidate.resources.instructions !== undefined\n ? {\n instructions:\n typeof candidate.resources.instructions === 'string'\n ? candidate.resources.instructions\n : publicResource(candidate.resources.instructions),\n }\n : {}),\n }\n }\n return output as AgentProfile\n}\n\n/** Recursively remove undefined object fields while refusing undefined array entries. */\nexport function omitUndefinedObjectFields(value: unknown, path: string): unknown {\n if (Array.isArray(value)) {\n return value.map((entry, index) => {\n if (entry === undefined) {\n throw new Error(`${path} produced an undefined array entry at ${index}`)\n }\n return omitUndefinedObjectFields(entry, `${path}[${index}]`)\n })\n }\n if (value === null || typeof value !== 'object') return value\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>)\n .filter(([, entry]) => entry !== undefined)\n .map(([key, entry]) => [key, omitUndefinedObjectFields(entry, `${path}.${key}`)]),\n )\n}\n\nfunction freezeMcpServers(servers: Record<string, AgentProfileMcpServer>): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(servers).map(([name, server]) => {\n if (server.transport !== undefined && server.transport !== 'stdio') {\n unsupportedProfileField(`mcp.${name}.transport=${server.transport}`)\n }\n if (server.url !== undefined) unsupportedProfileField(`mcp.${name}.url`)\n if (server.headers !== undefined) unsupportedProfileField(`mcp.${name}.headers`)\n if (server.metadata !== undefined) unsupportedProfileField(`mcp.${name}.metadata`)\n return [\n name,\n {\n ...(server.transport ? { transport: server.transport } : {}),\n ...(server.command ? { command: server.command } : {}),\n ...(server.args\n ? {\n args: server.args.map((value, index) =>\n candidatePublicValue(value, `mcp.${name}.args[${index}]`),\n ),\n }\n : {}),\n ...(server.env ? { env: mapCandidatePublicValues(server.env, `mcp.${name}.env`) } : {}),\n ...(server.cwd ? { cwd: server.cwd } : {}),\n ...(server.enabled === undefined ? {} : { enabled: server.enabled }),\n },\n ]\n }),\n )\n}\n\n/** A newer peer may admit knowledge pins that these candidate conversions cannot preserve. */\nfunction assertResolvedKnowledgeResources(resources: unknown): void {\n if (\n resources !== null &&\n typeof resources === 'object' &&\n 'knowledge' in resources &&\n resources.knowledge !== undefined\n ) {\n throw new Error(\n 'candidate profile resources.knowledge must be owner-authorized and resolved before candidate conversion or execution',\n )\n }\n}\n\n/**\n * Interface 5.3 admits profile `proxySecrets` and candidate secret-ref config values, but\n * Sandbox still ships its own Interface 4.0.0, which carries neither. Refuse them by name\n * rather than drop them; remove this once Sandbox adopts Interface 5.3.\n */\nfunction refuseFieldsSandboxCannotCarry(profile: unknown): void {\n if (!isRecord(profile)) return\n if (profile.proxySecrets !== undefined) refuseFieldSandboxCannotCarry('proxySecrets')\n if (isRecord(profile.mcp)) {\n for (const [name, server] of Object.entries(profile.mcp)) {\n if (!isRecord(server)) continue\n refuseNonPublicConfigValues(server.args, `mcp.${name}.args`)\n refuseNonPublicConfigValues(server.env, `mcp.${name}.env`)\n }\n }\n if (isRecord(profile.hooks)) {\n for (const [event, hooks] of Object.entries(profile.hooks)) {\n if (!Array.isArray(hooks)) continue\n for (const [index, hook] of hooks.entries()) {\n if (!isRecord(hook)) continue\n refuseNonPublicConfigValues(hook.args, `hooks.${event}[${index}].args`)\n refuseNonPublicConfigValues(hook.env, `hooks.${event}[${index}].env`)\n }\n }\n }\n}\n\nfunction refuseNonPublicConfigValues(values: unknown, path: string): void {\n const entries = Array.isArray(values)\n ? values.map((value, index) => [`${path}[${index}]`, value] as const)\n : isRecord(values)\n ? Object.entries(values).map(([name, value]) => [`${path}.${name}`, value] as const)\n : []\n for (const [field, value] of entries) {\n if (isRecord(value) && value.kind !== 'public') {\n refuseFieldSandboxCannotCarry(`${field} (${String(value.kind)})`)\n }\n }\n}\n\nfunction refuseFieldSandboxCannotCarry(field: string): never {\n throw new ValidationError(\n `candidate profile field ${field} is refused: Sandbox's Interface 4.0.0 cannot carry it yet, and Runtime does not drop it`,\n )\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n}\n\nfunction freezeResources(resources: NonNullable<AgentProfile['resources']>): unknown {\n if (resources.failOnError !== true) {\n throw new Error('candidate profile resources require failOnError: true')\n }\n return {\n failOnError: true,\n ...(resources.files\n ? {\n files: resources.files.map((file) => ({\n ...file,\n resource: freezeResource(file.resource),\n })),\n }\n : {}),\n ...(resources.tools ? { tools: resources.tools.map(freezeResource) } : {}),\n ...(resources.skills ? { skills: resources.skills.map(freezeResource) } : {}),\n ...(resources.agents ? { agents: resources.agents.map(freezeResource) } : {}),\n ...(resources.commands ? { commands: resources.commands.map(freezeResource) } : {}),\n ...(resources.instructions === undefined\n ? {}\n : {\n instructions:\n typeof resources.instructions === 'string'\n ? resources.instructions\n : freezeResource(resources.instructions),\n }),\n }\n}\n\nfunction freezeResource(resource: AgentProfileResourceRef): AgentCandidateResourceRef {\n if (resource.kind === 'github') {\n throw new Error(\n 'generic GitHub profile resources do not carry byte identity; use a candidate-profile source with a pinned commit, digest, and byte length',\n )\n }\n const bytes = Buffer.from(resource.content, 'utf8')\n return {\n ...resource,\n sha256: embeddedCandidateArtifact(bytes).sha256,\n byteLength: bytes.byteLength,\n }\n}\n\nfunction copyDirectProfileFields(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n): void {\n for (const key of CANDIDATE_PROFILE_DIRECT_FIELDS) {\n if (source[key] !== undefined) target[key] = source[key]\n }\n}\n\nfunction assertCanonicalParse(input: unknown, parsed: unknown, label: string): void {\n if (!Buffer.from(canonicalCandidateBytes(input)).equals(canonicalCandidateBytes(parsed))) {\n throw new Error(`${label} contains unsupported or non-canonical fields`)\n }\n}\n\nfunction publicResource(resource: AgentCandidateResourceRef): unknown {\n if (resource.kind === 'inline') {\n return { kind: 'inline', name: resource.name, content: resource.content }\n }\n return {\n kind: 'github',\n repository: `${resource.repository.owner}/${resource.repository.repo}`,\n path: resource.path,\n ref: resource.commit,\n ...(resource.name ? { name: resource.name } : {}),\n }\n}\n\n/** Freeze one profile config value into the candidate's PUBLIC-only config\n * shape. A secret-ref is refused, never silently dropped or unwrapped. */\nfunction candidatePublicValue(\n value: AgentProfileConfigValue,\n path: string,\n): { kind: 'public'; value: string } {\n if (value.kind !== 'public') refuseFieldSandboxCannotCarry(`${path} (${value.kind})`)\n return { kind: 'public', value: value.value }\n}\n\nfunction mapCandidatePublicValues(\n values: Record<string, AgentProfileConfigValue>,\n pathPrefix: string,\n): Record<string, { kind: 'public'; value: string }> {\n return Object.fromEntries(\n Object.entries(values).map(([name, value]) => [\n name,\n candidatePublicValue(value, `${pathPrefix}.${name}`),\n ]),\n )\n}\n\nfunction publicValue(value: AgentCandidateConfigValue): string {\n return value.value\n}\n\nfunction cloneRecord<T>(values: Record<string, T>): Record<string, T> {\n return Object.fromEntries(\n Object.entries(values).map(([key, value]) => [key, { ...value }]),\n ) as Record<string, T>\n}\n\nfunction hasEntries(value: unknown): boolean {\n return value !== undefined && value !== null && typeof value === 'object'\n ? Object.keys(value).length > 0\n : false\n}\n\nfunction shellQuote(value: string): string {\n return /^[A-Za-z0-9_./:@%+=,-]+$/.test(value) ? value : `'${value.replaceAll(\"'\", `'\"'\"'`)}'`\n}\n\nfunction unsupportedProfileField(path: string): never {\n throw new Error(\n `generic AgentProfile field ${path} is not representable in a sealed candidate profile`,\n )\n}\n"],"mappings":";;;;;;AAWA,MAAM,qBAAqB;AAC3B,MAAM,4BAA4B;AA8BlC,MAAM,sBAAsB,CAAC,mBAAmB,sBAAsB;AACtE,MAAM,6BAA6B,CACjC,0BACA,6BACF;AAEA,SAAS,wBAAwB,QAAoC;CACnE,OAAO,OAAO,MAAM,UAClB,oBAAoB,MAAM,SAAS,UAAU,QAAQ,MAAM,WAAW,GAAG,KAAK,EAAE,CAAC,CACnF;AACF;AAEA,SAAS,8BAA8B,QAAoC;CACzE,OAAO,OAAO,MAAM,UAClB,2BAA2B,MAAM,SAAS,UAAU,QAAQ,MAAM,WAAW,GAAG,KAAK,EAAE,CAAC,CAC1F;AACF;;AAGA,MAAM,yBAAyB,CAAC,2BAA2B,wBAAwB;AAEnF,SAAS,gCAAgC,QAAoC;CAC3E,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,QAAQ,SAAS;EAClD,MAAM,QAAQ,OAAO;EACrB,MAAM,SACJ,UAAU,QAAQ,UAAU,aACxB,OAAO,QAAQ,KACf,MAAM,WAAW,WAAW,IAC1B,MAAM,MAAM,CAAkB,IAC9B,KAAA;EAC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KAAK,CAAC,CAAC,SAAS,IAC5B;AACN;AAEA,SAAS,WAAW,OAAuB;CACzC,OAAO,2BAA2B,KAAK,KAAK,IAAI,QAAQ,IAAI,MAAM,WAAW,KAAK,OAAO,EAAE;AAC7F;AAEA,SAAS,wBAAwB,MAAqB;CACpD,MAAM,IAAI,MACR,8BAA8B,KAAK,oDACrC;AACF"}
@@ -1,4 +1,4 @@
1
- import { Bb as UiLens, Fb as UI_FINDING_SEVERITIES, Gb as ResearchSource, Hb as KnowledgeUpdate, Ib as UI_LENSES, Jb as createResearcherValidator, Jx as CoderTask, Kb as ResearchTask, Lb as UiFinding, Rb as UiFindingScreenshot, Ub as MultiHarnessResearcherFanoutOptions, Vb as KnowledgeItem, Wb as ResearchOutput, Xb as researcherProfile, Yb as multiHarnessResearcherFanout, Yx as coderTaskToPrompt, qb as ResearcherProfileOptions, zb as UiFindingSeverity } from "./index-Da7w2H86.js";
1
+ import { $b as UiFindingSeverity, Qb as UiFindingScreenshot, Xb as UI_LENSES, Yb as UI_FINDING_SEVERITIES, Zb as UiFinding, ax as ResearchSource, cS as CoderTask, cx as createResearcherValidator, ex as UiLens, ix as ResearchOutput, lS as coderTaskToPrompt, lx as multiHarnessResearcherFanout, nx as KnowledgeUpdate, ox as ResearchTask, rx as MultiHarnessResearcherFanoutOptions, sx as ResearcherProfileOptions, tx as KnowledgeItem, ux as researcherProfile } from "./index-BxiHetnG.js";
2
2
  import { SandboxEvent } from "@tangle-network/sandbox";
3
3
  //#region src/profiles/ui-auditor/lens-prompts.d.ts
4
4
  /** Cross-lens rules injected into every UI audit iteration: finding quality standards and scope limits. @experimental */
@@ -1,6 +1,6 @@
1
1
  import { L as immutableCandidateValue, M as canonicalCandidateBytes, N as canonicalCandidateDigest, _ as assertExactObjectKeys, z as sha256Bytes } from "./workspace-streams-DFAhW7hF.js";
2
- import { b as assertAgentCandidateExecutionRoots, d as sealAgentCandidateModelSettlement, f as usdToNanos, i as candidateKnowledgeExecutionPaths } from "./prepare-DjCLEN-q.js";
3
- import { s as candidateProfileAgentPaths } from "./profile-DmVM4Gxb.js";
2
+ import { b as assertAgentCandidateExecutionRoots, d as sealAgentCandidateModelSettlement, f as usdToNanos, i as candidateKnowledgeExecutionPaths } from "./prepare-CFQLx9e3.js";
3
+ import { s as candidateProfileAgentPaths } from "./profile-BTbpdL9h.js";
4
4
  import { posix } from "node:path";
5
5
  import { isDeepStrictEqual } from "node:util";
6
6
  //#region src/candidate-execution/exact-process-executor.ts
@@ -763,4 +763,4 @@ function record(value, label) {
763
763
  //#endregion
764
764
  export { exactProcessProviderAsCandidateExecutor as n, createProtectedAgentCandidateModelPort as t };
765
765
 
766
- //# sourceMappingURL=protected-model-port-D1fcnYdj.js.map
766
+ //# sourceMappingURL=protected-model-port-f1N2f0Uq.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"protected-model-port-D1fcnYdj.js","names":["isSha256Digest"],"sources":["../src/candidate-execution/exact-process-executor.ts","../src/candidate-execution/protected-model-port.ts"],"sourcesContent":["import { posix } from 'node:path'\nimport { isDeepStrictEqual } from 'node:util'\n\nimport type { TraceStore } from '@tangle-network/agent-eval'\nimport type { AgentCandidateTermination, Sha256Digest } from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironmentCapabilities,\n AgentEnvironmentProvider,\n AgentExactProcess,\n AgentExactProcessEnvironment,\n AgentExactProcessLaunch,\n AgentExactProcessResources,\n AgentExactProcessStatus,\n} from '@tangle-network/agent-interface/environment-provider'\nimport {\n canonicalCandidateBytes,\n canonicalCandidateDigest,\n immutableCandidateValue,\n sha256Bytes,\n} from './digest'\nimport { assertAgentCandidateExecutionRoots } from './execution-roots'\nimport {\n CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV,\n CANDIDATE_KNOWLEDGE_ROOT_ENV,\n candidateKnowledgeExecutionPaths,\n} from './knowledge'\nimport {\n candidateProfileAgentPaths,\n PI_CANDIDATE_AGENT_DIR_ENV,\n PI_CANDIDATE_SESSION_DIR_ENV,\n} from './profile'\nimport type {\n AgentCandidateExecutorPort,\n AgentCandidateExecutorRequest,\n AgentCandidateExecutorStopRequest,\n} from './types'\n\nconst DEFAULT_PROVISION_TIMEOUT_MS = 120_000\nconst DEFAULT_RECOVERY_RETENTION_MS = 15 * 60_000\n\ninterface ExactProcessRunState {\n environment: AgentExactProcessEnvironment\n output?: Uint8Array\n termination?: AgentCandidateTermination\n runtimeTermination?: AgentCandidateTermination\n trace?: {\n runId: string\n scenarioId: string\n startedAt: number\n deadlineAtMs: number\n timeoutMs: number\n tags: Record<string, string>\n written: boolean\n }\n}\n\nexport interface ExactProcessCandidateExecutorOptions {\n provider: AgentEnvironmentProvider\n resources: AgentExactProcessResources\n provisionTimeoutMs?: number\n recoveryRetentionMs?: number\n providerOptions?: Record<string, unknown>\n}\n\n/** Adapt one neutral exact-process provider to Runtime's trusted candidate boundary. */\nexport function exactProcessProviderAsCandidateExecutor(\n options: ExactProcessCandidateExecutorOptions,\n): AgentCandidateExecutorPort {\n return new ExactProcessAgentCandidateExecutor(options)\n}\n\nclass ExactProcessAgentCandidateExecutor implements AgentCandidateExecutorPort {\n private readonly states = new Map<string, ExactProcessRunState>()\n private readonly exactProcess\n private readonly resources: AgentExactProcessResources\n private readonly provisionTimeoutMs: number\n private readonly recoveryRetentionMs: number\n private readonly providerOptions?: Record<string, unknown>\n private capabilitiesPromise?: Promise<AgentEnvironmentCapabilities>\n\n constructor(private readonly options: ExactProcessCandidateExecutorOptions) {\n if (!options.provider.exactProcess) {\n throw new Error(\n `agent environment provider \"${options.provider.name}\" does not implement exact processes`,\n )\n }\n this.exactProcess = options.provider.exactProcess\n this.resources = exactResources(options.resources)\n this.provisionTimeoutMs = positiveInteger(\n options.provisionTimeoutMs ?? DEFAULT_PROVISION_TIMEOUT_MS,\n 'exact process provision timeout',\n )\n this.recoveryRetentionMs = positiveInteger(\n options.recoveryRetentionMs ?? DEFAULT_RECOVERY_RETENTION_MS,\n 'exact process recovery retention',\n )\n this.providerOptions = options.providerOptions\n ? immutableCandidateValue(options.providerOptions)\n : undefined\n }\n\n async execute(\n request: AgentCandidateExecutorRequest,\n context: Parameters<AgentCandidateExecutorPort['execute']>[1],\n ) {\n assertSupportedRequest(request)\n const outcome = request.benchmark.task.outcome\n if (outcome.kind !== 'output') throw new Error('exact process executor requires an output task')\n const network = request.executionPlan.value.material.model.access.network\n const egress =\n network.mode === 'disabled'\n ? ({ mode: 'blocked' } as const)\n : ({ mode: 'strict', allowDomains: [...network.domains] } as const)\n await this.assertCapability(egress.mode)\n context.signal.throwIfAborted()\n\n const key = executionKey(request.executionId, request.executionPlan.value.digest)\n if (this.states.has(key)) throw new Error('candidate execution environment is already active')\n const image = exactImage(\n request.executionPlan.value.material.container.image,\n request.executionPlan.value.material.container.manifestDigest,\n )\n const maxLifetimeMs = environmentLifetimeMs(\n request.hardLimits.timeoutMs,\n this.recoveryRetentionMs,\n )\n const createMaterial = immutableCandidateValue({\n kind: 'agent-candidate-exact-process-create',\n provider: this.options.provider.name,\n executionId: request.executionId,\n executionPlanDigest: request.executionPlan.value.digest,\n image,\n egress,\n maxLifetimeMs,\n provisionTimeoutMs: this.provisionTimeoutMs,\n resources: this.resources,\n output: { mediaType: outcome.mediaType, maxBytes: outcome.maxBytes },\n ...(this.providerOptions ? { providerOptions: this.providerOptions } : {}),\n })\n const createInputDigest = canonicalCandidateDigest(createMaterial)\n const metadata = immutableCandidateValue({\n kind: 'agent-candidate-execution',\n provider: this.options.provider.name,\n executionId: request.executionId,\n executionPlanDigest: request.executionPlan.value.digest,\n createInputDigest,\n outputMediaType: outcome.mediaType,\n outputMaxBytes: outcome.maxBytes,\n })\n const environment = await this.exactProcess.create({\n image,\n egress,\n maxLifetimeMs,\n provisionTimeoutMs: this.provisionTimeoutMs,\n resources: this.resources,\n metadata,\n idempotencyKey: executionIdempotencyKey(\n request.executionId,\n request.executionPlan.value.digest,\n ),\n signal: context.signal,\n ...(this.providerOptions ? { providerOptions: this.providerOptions } : {}),\n })\n try {\n assertExecutionEnvironment(environment, metadata, this.options.provider.name)\n } catch (error) {\n try {\n await environment.destroy()\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n 'exact process validation and cleanup both failed',\n )\n }\n throw error\n }\n const state: ExactProcessRunState = { environment }\n this.states.set(key, state)\n\n const existing = await environment.process.list()\n if (existing.length !== 0) {\n throw new Error('fresh candidate environment already contains a process')\n }\n await materializeRequest(environment, request, context.signal)\n const launch = exactLaunch(request)\n const startedAt = Date.now()\n state.trace = {\n runId: request.trace.runId,\n scenarioId: request.benchmark.task.scenario.id,\n startedAt,\n deadlineAtMs: context.deadlineAtMs,\n timeoutMs: request.hardLimits.timeoutMs,\n tags: {\n ...request.trace.tags,\n environmentId: environment.id,\n environmentProvider: environment.provider,\n },\n written: false,\n }\n const process = await environment.process.spawn(launch, { signal: context.signal })\n const outputPromise = collectOutput(process, outcome.maxBytes)\n void outputPromise.catch(() => undefined)\n let cancellation: Promise<void> | undefined\n let processExited = false\n const cancel = () => {\n if (!processExited) cancellation ??= stopProcess(process)\n }\n context.signal.addEventListener('abort', cancel, { once: true })\n if (context.signal.aborted) cancel()\n try {\n const termination = await process.wait()\n processExited = true\n context.signal.removeEventListener('abort', cancel)\n if (cancellation) await cancellation\n const status = await process.status()\n assertTerminalStatus(status, termination)\n state.output = await awaitOutput(outputPromise, context.signal, context.deadlineAtMs)\n state.termination = termination\n await appendExactProcessTrace(state, context.traceStore, status)\n return { executionId: request.executionId, termination }\n } finally {\n context.signal.removeEventListener('abort', cancel)\n }\n }\n\n async stop(\n request: AgentCandidateExecutorStopRequest,\n context: Parameters<AgentCandidateExecutorPort['stop']>[1],\n ): Promise<{ readonly stopped: true }> {\n await this.assertCapability()\n context.signal.throwIfAborted()\n const environment = await this.resolve(request, true)\n if (!environment) return { stopped: true }\n let statuses = await environment.process.list()\n if (statuses.length > 1) {\n throw new Error('candidate exact process environment contains more than one process')\n }\n const status = statuses[0]\n if (status?.running) {\n const process = await environment.process.get(status.pid)\n if (!process) throw new Error('candidate environment lost its running process handle')\n await stopProcess(process)\n }\n context.signal.throwIfAborted()\n statuses = await environment.process.list()\n if (statuses.some((entry) => entry.running)) {\n throw new Error('candidate exact process termination is not proven')\n }\n const finalStatus = statuses[0]\n if (finalStatus) assertTerminalStatus(finalStatus)\n const state = this.states.get(executionKey(request.executionId, request.executionPlanDigest))\n if (state) {\n state.termination = finalStatus?.termination ?? state.termination\n if (context.reason === 'timeout' && state.trace) {\n state.runtimeTermination = {\n kind: 'timeout',\n timeoutMs: state.trace.timeoutMs,\n }\n }\n await appendExactProcessTrace(state, context.traceStore, finalStatus)\n }\n return { stopped: true }\n }\n\n async capture(\n request: AgentCandidateExecutorStopRequest,\n context: Parameters<AgentCandidateExecutorPort['capture']>[1],\n ) {\n await this.assertCapability()\n context.signal.throwIfAborted()\n const environment = await this.resolve(request, false)\n const statuses = await environment.process.list()\n const status = statuses[0]\n if (statuses.length !== 1 || !status || status.running) {\n throw new Error('candidate environment must contain one stopped process before capture')\n }\n assertTerminalStatus(status)\n const process = await environment.process.get(status.pid)\n if (!process) throw new Error('candidate environment lost its captured process handle')\n const currentStatus = await process.status()\n assertTerminalStatus(currentStatus, status.termination)\n const state = this.states.get(executionKey(request.executionId, request.executionPlanDigest))\n const output =\n state?.output ??\n (await awaitOutput(\n collectOutput(process, outputSpec(environment).maxBytes),\n context.signal,\n Date.now() + this.provisionTimeoutMs,\n ))\n context.signal.throwIfAborted()\n const evidence = canonicalCandidateBytes({\n kind: 'agent-candidate-exact-process-capture',\n provider: environment.provider,\n environmentId: environment.id,\n executionId: request.executionId,\n executionPlanDigest: request.executionPlanDigest,\n createInputDigest: environment.metadata?.createInputDigest,\n process: {\n pid: status.pid,\n exitCode: status.exitCode,\n ...(status.exitSignal ? { exitSignal: status.exitSignal } : {}),\n termination: status.termination,\n },\n ...(state?.runtimeTermination ? { runtimeTermination: state.runtimeTermination } : {}),\n output: { sha256: sha256Bytes(output), byteLength: output.byteLength },\n })\n return {\n taskOutcome: { kind: 'output' as const, bytes: output },\n evidence,\n }\n }\n\n async dispose(\n request: AgentCandidateExecutorStopRequest,\n context: { signal: AbortSignal },\n ): Promise<{ readonly disposed: true }> {\n await this.assertCapability()\n context.signal.throwIfAborted()\n const environment = await this.resolve(request, true)\n if (!environment) return { disposed: true }\n let destroyError: unknown\n try {\n await environment.destroy()\n } catch (error) {\n destroyError = error\n }\n const remaining = await this.exactProcess.get(environment.id)\n if (remaining) {\n throw new Error('exact process environment disposal is not proven', { cause: destroyError })\n }\n context.signal.throwIfAborted()\n this.states.delete(executionKey(request.executionId, request.executionPlanDigest))\n return { disposed: true }\n }\n\n private async assertCapability(mode?: 'blocked' | 'strict'): Promise<void> {\n const pending =\n this.capabilitiesPromise ?? Promise.resolve(this.options.provider.capabilities())\n this.capabilitiesPromise = pending\n let capabilities: AgentEnvironmentCapabilities\n try {\n capabilities = await pending\n } catch (error) {\n if (this.capabilitiesPromise === pending) this.capabilitiesPromise = undefined\n throw error\n }\n const exact = capabilities.exactProcess\n if (!exact) {\n throw new Error(\n `agent environment provider \"${this.options.provider.name}\" does not declare exact process support`,\n )\n }\n if (mode && !exact.egress.includes(mode)) {\n throw new Error(\n `agent environment provider \"${this.options.provider.name}\" does not declare ${mode} exact egress`,\n )\n }\n }\n\n private async resolve(\n request: AgentCandidateExecutorStopRequest,\n missingIsDeleted: false,\n ): Promise<AgentExactProcessEnvironment>\n private async resolve(\n request: AgentCandidateExecutorStopRequest,\n missingIsDeleted: true,\n ): Promise<AgentExactProcessEnvironment | undefined>\n private async resolve(\n request: AgentCandidateExecutorStopRequest,\n missingIsDeleted: boolean,\n ): Promise<AgentExactProcessEnvironment | undefined> {\n const key = executionKey(request.executionId, request.executionPlanDigest)\n const active = this.states.get(key)?.environment\n if (active) return active\n const metadata = {\n kind: 'agent-candidate-execution',\n provider: this.options.provider.name,\n executionId: request.executionId,\n executionPlanDigest: request.executionPlanDigest,\n }\n const listed = await this.exactProcess.list({\n metadata,\n ...(this.providerOptions ? { providerOptions: this.providerOptions } : {}),\n })\n const matches = listed.filter(\n (environment) =>\n environment.provider === this.options.provider.name &&\n Object.entries(metadata).every(([name, value]) =>\n isDeepStrictEqual(environment.metadata?.[name], value),\n ),\n )\n if (matches.length > 1) {\n throw new Error('multiple exact process environments match one candidate execution')\n }\n const environment = matches[0]\n if (!environment) {\n if (missingIsDeleted) return undefined\n throw new Error('candidate exact process evidence is unavailable')\n }\n if (!isSha256Digest(environment.metadata?.createInputDigest)) {\n throw new Error('candidate exact process create-input digest is unavailable')\n }\n this.states.set(key, { environment })\n return environment\n }\n}\n\nasync function appendExactProcessTrace(\n state: ExactProcessRunState,\n traceStore: TraceStore,\n status?: AgentExactProcessStatus,\n): Promise<void> {\n const trace = state.trace\n if (!trace || trace.written) return\n const endedAt = Math.max(trace.startedAt, Math.min(Date.now(), trace.deadlineAtMs))\n const termination = state.runtimeTermination ?? state.termination ?? status?.termination\n await traceStore.appendRun({\n runId: trace.runId,\n scenarioId: trace.scenarioId,\n startedAt: trace.startedAt,\n endedAt,\n status: termination?.kind === 'exit' && termination.exitCode === 0 ? 'completed' : 'failed',\n tags: trace.tags,\n })\n trace.written = true\n}\n\nfunction assertSupportedRequest(request: AgentCandidateExecutorRequest): void {\n if (request.benchmark.task.outcome.kind !== 'output') {\n throw new Error(\n 'exact process candidate executor does not support workspace outcomes; use Pier',\n )\n }\n if (request.executionPlan.value.material.codeKind !== 'disabled' || request.inputs.candidate) {\n throw new Error('exact process candidate executor does not support code workspaces; use Pier')\n }\n if (request.memory.mode !== 'disabled') {\n throw new Error('exact process candidate executor does not support isolated memory')\n }\n const mediaType = request.benchmark.task.outcome.mediaType.toLowerCase()\n if (\n !(\n mediaType.startsWith('text/') ||\n mediaType === 'application/json' ||\n mediaType.endsWith('+json')\n )\n ) {\n throw new Error('exact process candidate executor supports only UTF-8 text and JSON outputs')\n }\n if (!posix.isAbsolute(request.launch.executable) && !request.launch.env.PATH?.trim()) {\n throw new Error('exact process candidate executable must be absolute or declare a signed PATH')\n }\n if (!request.roots) throw new Error('candidate execution roots are missing')\n assertAgentCandidateExecutionRoots(request.roots)\n}\n\nasync function materializeRequest(\n environment: AgentExactProcessEnvironment,\n request: AgentCandidateExecutorRequest,\n signal: AbortSignal,\n): Promise<void> {\n assertAgentCandidateExecutionRoots(request.roots)\n const knowledgePaths = assertKnowledgeExecutionBinding(request)\n for (const file of request.inputs.task.files) {\n await environment.writeFile(beneath(request.roots.taskRoot, file.path), file.bytes, {\n mode: file.mode,\n signal,\n })\n }\n for (const file of request.inputs.profile.files) {\n await environment.writeFile(profileFileExecutionPath(request, file), file.bytes, {\n mode: file.mode,\n signal,\n })\n }\n if (request.knowledge && knowledgePaths) {\n for (const file of request.knowledge.files) {\n await environment.writeFile(beneath(knowledgePaths.root, file.path), file.bytes, {\n mode: file.mode,\n signal,\n })\n }\n if (request.knowledge.retrievalConfig && knowledgePaths.retrievalConfig) {\n await environment.writeFile(\n knowledgePaths.retrievalConfig,\n request.knowledge.retrievalConfig,\n { mode: 0o644, signal },\n )\n }\n }\n if (request.instruction.delivery.kind === 'utf8-file') {\n await environment.writeFile(request.instruction.delivery.path, request.instruction.bytes, {\n mode: 0o644,\n signal,\n })\n }\n}\n\nfunction assertKnowledgeExecutionBinding(\n request: AgentCandidateExecutorRequest,\n): ReturnType<typeof candidateKnowledgeExecutionPaths> | undefined {\n const knowledge = request.knowledge\n if (!knowledge) {\n if (\n request.launch.env[CANDIDATE_KNOWLEDGE_ROOT_ENV] !== undefined ||\n request.launch.env[CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV] !== undefined\n ) {\n throw new Error('candidate launch declares knowledge paths without verified knowledge')\n }\n return undefined\n }\n const paths = candidateKnowledgeExecutionPaths(\n request.roots.taskRoot,\n knowledge.retrievalConfig !== undefined,\n )\n if (\n request.launch.env[CANDIDATE_KNOWLEDGE_ROOT_ENV] !== paths.root ||\n request.launch.env[CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV] !== paths.retrievalConfig\n ) {\n throw new Error('candidate knowledge paths do not match the signed launch environment')\n }\n const reserved = [paths.root, paths.retrievalConfig].filter(\n (value): value is string => value !== undefined,\n )\n const otherFiles = [\n ...request.inputs.task.files.map((file) => beneath(request.roots.taskRoot, file.path)),\n ...request.inputs.profile.files.map((file) => profileFileExecutionPath(request, file)),\n ...(request.instruction.delivery.kind === 'utf8-file'\n ? [request.instruction.delivery.path]\n : []),\n ]\n if (\n otherFiles.some((path) =>\n reserved.some(\n (reservedPath) =>\n path === reservedPath ||\n path.startsWith(`${reservedPath}/`) ||\n reservedPath.startsWith(`${path}/`),\n ),\n )\n ) {\n throw new Error('candidate knowledge paths overlap other execution inputs')\n }\n return paths\n}\n\nfunction profileFileExecutionPath(\n request: AgentCandidateExecutorRequest,\n file: AgentCandidateExecutorRequest['inputs']['profile']['files'][number],\n): string {\n const workspace = request.executionPlan.value.material.profile.targetWorkspace\n const workspaceRoot = workspace === 'task' ? request.roots.taskRoot : request.roots.candidateRoot\n if (!workspaceRoot) throw new Error('candidate profile targets a missing workspace')\n if (file.root !== 'agent') return beneath(workspaceRoot, file.path)\n const agentDir = profileAgentDirectory(request)\n return beneath(agentDir, file.path)\n}\n\nfunction profileAgentDirectory(request: AgentCandidateExecutorRequest): string {\n const paths = candidateProfileAgentPaths(\n request.profilePlan.value.material,\n request.roots.profileRoot,\n )\n if (!paths) throw new Error('candidate profile agent-root file is missing its private root')\n if (\n request.launch.env[PI_CANDIDATE_AGENT_DIR_ENV] !== paths.agentDir ||\n request.launch.env[PI_CANDIDATE_SESSION_DIR_ENV] !== paths.sessionDir\n ) {\n throw new Error('candidate Pi agent-root files do not match the signed launch environment')\n }\n return paths.agentDir\n}\n\nfunction exactLaunch(request: AgentCandidateExecutorRequest): AgentExactProcessLaunch {\n const instruction = new TextDecoder('utf-8', { fatal: true }).decode(request.instruction.bytes)\n const base = {\n executable: request.launch.executable,\n args: request.launch.args,\n cwd: request.launch.cwd,\n env: request.launch.env,\n timeoutMs: 0,\n }\n switch (request.instruction.delivery.kind) {\n case 'argv-append':\n return { ...base, args: [...base.args, instruction] }\n case 'stdin-utf8':\n return { ...base, stdin: instruction }\n case 'utf8-file':\n return base\n }\n}\n\nasync function collectOutput(process: AgentExactProcess, maxBytes: number): Promise<Uint8Array> {\n const chunks: Buffer[] = []\n let byteLength = 0\n for await (const chunk of process.stdout()) {\n const bytes = Buffer.from(chunk, 'utf8')\n byteLength += bytes.byteLength\n if (byteLength > maxBytes) {\n let stopError: unknown\n try {\n await stopProcess(process)\n } catch (error) {\n stopError = error\n }\n throw new Error(`candidate output exceeds its ${maxBytes}-byte maximum`, {\n cause: stopError,\n })\n }\n chunks.push(bytes)\n }\n return Uint8Array.from(Buffer.concat(chunks, byteLength))\n}\n\nasync function awaitOutput(\n output: Promise<Uint8Array>,\n signal: AbortSignal,\n deadlineAtMs: number,\n): Promise<Uint8Array> {\n signal.throwIfAborted()\n const remainingMs = deadlineAtMs - Date.now()\n if (remainingMs <= 0) throw new Error('candidate output deadline expired')\n let timer: ReturnType<typeof setTimeout> | undefined\n let onAbort: (() => void) | undefined\n try {\n return await Promise.race([\n output,\n new Promise<never>((_resolve, reject) => {\n onAbort = () => reject(signal.reason ?? new Error('candidate output cancelled'))\n signal.addEventListener('abort', onAbort, { once: true })\n timer = setTimeout(\n () => reject(new Error('candidate output deadline expired')),\n remainingMs,\n )\n }),\n ])\n } finally {\n if (onAbort) signal.removeEventListener('abort', onAbort)\n if (timer) clearTimeout(timer)\n }\n}\n\nasync function stopProcess(process: AgentExactProcess): Promise<void> {\n const before = await process.status()\n if (!before.running) return\n try {\n await process.kill()\n } catch (error) {\n if ((await process.status()).running) throw error\n }\n const termination = await process.wait()\n assertTerminalStatus(await process.status(), termination)\n}\n\nfunction assertTerminalStatus(\n status: AgentExactProcessStatus,\n expected?: AgentCandidateTermination,\n): asserts status is AgentExactProcessStatus & { termination: AgentCandidateTermination } {\n if (status.running || !status.termination) {\n throw new Error('exact process returned no terminal reason after exit')\n }\n if (expected && !isDeepStrictEqual(status.termination, expected)) {\n throw new Error('exact process wait and status returned different terminal reasons')\n }\n}\n\nfunction assertExecutionEnvironment(\n environment: AgentExactProcessEnvironment,\n metadata: Record<string, unknown>,\n providerName: string,\n): void {\n if (!environment.id || environment.provider !== providerName) {\n throw new Error('exact process provider returned the wrong environment identity')\n }\n if (\n !Object.entries(metadata).every(([name, value]) =>\n isDeepStrictEqual(environment.metadata?.[name], value),\n )\n ) {\n throw new Error('exact process provider did not persist candidate execution metadata')\n }\n}\n\nfunction outputSpec(environment: AgentExactProcessEnvironment): { maxBytes: number } {\n const maxBytes = environment.metadata?.outputMaxBytes\n if (!Number.isSafeInteger(maxBytes) || Number(maxBytes) < 1) {\n throw new Error('candidate exact process output bound is unavailable')\n }\n return { maxBytes: Number(maxBytes) }\n}\n\nfunction executionKey(executionId: string, executionPlanDigest: Sha256Digest): string {\n return `${executionId}\\0${executionPlanDigest}`\n}\n\nfunction executionIdempotencyKey(executionId: string, executionPlanDigest: Sha256Digest): string {\n return `candidate-${canonicalCandidateDigest({\n kind: 'agent-candidate-execution-identity',\n executionId,\n executionPlanDigest,\n }).slice('sha256:'.length)}`\n}\n\nfunction exactImage(image: string, manifestDigest: Sha256Digest): string {\n if (isSha256Digest(image)) {\n if (image !== manifestDigest) {\n throw new Error('candidate container image conflicts with its resolved manifest')\n }\n return image\n }\n const marker = image.lastIndexOf('@')\n if (marker < 0) return `${image}@${manifestDigest}`\n if (image.slice(marker + 1) !== manifestDigest) {\n throw new Error('candidate container image conflicts with its resolved manifest')\n }\n return image\n}\n\nfunction environmentLifetimeMs(timeoutMs: number, retentionMs: number): number {\n const total = positiveInteger(timeoutMs, 'candidate execution timeout') + retentionMs\n if (!Number.isSafeInteger(total)) throw new Error('candidate environment lifetime is too large')\n return Math.ceil(total / 1_000) * 1_000\n}\n\nfunction exactResources(resources: AgentExactProcessResources): AgentExactProcessResources {\n if (!Number.isFinite(resources.cpu) || resources.cpu <= 0) {\n throw new Error('exact process CPU must be positive and finite')\n }\n return Object.freeze({\n cpu: resources.cpu,\n memoryMb: positiveInteger(resources.memoryMb, 'exact process memory'),\n diskMb: positiveInteger(resources.diskMb, 'exact process disk'),\n })\n}\n\nfunction positiveInteger(value: number, label: string): number {\n if (!Number.isSafeInteger(value) || value < 1)\n throw new Error(`${label} must be a positive integer`)\n return value\n}\n\nfunction beneath(root: string, relativePath: string): string {\n if (posix.isAbsolute(relativePath)) throw new Error('candidate input path must be relative')\n const path = posix.normalize(relativePath)\n if (path === '..' || path.startsWith('../')) {\n throw new Error('candidate input path escapes its execution root')\n }\n return posix.join(root, path)\n}\n\nfunction isSha256Digest(value: unknown): value is Sha256Digest {\n return typeof value === 'string' && /^sha256:[a-f0-9]{64}$/.test(value)\n}\n","import type {\n AgentCandidateModelAccessNetwork,\n AgentCandidateResolvedModel,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue } from './digest'\nimport { assertExactObjectKeys } from './exact-object'\nimport { sealAgentCandidateModelSettlement, usdToNanos } from './model-settlement'\nimport type {\n AgentCandidateModelLimits,\n AgentCandidateModelPort,\n AgentCandidateProtectedModelActivation,\n AgentCandidateProtectedModelReservation,\n AgentCandidateProtectedModelSettlement,\n} from './types'\n\nexport type AgentCandidateModelGrantReserveInput = Parameters<\n AgentCandidateModelPort['reserveGrant']\n>[0]\nexport type AgentCandidateModelGrantActivateInput = Parameters<\n AgentCandidateModelPort['activateGrant']\n>[0]\nexport type AgentCandidateModelGrantSettleInput = Parameters<\n AgentCandidateModelPort['settleGrant']\n>[0]\n\n/** Secret-free response from the service's reservation endpoint. */\nexport type AgentCandidateModelGrantReservation = AgentCandidateProtectedModelReservation\n\n/**\n * Narrow transport contract for a service that owns scoped model credentials\n * and the authoritative per-call usage ledger.\n *\n * An HTTP client can bind these methods to control-plane endpoints. Keeping\n * transport out of the runtime prevents parent credentials, endpoint paths,\n * and retry policy from becoming part of the portable candidate contract.\n */\nexport interface AgentCandidateModelGrantClient {\n reserve(input: AgentCandidateModelGrantReserveInput): Promise<AgentCandidateModelGrantReservation>\n activate(\n input: AgentCandidateModelGrantActivateInput,\n ): Promise<AgentCandidateProtectedModelActivation>\n settle(\n input: AgentCandidateModelGrantSettleInput,\n ): Promise<AgentCandidateProtectedModelSettlement>\n}\n\nexport interface CreateProtectedAgentCandidateModelPortOptions {\n client: AgentCandidateModelGrantClient\n /** Catalog/snapshot resolution stays separate from credential issuance. */\n resolveModel: AgentCandidateModelPort['resolve']\n /** The only public DNS name candidate processes may reach for inference. */\n gatewayDomain: string\n /** Exact environment names the activation endpoint must return, no more or fewer. */\n activationEnvNames: readonly string[]\n}\n\ninterface RememberedReservation {\n requestDigest: Sha256Digest\n responseDigest: Sha256Digest\n executionId: string\n preparationId: string\n grantDigest: Sha256Digest\n expiresAtMs: number\n resolved: AgentCandidateResolvedModel\n limits: AgentCandidateModelLimits\n maxCostUsdNanos: number\n activation: 'reserved' | 'activating' | 'activated'\n settlementDigest?: Sha256Digest\n settlementReason?: AgentCandidateModelGrantSettleInput['reason']\n}\n\ninterface RememberedSettlement {\n settlementDigest: Sha256Digest\n settlementReason: AgentCandidateModelGrantSettleInput['reason']\n expiresAtMs: number\n}\n\nconst MAX_RECENT_SETTLEMENTS = 4_096\nconst RECOVERED_SETTLEMENT_RETENTION_MS = 15 * 60 * 1_000\n\n/**\n * Bind a protected model-grant service to the immutable candidate runtime.\n *\n * The service remains the authority for expiry, admission, revocation, and\n * metering. This adapter independently checks every response before allowing\n * it to cross into candidate execution or durable receipt finalization.\n */\nexport function createProtectedAgentCandidateModelPort(\n options: CreateProtectedAgentCandidateModelPortOptions,\n): AgentCandidateModelPort {\n const gatewayDomain = assertGatewayDomain(options.gatewayDomain)\n const activationEnvNames = exactEnvironmentNames(options.activationEnvNames)\n const reservations = new Map<string, RememberedReservation>()\n const expiredReservations = new Map<\n string,\n { state: RememberedReservation; retainedUntilMs: number }\n >()\n const recentSettlements = new Map<string, RememberedSettlement>()\n\n return {\n resolve: async (input) => {\n const request = immutableCandidateValue(input)\n const resolved = validateResolvedModel(await options.resolveModel(request), request)\n return immutableCandidateValue(resolved)\n },\n\n reserveGrant: async (input) => {\n pruneExpiredState(reservations, expiredReservations, recentSettlements, Date.now())\n const request = immutableCandidateValue(input)\n validateReserveInput(request)\n const requestDigest = canonicalCandidateDigest(request)\n const key = reservationKey(request.executionId, request.preparationId)\n if (recentSettlements.has(key)) {\n throw new Error('protected model reservation is already settled')\n }\n const expired = expiredReservations.get(key)\n if (expired) throw new Error('protected model reservation has expired')\n const previous = reservations.get(key)\n if (previous && previous.requestDigest !== requestDigest) {\n throw new Error('protected model reservation retry changed immutable input')\n }\n\n const reservation = validateReservation(\n await options.client.reserve(request),\n request,\n gatewayDomain,\n )\n const responseDigest = canonicalCandidateDigest(reservation)\n if (recentSettlements.has(key)) {\n throw new Error('protected model reservation completed after the grant was settled')\n }\n const recorded = previous ?? reservations.get(key)\n if (recorded && recorded.requestDigest !== requestDigest) {\n throw new Error('protected model reservation retry changed immutable input')\n }\n if (recorded && recorded.responseDigest !== responseDigest) {\n throw new Error('protected model reservation retry returned different evidence')\n }\n if (!recorded) {\n reservations.set(key, {\n requestDigest,\n responseDigest,\n executionId: request.executionId,\n preparationId: request.preparationId,\n grantDigest: reservation.digest,\n expiresAtMs: request.expiresAtMs,\n resolved: immutableCandidateValue(request.resolved),\n limits: immutableCandidateValue(request.limits),\n maxCostUsdNanos: usdToNanos(request.limits.maxCostUsd, 'reserved maxCostUsd'),\n activation: 'reserved',\n })\n }\n return reservation\n },\n\n activateGrant: async (input) => {\n pruneExpiredState(reservations, expiredReservations, recentSettlements, Date.now())\n const request = immutableCandidateValue(input)\n const key = reservationKey(request.executionId, request.preparationId)\n if (recentSettlements.has(key)) throw new Error('protected model grant is already settled')\n const state = reservations.get(key)\n if (!state && expiredReservations.has(key)) {\n throw new Error('protected model grant reservation has expired')\n }\n if (!state) throw new Error('protected model grant was not reserved by this port')\n assertGrantIdentity(state, request)\n if (state.settlementDigest) throw new Error('protected model grant is already settled')\n if (state.activation !== 'reserved') {\n throw new Error('protected model grant activation is single-use')\n }\n if (!Number.isSafeInteger(request.deadlineAtMs) || request.deadlineAtMs <= 0) {\n throw new Error('protected model activation deadline must be a positive safe integer')\n }\n if (request.deadlineAtMs <= Date.now()) {\n throw new Error('protected model activation deadline must be in the future')\n }\n if (request.deadlineAtMs > state.expiresAtMs) {\n throw new Error('protected model activation deadline exceeds the reserved expiry')\n }\n state.activation = 'activating'\n try {\n const activation = validateActivation(\n await options.client.activate(request),\n state.limits.maxModelCalls === 0 ? [] : activationEnvNames,\n )\n if (recentSettlements.has(key) || reservations.get(key) !== state) {\n throw new Error('protected model grant settled while activation was in flight')\n }\n state.activation = 'activated'\n return activation\n } catch (error) {\n state.activation = 'reserved'\n throw error\n }\n },\n\n settleGrant: async (input) => {\n const now = Date.now()\n pruneExpiredState(reservations, expiredReservations, recentSettlements, now)\n const request = immutableCandidateValue(input)\n const key = reservationKey(request.executionId, request.preparationId)\n const state = reservations.get(key) ?? expiredReservations.get(key)?.state\n if (state) assertGrantIdentity(state, request)\n const remembered = state ?? recentSettlements.get(key)\n if (remembered?.settlementReason && remembered.settlementReason !== request.reason) {\n throw new Error('protected model settlement retry changed the termination reason')\n }\n\n const sealed = sealAgentCandidateModelSettlement(await options.client.settle(request), {\n preparationId: request.preparationId,\n grantDigest: request.grantDigest,\n model: request.resolved.model,\n })\n if (state) assertWithinReservedLimits(sealed.usage, state)\n\n const settlementDigest = canonicalCandidateDigest(sealed.value)\n if (remembered?.settlementDigest && remembered.settlementDigest !== settlementDigest) {\n throw new Error('protected model settlement retry returned a different final ledger')\n }\n if (remembered?.settlementReason && remembered.settlementReason !== request.reason) {\n throw new Error('protected model settlement retry changed the termination reason')\n }\n const expiresAtMs = state?.expiresAtMs ?? now + RECOVERED_SETTLEMENT_RETENTION_MS\n if (state) {\n state.settlementDigest = settlementDigest\n state.settlementReason = request.reason\n }\n reservations.delete(key)\n expiredReservations.delete(key)\n rememberSettlement(recentSettlements, key, {\n settlementDigest,\n settlementReason: request.reason,\n expiresAtMs,\n })\n return sealed.value\n },\n }\n}\n\nfunction validateReserveInput(input: AgentCandidateModelGrantReserveInput): void {\n if (!Number.isSafeInteger(input.expiresAtMs) || input.expiresAtMs <= 0) {\n throw new Error('protected model reservation expiry must be a positive safe integer')\n }\n if (input.expiresAtMs <= Date.now()) {\n throw new Error('protected model reservation expiry must be in the future')\n }\n for (const [name, value] of [\n ['maxModelCalls', input.limits.maxModelCalls],\n ['maxInputTokens', input.limits.maxInputTokens],\n ['maxOutputTokens', input.limits.maxOutputTokens],\n ['maxTotalTokens', input.limits.maxTotalTokens],\n ] as const) {\n if (value === undefined) continue\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`protected model reservation ${name} must be a nonnegative safe integer`)\n }\n }\n usdToNanos(input.limits.maxCostUsd, 'reserved maxCostUsd')\n}\n\nfunction validateReservation(\n value: unknown,\n expected: AgentCandidateModelGrantReserveInput,\n gatewayDomain: string,\n): AgentCandidateModelGrantReservation {\n const source = exactRecord(\n value,\n ['preparationId', 'digest', 'expiresAtMs', 'enforcedLimits', 'network'],\n 'protected model reservation response',\n )\n if (source.preparationId !== expected.preparationId) {\n throw new Error('protected model reservation response changed preparation identity')\n }\n if (!isSha256Digest(source.digest)) {\n throw new Error('protected model reservation response has an invalid digest')\n }\n if (source.expiresAtMs !== expected.expiresAtMs) {\n throw new Error('protected model reservation response changed expiry')\n }\n exactRecord(\n source.enforcedLimits,\n modelLimitKeys(expected.limits),\n 'protected model reservation enforced limits',\n )\n if (\n canonicalCandidateDigest(source.enforcedLimits) !== canonicalCandidateDigest(expected.limits)\n ) {\n throw new Error('protected model reservation response changed enforced limits')\n }\n\n const network = validateReservationNetwork(\n source.network,\n expected.limits.maxModelCalls,\n gatewayDomain,\n )\n return immutableCandidateValue({\n preparationId: source.preparationId,\n digest: source.digest,\n expiresAtMs: source.expiresAtMs,\n enforcedLimits: source.enforcedLimits,\n network,\n }) as AgentCandidateModelGrantReservation\n}\n\nfunction validateReservationNetwork(\n value: unknown,\n maxModelCalls: number,\n gatewayDomain: string,\n): AgentCandidateModelAccessNetwork {\n if (maxModelCalls === 0) {\n const source = exactRecord(value, ['mode'], 'protected model reservation network')\n if (source.mode !== 'disabled') {\n throw new Error('zero-call protected model reservation must disable gateway access')\n }\n return { mode: 'disabled' }\n }\n\n const source = exactRecord(value, ['mode', 'domains'], 'protected model reservation network')\n if (source.mode !== 'gateway-only') {\n throw new Error('protected model reservation must allow only its model gateway')\n }\n if (\n !Array.isArray(source.domains) ||\n source.domains.length !== 1 ||\n source.domains[0] !== gatewayDomain\n ) {\n throw new Error('protected model reservation returned an unexpected gateway domain')\n }\n return { mode: 'gateway-only', domains: [gatewayDomain] }\n}\n\nfunction validateActivation(\n value: unknown,\n expectedNames: readonly string[],\n): AgentCandidateProtectedModelActivation {\n const source = exactRecord(value, ['env'], 'protected model activation response')\n const env = record(source.env, 'protected model activation environment')\n const actualNames = Object.keys(env).sort()\n if (\n actualNames.length !== expectedNames.length ||\n actualNames.some((name, index) => name !== expectedNames[index])\n ) {\n throw new Error('protected model activation returned unexpected environment names')\n }\n const detached: Record<string, string> = Object.create(null) as Record<string, string>\n for (const name of expectedNames) {\n const value = env[name]\n if (typeof value !== 'string' || value.length < 8 || value.length > 65_536) {\n throw new Error(`protected model activation ${name} must be a non-empty protected value`)\n }\n detached[name] = value\n }\n return Object.freeze({ env: Object.freeze(detached) })\n}\n\nfunction validateResolvedModel(\n value: unknown,\n expected: Parameters<AgentCandidateModelPort['resolve']>[0],\n): AgentCandidateResolvedModel {\n const source = exactRecord(\n value,\n ['requested', 'provider', 'model', 'snapshot', 'reasoningEffort'],\n 'resolved candidate model',\n )\n if (source.requested !== expected.requested) {\n throw new Error('model resolver changed the evaluator-owned request')\n }\n if (source.reasoningEffort !== expected.reasoningEffort) {\n throw new Error('model resolver changed the evaluator-owned reasoning effort')\n }\n for (const name of ['requested', 'provider', 'model', 'snapshot'] as const) {\n if (typeof source[name] !== 'string' || source[name].length === 0) {\n throw new Error(`resolved candidate model ${name} must be non-empty`)\n }\n }\n return source as unknown as AgentCandidateResolvedModel\n}\n\nfunction assertGrantIdentity(\n expected: RememberedReservation,\n actual: AgentCandidateModelGrantActivateInput | AgentCandidateModelGrantSettleInput,\n): void {\n if (\n actual.executionId !== expected.executionId ||\n actual.preparationId !== expected.preparationId ||\n actual.grantDigest !== expected.grantDigest ||\n canonicalCandidateDigest(actual.resolved) !== canonicalCandidateDigest(expected.resolved)\n ) {\n throw new Error('protected model grant input does not match its immutable reservation')\n }\n}\n\nfunction assertWithinReservedLimits(\n usage: {\n modelCalls: number\n inputTokens: number\n outputTokens: number\n costUsdNanos: number\n },\n reservation: RememberedReservation,\n): void {\n for (const [name, actual, limit] of [\n ['model calls', usage.modelCalls, reservation.limits.maxModelCalls],\n ['input tokens', usage.inputTokens, reservation.limits.maxInputTokens],\n ['output tokens', usage.outputTokens, reservation.limits.maxOutputTokens],\n ['cost USD nanos', usage.costUsdNanos, reservation.maxCostUsdNanos],\n ] as const) {\n if (actual > limit) {\n throw new Error(`protected model settlement ${name} ${actual} exceeds reserved ${limit}`)\n }\n }\n const maxTotalTokens = reservation.limits.maxTotalTokens\n if (maxTotalTokens !== undefined) {\n const totalTokens = usage.inputTokens + usage.outputTokens\n if (!Number.isSafeInteger(totalTokens)) {\n throw new Error('protected model settlement total token usage is incomplete')\n }\n if (totalTokens > maxTotalTokens) {\n throw new Error(\n `protected model settlement total tokens ${totalTokens} exceeds reserved ${maxTotalTokens}`,\n )\n }\n }\n}\n\nfunction modelLimitKeys(limits: AgentCandidateModelLimits): readonly string[] {\n return limits.maxTotalTokens === undefined\n ? ['maxModelCalls', 'maxInputTokens', 'maxOutputTokens', 'maxCostUsd']\n : ['maxModelCalls', 'maxInputTokens', 'maxOutputTokens', 'maxTotalTokens', 'maxCostUsd']\n}\n\nfunction exactEnvironmentNames(values: readonly string[]): readonly string[] {\n if (values.length === 0) {\n throw new Error('protected model activation environment names must not be empty')\n }\n const names = [...values].sort()\n if (new Set(names).size !== names.length) {\n throw new Error('protected model activation environment names must be unique')\n }\n for (const name of names) {\n if (\n !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) ||\n ['__proto__', 'constructor', 'prototype'].includes(name)\n ) {\n throw new Error(`protected model activation environment name is invalid: ${name}`)\n }\n }\n return Object.freeze(names)\n}\n\nfunction assertGatewayDomain(value: string): string {\n if (\n value.length > 253 ||\n value !== value.toLowerCase() ||\n value.endsWith('.') ||\n value.includes(':') ||\n value === 'localhost' ||\n value.endsWith('.localhost') ||\n value === 'metadata.google' ||\n value === 'metadata.google.internal'\n ) {\n throw new Error('protected model gateway must be an exact lowercase public DNS name')\n }\n const labels = value.split('.')\n if (\n labels.length < 2 ||\n !labels.every(\n (label) =>\n label.length >= 1 && label.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label),\n ) ||\n !/[a-z]/.test(labels.at(-1) ?? '')\n ) {\n throw new Error('protected model gateway must be an exact lowercase public DNS name')\n }\n return value\n}\n\nfunction reservationKey(executionId: string, preparationId: string): string {\n return canonicalCandidateDigest({ executionId, preparationId })\n}\n\nfunction pruneExpiredState(\n reservations: Map<string, RememberedReservation>,\n expiredReservations: Map<string, { state: RememberedReservation; retainedUntilMs: number }>,\n settlements: Map<string, RememberedSettlement>,\n now: number,\n): void {\n for (const [key, value] of reservations) {\n if (value.expiresAtMs <= now) {\n reservations.delete(key)\n expiredReservations.set(key, {\n state: value,\n retainedUntilMs: now + RECOVERED_SETTLEMENT_RETENTION_MS,\n })\n }\n }\n for (const [key, value] of expiredReservations) {\n if (value.retainedUntilMs <= now) expiredReservations.delete(key)\n }\n for (const [key, value] of settlements) {\n if (value.expiresAtMs <= now) settlements.delete(key)\n }\n}\n\nfunction rememberSettlement(\n settlements: Map<string, RememberedSettlement>,\n key: string,\n value: RememberedSettlement,\n): void {\n settlements.delete(key)\n settlements.set(key, value)\n while (settlements.size > MAX_RECENT_SETTLEMENTS) {\n const oldest = settlements.keys().next().value\n if (oldest === undefined) return\n settlements.delete(oldest)\n }\n}\n\nfunction isSha256Digest(value: unknown): value is Sha256Digest {\n return typeof value === 'string' && /^sha256:[a-f0-9]{64}$/.test(value)\n}\n\nfunction exactRecord(\n value: unknown,\n keys: readonly string[],\n label: string,\n): Record<string, unknown> {\n const source = record(value, label)\n assertExactObjectKeys(source, keys, label)\n return source\n}\n\nfunction record(value: unknown, label: string): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`)\n }\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(`${label} must be a plain object`)\n }\n return value as Record<string, unknown>\n}\n"],"mappings":";;;;;;AAqCA,MAAM,+BAA+B;AACrC,MAAM,gCAAgC,KAAK;;AA2B3C,SAAgB,wCACd,SAC4B;CAC5B,OAAO,IAAI,mCAAmC,OAAO;AACvD;AAEA,IAAM,qCAAN,MAA+E;CAShD;CAR7B,yBAA0B,IAAI,IAAkC;CAChE;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,SAAgE;EAA/C,KAAA,UAAA;EAC3B,IAAI,CAAC,QAAQ,SAAS,cACpB,MAAM,IAAI,MACR,+BAA+B,QAAQ,SAAS,KAAK,qCACvD;EAEF,KAAK,eAAe,QAAQ,SAAS;EACrC,KAAK,YAAY,eAAe,QAAQ,SAAS;EACjD,KAAK,qBAAqB,gBACxB,QAAQ,sBAAsB,8BAC9B,iCACF;EACA,KAAK,sBAAsB,gBACzB,QAAQ,uBAAuB,+BAC/B,kCACF;EACA,KAAK,kBAAkB,QAAQ,kBAC3B,wBAAwB,QAAQ,eAAe,IAC/C,KAAA;CACN;CAEA,MAAM,QACJ,SACA,SACA;EACA,uBAAuB,OAAO;EAC9B,MAAM,UAAU,QAAQ,UAAU,KAAK;EACvC,IAAI,QAAQ,SAAS,UAAU,MAAM,IAAI,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U,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GACpE,MAAM,IAAI,MAAM,GAAG,MAAM,mBAAmB;CAE9C,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,IAAI,cAAc,OAAO,aAAa,cAAc,MAClD,MAAM,IAAI,MAAM,GAAG,MAAM,wBAAwB;CAEnD,OAAO;AACT"}
1
+ {"version":3,"file":"protected-model-port-f1N2f0Uq.js","names":["isSha256Digest"],"sources":["../src/candidate-execution/exact-process-executor.ts","../src/candidate-execution/protected-model-port.ts"],"sourcesContent":["import { posix } from 'node:path'\nimport { isDeepStrictEqual } from 'node:util'\n\nimport type { TraceStore } from '@tangle-network/agent-eval'\nimport type { AgentCandidateTermination, Sha256Digest } from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironmentCapabilities,\n AgentEnvironmentProvider,\n AgentExactProcess,\n AgentExactProcessEnvironment,\n AgentExactProcessLaunch,\n AgentExactProcessResources,\n AgentExactProcessStatus,\n} from '@tangle-network/agent-interface/environment-provider'\nimport {\n canonicalCandidateBytes,\n canonicalCandidateDigest,\n immutableCandidateValue,\n sha256Bytes,\n} from './digest'\nimport { assertAgentCandidateExecutionRoots } from './execution-roots'\nimport {\n CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV,\n CANDIDATE_KNOWLEDGE_ROOT_ENV,\n candidateKnowledgeExecutionPaths,\n} from './knowledge'\nimport {\n candidateProfileAgentPaths,\n PI_CANDIDATE_AGENT_DIR_ENV,\n PI_CANDIDATE_SESSION_DIR_ENV,\n} from './profile'\nimport type {\n AgentCandidateExecutorPort,\n AgentCandidateExecutorRequest,\n AgentCandidateExecutorStopRequest,\n} from './types'\n\nconst DEFAULT_PROVISION_TIMEOUT_MS = 120_000\nconst DEFAULT_RECOVERY_RETENTION_MS = 15 * 60_000\n\ninterface ExactProcessRunState {\n environment: AgentExactProcessEnvironment\n output?: Uint8Array\n termination?: AgentCandidateTermination\n runtimeTermination?: AgentCandidateTermination\n trace?: {\n runId: string\n scenarioId: string\n startedAt: number\n deadlineAtMs: number\n timeoutMs: number\n tags: Record<string, string>\n written: boolean\n }\n}\n\nexport interface ExactProcessCandidateExecutorOptions {\n provider: AgentEnvironmentProvider\n resources: AgentExactProcessResources\n provisionTimeoutMs?: number\n recoveryRetentionMs?: number\n providerOptions?: Record<string, unknown>\n}\n\n/** Adapt one neutral exact-process provider to Runtime's trusted candidate boundary. */\nexport function exactProcessProviderAsCandidateExecutor(\n options: ExactProcessCandidateExecutorOptions,\n): AgentCandidateExecutorPort {\n return new ExactProcessAgentCandidateExecutor(options)\n}\n\nclass ExactProcessAgentCandidateExecutor implements AgentCandidateExecutorPort {\n private readonly states = new Map<string, ExactProcessRunState>()\n private readonly exactProcess\n private readonly resources: AgentExactProcessResources\n private readonly provisionTimeoutMs: number\n private readonly recoveryRetentionMs: number\n private readonly providerOptions?: Record<string, unknown>\n private capabilitiesPromise?: Promise<AgentEnvironmentCapabilities>\n\n constructor(private readonly options: ExactProcessCandidateExecutorOptions) {\n if (!options.provider.exactProcess) {\n throw new Error(\n `agent environment provider \"${options.provider.name}\" does not implement exact processes`,\n )\n }\n this.exactProcess = options.provider.exactProcess\n this.resources = exactResources(options.resources)\n this.provisionTimeoutMs = positiveInteger(\n options.provisionTimeoutMs ?? DEFAULT_PROVISION_TIMEOUT_MS,\n 'exact process provision timeout',\n )\n this.recoveryRetentionMs = positiveInteger(\n options.recoveryRetentionMs ?? DEFAULT_RECOVERY_RETENTION_MS,\n 'exact process recovery retention',\n )\n this.providerOptions = options.providerOptions\n ? immutableCandidateValue(options.providerOptions)\n : undefined\n }\n\n async execute(\n request: AgentCandidateExecutorRequest,\n context: Parameters<AgentCandidateExecutorPort['execute']>[1],\n ) {\n assertSupportedRequest(request)\n const outcome = request.benchmark.task.outcome\n if (outcome.kind !== 'output') throw new Error('exact process executor requires an output task')\n const network = request.executionPlan.value.material.model.access.network\n const egress =\n network.mode === 'disabled'\n ? ({ mode: 'blocked' } as const)\n : ({ mode: 'strict', allowDomains: [...network.domains] } as const)\n await this.assertCapability(egress.mode)\n context.signal.throwIfAborted()\n\n const key = executionKey(request.executionId, request.executionPlan.value.digest)\n if (this.states.has(key)) throw new Error('candidate execution environment is already active')\n const image = exactImage(\n request.executionPlan.value.material.container.image,\n request.executionPlan.value.material.container.manifestDigest,\n )\n const maxLifetimeMs = environmentLifetimeMs(\n request.hardLimits.timeoutMs,\n this.recoveryRetentionMs,\n )\n const createMaterial = immutableCandidateValue({\n kind: 'agent-candidate-exact-process-create',\n provider: this.options.provider.name,\n executionId: request.executionId,\n executionPlanDigest: request.executionPlan.value.digest,\n image,\n egress,\n maxLifetimeMs,\n provisionTimeoutMs: this.provisionTimeoutMs,\n resources: this.resources,\n output: { mediaType: outcome.mediaType, maxBytes: outcome.maxBytes },\n ...(this.providerOptions ? { providerOptions: this.providerOptions } : {}),\n })\n const createInputDigest = canonicalCandidateDigest(createMaterial)\n const metadata = immutableCandidateValue({\n kind: 'agent-candidate-execution',\n provider: this.options.provider.name,\n executionId: request.executionId,\n executionPlanDigest: request.executionPlan.value.digest,\n createInputDigest,\n outputMediaType: outcome.mediaType,\n outputMaxBytes: outcome.maxBytes,\n })\n const environment = await this.exactProcess.create({\n image,\n egress,\n maxLifetimeMs,\n provisionTimeoutMs: this.provisionTimeoutMs,\n resources: this.resources,\n metadata,\n idempotencyKey: executionIdempotencyKey(\n request.executionId,\n request.executionPlan.value.digest,\n ),\n signal: context.signal,\n ...(this.providerOptions ? { providerOptions: this.providerOptions } : {}),\n })\n try {\n assertExecutionEnvironment(environment, metadata, this.options.provider.name)\n } catch (error) {\n try {\n await environment.destroy()\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n 'exact process validation and cleanup both failed',\n )\n }\n throw error\n }\n const state: ExactProcessRunState = { environment }\n this.states.set(key, state)\n\n const existing = await environment.process.list()\n if (existing.length !== 0) {\n throw new Error('fresh candidate environment already contains a process')\n }\n await materializeRequest(environment, request, context.signal)\n const launch = exactLaunch(request)\n const startedAt = Date.now()\n state.trace = {\n runId: request.trace.runId,\n scenarioId: request.benchmark.task.scenario.id,\n startedAt,\n deadlineAtMs: context.deadlineAtMs,\n timeoutMs: request.hardLimits.timeoutMs,\n tags: {\n ...request.trace.tags,\n environmentId: environment.id,\n environmentProvider: environment.provider,\n },\n written: false,\n }\n const process = await environment.process.spawn(launch, { signal: context.signal })\n const outputPromise = collectOutput(process, outcome.maxBytes)\n void outputPromise.catch(() => undefined)\n let cancellation: Promise<void> | undefined\n let processExited = false\n const cancel = () => {\n if (!processExited) cancellation ??= stopProcess(process)\n }\n context.signal.addEventListener('abort', cancel, { once: true })\n if (context.signal.aborted) cancel()\n try {\n const termination = await process.wait()\n processExited = true\n context.signal.removeEventListener('abort', cancel)\n if (cancellation) await cancellation\n const status = await process.status()\n assertTerminalStatus(status, termination)\n state.output = await awaitOutput(outputPromise, context.signal, context.deadlineAtMs)\n state.termination = termination\n await appendExactProcessTrace(state, context.traceStore, status)\n return { executionId: request.executionId, termination }\n } finally {\n context.signal.removeEventListener('abort', cancel)\n }\n }\n\n async stop(\n request: AgentCandidateExecutorStopRequest,\n context: Parameters<AgentCandidateExecutorPort['stop']>[1],\n ): Promise<{ readonly stopped: true }> {\n await this.assertCapability()\n context.signal.throwIfAborted()\n const environment = await this.resolve(request, true)\n if (!environment) return { stopped: true }\n let statuses = await environment.process.list()\n if (statuses.length > 1) {\n throw new Error('candidate exact process environment contains more than one process')\n }\n const status = statuses[0]\n if (status?.running) {\n const process = await environment.process.get(status.pid)\n if (!process) throw new Error('candidate environment lost its running process handle')\n await stopProcess(process)\n }\n context.signal.throwIfAborted()\n statuses = await environment.process.list()\n if (statuses.some((entry) => entry.running)) {\n throw new Error('candidate exact process termination is not proven')\n }\n const finalStatus = statuses[0]\n if (finalStatus) assertTerminalStatus(finalStatus)\n const state = this.states.get(executionKey(request.executionId, request.executionPlanDigest))\n if (state) {\n state.termination = finalStatus?.termination ?? state.termination\n if (context.reason === 'timeout' && state.trace) {\n state.runtimeTermination = {\n kind: 'timeout',\n timeoutMs: state.trace.timeoutMs,\n }\n }\n await appendExactProcessTrace(state, context.traceStore, finalStatus)\n }\n return { stopped: true }\n }\n\n async capture(\n request: AgentCandidateExecutorStopRequest,\n context: Parameters<AgentCandidateExecutorPort['capture']>[1],\n ) {\n await this.assertCapability()\n context.signal.throwIfAborted()\n const environment = await this.resolve(request, false)\n const statuses = await environment.process.list()\n const status = statuses[0]\n if (statuses.length !== 1 || !status || status.running) {\n throw new Error('candidate environment must contain one stopped process before capture')\n }\n assertTerminalStatus(status)\n const process = await environment.process.get(status.pid)\n if (!process) throw new Error('candidate environment lost its captured process handle')\n const currentStatus = await process.status()\n assertTerminalStatus(currentStatus, status.termination)\n const state = this.states.get(executionKey(request.executionId, request.executionPlanDigest))\n const output =\n state?.output ??\n (await awaitOutput(\n collectOutput(process, outputSpec(environment).maxBytes),\n context.signal,\n Date.now() + this.provisionTimeoutMs,\n ))\n context.signal.throwIfAborted()\n const evidence = canonicalCandidateBytes({\n kind: 'agent-candidate-exact-process-capture',\n provider: environment.provider,\n environmentId: environment.id,\n executionId: request.executionId,\n executionPlanDigest: request.executionPlanDigest,\n createInputDigest: environment.metadata?.createInputDigest,\n process: {\n pid: status.pid,\n exitCode: status.exitCode,\n ...(status.exitSignal ? { exitSignal: status.exitSignal } : {}),\n termination: status.termination,\n },\n ...(state?.runtimeTermination ? { runtimeTermination: state.runtimeTermination } : {}),\n output: { sha256: sha256Bytes(output), byteLength: output.byteLength },\n })\n return {\n taskOutcome: { kind: 'output' as const, bytes: output },\n evidence,\n }\n }\n\n async dispose(\n request: AgentCandidateExecutorStopRequest,\n context: { signal: AbortSignal },\n ): Promise<{ readonly disposed: true }> {\n await this.assertCapability()\n context.signal.throwIfAborted()\n const environment = await this.resolve(request, true)\n if (!environment) return { disposed: true }\n let destroyError: unknown\n try {\n await environment.destroy()\n } catch (error) {\n destroyError = error\n }\n const remaining = await this.exactProcess.get(environment.id)\n if (remaining) {\n throw new Error('exact process environment disposal is not proven', { cause: destroyError })\n }\n context.signal.throwIfAborted()\n this.states.delete(executionKey(request.executionId, request.executionPlanDigest))\n return { disposed: true }\n }\n\n private async assertCapability(mode?: 'blocked' | 'strict'): Promise<void> {\n const pending =\n this.capabilitiesPromise ?? Promise.resolve(this.options.provider.capabilities())\n this.capabilitiesPromise = pending\n let capabilities: AgentEnvironmentCapabilities\n try {\n capabilities = await pending\n } catch (error) {\n if (this.capabilitiesPromise === pending) this.capabilitiesPromise = undefined\n throw error\n }\n const exact = capabilities.exactProcess\n if (!exact) {\n throw new Error(\n `agent environment provider \"${this.options.provider.name}\" does not declare exact process support`,\n )\n }\n if (mode && !exact.egress.includes(mode)) {\n throw new Error(\n `agent environment provider \"${this.options.provider.name}\" does not declare ${mode} exact egress`,\n )\n }\n }\n\n private async resolve(\n request: AgentCandidateExecutorStopRequest,\n missingIsDeleted: false,\n ): Promise<AgentExactProcessEnvironment>\n private async resolve(\n request: AgentCandidateExecutorStopRequest,\n missingIsDeleted: true,\n ): Promise<AgentExactProcessEnvironment | undefined>\n private async resolve(\n request: AgentCandidateExecutorStopRequest,\n missingIsDeleted: boolean,\n ): Promise<AgentExactProcessEnvironment | undefined> {\n const key = executionKey(request.executionId, request.executionPlanDigest)\n const active = this.states.get(key)?.environment\n if (active) return active\n const metadata = {\n kind: 'agent-candidate-execution',\n provider: this.options.provider.name,\n executionId: request.executionId,\n executionPlanDigest: request.executionPlanDigest,\n }\n const listed = await this.exactProcess.list({\n metadata,\n ...(this.providerOptions ? { providerOptions: this.providerOptions } : {}),\n })\n const matches = listed.filter(\n (environment) =>\n environment.provider === this.options.provider.name &&\n Object.entries(metadata).every(([name, value]) =>\n isDeepStrictEqual(environment.metadata?.[name], value),\n ),\n )\n if (matches.length > 1) {\n throw new Error('multiple exact process environments match one candidate execution')\n }\n const environment = matches[0]\n if (!environment) {\n if (missingIsDeleted) return undefined\n throw new Error('candidate exact process evidence is unavailable')\n }\n if (!isSha256Digest(environment.metadata?.createInputDigest)) {\n throw new Error('candidate exact process create-input digest is unavailable')\n }\n this.states.set(key, { environment })\n return environment\n }\n}\n\nasync function appendExactProcessTrace(\n state: ExactProcessRunState,\n traceStore: TraceStore,\n status?: AgentExactProcessStatus,\n): Promise<void> {\n const trace = state.trace\n if (!trace || trace.written) return\n const endedAt = Math.max(trace.startedAt, Math.min(Date.now(), trace.deadlineAtMs))\n const termination = state.runtimeTermination ?? state.termination ?? status?.termination\n await traceStore.appendRun({\n runId: trace.runId,\n scenarioId: trace.scenarioId,\n startedAt: trace.startedAt,\n endedAt,\n status: termination?.kind === 'exit' && termination.exitCode === 0 ? 'completed' : 'failed',\n tags: trace.tags,\n })\n trace.written = true\n}\n\nfunction assertSupportedRequest(request: AgentCandidateExecutorRequest): void {\n if (request.benchmark.task.outcome.kind !== 'output') {\n throw new Error(\n 'exact process candidate executor does not support workspace outcomes; use Pier',\n )\n }\n if (request.executionPlan.value.material.codeKind !== 'disabled' || request.inputs.candidate) {\n throw new Error('exact process candidate executor does not support code workspaces; use Pier')\n }\n if (request.memory.mode !== 'disabled') {\n throw new Error('exact process candidate executor does not support isolated memory')\n }\n const mediaType = request.benchmark.task.outcome.mediaType.toLowerCase()\n if (\n !(\n mediaType.startsWith('text/') ||\n mediaType === 'application/json' ||\n mediaType.endsWith('+json')\n )\n ) {\n throw new Error('exact process candidate executor supports only UTF-8 text and JSON outputs')\n }\n if (!posix.isAbsolute(request.launch.executable) && !request.launch.env.PATH?.trim()) {\n throw new Error('exact process candidate executable must be absolute or declare a signed PATH')\n }\n if (!request.roots) throw new Error('candidate execution roots are missing')\n assertAgentCandidateExecutionRoots(request.roots)\n}\n\nasync function materializeRequest(\n environment: AgentExactProcessEnvironment,\n request: AgentCandidateExecutorRequest,\n signal: AbortSignal,\n): Promise<void> {\n assertAgentCandidateExecutionRoots(request.roots)\n const knowledgePaths = assertKnowledgeExecutionBinding(request)\n for (const file of request.inputs.task.files) {\n await environment.writeFile(beneath(request.roots.taskRoot, file.path), file.bytes, {\n mode: file.mode,\n signal,\n })\n }\n for (const file of request.inputs.profile.files) {\n await environment.writeFile(profileFileExecutionPath(request, file), file.bytes, {\n mode: file.mode,\n signal,\n })\n }\n if (request.knowledge && knowledgePaths) {\n for (const file of request.knowledge.files) {\n await environment.writeFile(beneath(knowledgePaths.root, file.path), file.bytes, {\n mode: file.mode,\n signal,\n })\n }\n if (request.knowledge.retrievalConfig && knowledgePaths.retrievalConfig) {\n await environment.writeFile(\n knowledgePaths.retrievalConfig,\n request.knowledge.retrievalConfig,\n { mode: 0o644, signal },\n )\n }\n }\n if (request.instruction.delivery.kind === 'utf8-file') {\n await environment.writeFile(request.instruction.delivery.path, request.instruction.bytes, {\n mode: 0o644,\n signal,\n })\n }\n}\n\nfunction assertKnowledgeExecutionBinding(\n request: AgentCandidateExecutorRequest,\n): ReturnType<typeof candidateKnowledgeExecutionPaths> | undefined {\n const knowledge = request.knowledge\n if (!knowledge) {\n if (\n request.launch.env[CANDIDATE_KNOWLEDGE_ROOT_ENV] !== undefined ||\n request.launch.env[CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV] !== undefined\n ) {\n throw new Error('candidate launch declares knowledge paths without verified knowledge')\n }\n return undefined\n }\n const paths = candidateKnowledgeExecutionPaths(\n request.roots.taskRoot,\n knowledge.retrievalConfig !== undefined,\n )\n if (\n request.launch.env[CANDIDATE_KNOWLEDGE_ROOT_ENV] !== paths.root ||\n request.launch.env[CANDIDATE_KNOWLEDGE_RETRIEVAL_CONFIG_ENV] !== paths.retrievalConfig\n ) {\n throw new Error('candidate knowledge paths do not match the signed launch environment')\n }\n const reserved = [paths.root, paths.retrievalConfig].filter(\n (value): value is string => value !== undefined,\n )\n const otherFiles = [\n ...request.inputs.task.files.map((file) => beneath(request.roots.taskRoot, file.path)),\n ...request.inputs.profile.files.map((file) => profileFileExecutionPath(request, file)),\n ...(request.instruction.delivery.kind === 'utf8-file'\n ? [request.instruction.delivery.path]\n : []),\n ]\n if (\n otherFiles.some((path) =>\n reserved.some(\n (reservedPath) =>\n path === reservedPath ||\n path.startsWith(`${reservedPath}/`) ||\n reservedPath.startsWith(`${path}/`),\n ),\n )\n ) {\n throw new Error('candidate knowledge paths overlap other execution inputs')\n }\n return paths\n}\n\nfunction profileFileExecutionPath(\n request: AgentCandidateExecutorRequest,\n file: AgentCandidateExecutorRequest['inputs']['profile']['files'][number],\n): string {\n const workspace = request.executionPlan.value.material.profile.targetWorkspace\n const workspaceRoot = workspace === 'task' ? request.roots.taskRoot : request.roots.candidateRoot\n if (!workspaceRoot) throw new Error('candidate profile targets a missing workspace')\n if (file.root !== 'agent') return beneath(workspaceRoot, file.path)\n const agentDir = profileAgentDirectory(request)\n return beneath(agentDir, file.path)\n}\n\nfunction profileAgentDirectory(request: AgentCandidateExecutorRequest): string {\n const paths = candidateProfileAgentPaths(\n request.profilePlan.value.material,\n request.roots.profileRoot,\n )\n if (!paths) throw new Error('candidate profile agent-root file is missing its private root')\n if (\n request.launch.env[PI_CANDIDATE_AGENT_DIR_ENV] !== paths.agentDir ||\n request.launch.env[PI_CANDIDATE_SESSION_DIR_ENV] !== paths.sessionDir\n ) {\n throw new Error('candidate Pi agent-root files do not match the signed launch environment')\n }\n return paths.agentDir\n}\n\nfunction exactLaunch(request: AgentCandidateExecutorRequest): AgentExactProcessLaunch {\n const instruction = new TextDecoder('utf-8', { fatal: true }).decode(request.instruction.bytes)\n const base = {\n executable: request.launch.executable,\n args: request.launch.args,\n cwd: request.launch.cwd,\n env: request.launch.env,\n timeoutMs: 0,\n }\n switch (request.instruction.delivery.kind) {\n case 'argv-append':\n return { ...base, args: [...base.args, instruction] }\n case 'stdin-utf8':\n return { ...base, stdin: instruction }\n case 'utf8-file':\n return base\n }\n}\n\nasync function collectOutput(process: AgentExactProcess, maxBytes: number): Promise<Uint8Array> {\n const chunks: Buffer[] = []\n let byteLength = 0\n for await (const chunk of process.stdout()) {\n const bytes = Buffer.from(chunk, 'utf8')\n byteLength += bytes.byteLength\n if (byteLength > maxBytes) {\n let stopError: unknown\n try {\n await stopProcess(process)\n } catch (error) {\n stopError = error\n }\n throw new Error(`candidate output exceeds its ${maxBytes}-byte maximum`, {\n cause: stopError,\n })\n }\n chunks.push(bytes)\n }\n return Uint8Array.from(Buffer.concat(chunks, byteLength))\n}\n\nasync function awaitOutput(\n output: Promise<Uint8Array>,\n signal: AbortSignal,\n deadlineAtMs: number,\n): Promise<Uint8Array> {\n signal.throwIfAborted()\n const remainingMs = deadlineAtMs - Date.now()\n if (remainingMs <= 0) throw new Error('candidate output deadline expired')\n let timer: ReturnType<typeof setTimeout> | undefined\n let onAbort: (() => void) | undefined\n try {\n return await Promise.race([\n output,\n new Promise<never>((_resolve, reject) => {\n onAbort = () => reject(signal.reason ?? new Error('candidate output cancelled'))\n signal.addEventListener('abort', onAbort, { once: true })\n timer = setTimeout(\n () => reject(new Error('candidate output deadline expired')),\n remainingMs,\n )\n }),\n ])\n } finally {\n if (onAbort) signal.removeEventListener('abort', onAbort)\n if (timer) clearTimeout(timer)\n }\n}\n\nasync function stopProcess(process: AgentExactProcess): Promise<void> {\n const before = await process.status()\n if (!before.running) return\n try {\n await process.kill()\n } catch (error) {\n if ((await process.status()).running) throw error\n }\n const termination = await process.wait()\n assertTerminalStatus(await process.status(), termination)\n}\n\nfunction assertTerminalStatus(\n status: AgentExactProcessStatus,\n expected?: AgentCandidateTermination,\n): asserts status is AgentExactProcessStatus & { termination: AgentCandidateTermination } {\n if (status.running || !status.termination) {\n throw new Error('exact process returned no terminal reason after exit')\n }\n if (expected && !isDeepStrictEqual(status.termination, expected)) {\n throw new Error('exact process wait and status returned different terminal reasons')\n }\n}\n\nfunction assertExecutionEnvironment(\n environment: AgentExactProcessEnvironment,\n metadata: Record<string, unknown>,\n providerName: string,\n): void {\n if (!environment.id || environment.provider !== providerName) {\n throw new Error('exact process provider returned the wrong environment identity')\n }\n if (\n !Object.entries(metadata).every(([name, value]) =>\n isDeepStrictEqual(environment.metadata?.[name], value),\n )\n ) {\n throw new Error('exact process provider did not persist candidate execution metadata')\n }\n}\n\nfunction outputSpec(environment: AgentExactProcessEnvironment): { maxBytes: number } {\n const maxBytes = environment.metadata?.outputMaxBytes\n if (!Number.isSafeInteger(maxBytes) || Number(maxBytes) < 1) {\n throw new Error('candidate exact process output bound is unavailable')\n }\n return { maxBytes: Number(maxBytes) }\n}\n\nfunction executionKey(executionId: string, executionPlanDigest: Sha256Digest): string {\n return `${executionId}\\0${executionPlanDigest}`\n}\n\nfunction executionIdempotencyKey(executionId: string, executionPlanDigest: Sha256Digest): string {\n return `candidate-${canonicalCandidateDigest({\n kind: 'agent-candidate-execution-identity',\n executionId,\n executionPlanDigest,\n }).slice('sha256:'.length)}`\n}\n\nfunction exactImage(image: string, manifestDigest: Sha256Digest): string {\n if (isSha256Digest(image)) {\n if (image !== manifestDigest) {\n throw new Error('candidate container image conflicts with its resolved manifest')\n }\n return image\n }\n const marker = image.lastIndexOf('@')\n if (marker < 0) return `${image}@${manifestDigest}`\n if (image.slice(marker + 1) !== manifestDigest) {\n throw new Error('candidate container image conflicts with its resolved manifest')\n }\n return image\n}\n\nfunction environmentLifetimeMs(timeoutMs: number, retentionMs: number): number {\n const total = positiveInteger(timeoutMs, 'candidate execution timeout') + retentionMs\n if (!Number.isSafeInteger(total)) throw new Error('candidate environment lifetime is too large')\n return Math.ceil(total / 1_000) * 1_000\n}\n\nfunction exactResources(resources: AgentExactProcessResources): AgentExactProcessResources {\n if (!Number.isFinite(resources.cpu) || resources.cpu <= 0) {\n throw new Error('exact process CPU must be positive and finite')\n }\n return Object.freeze({\n cpu: resources.cpu,\n memoryMb: positiveInteger(resources.memoryMb, 'exact process memory'),\n diskMb: positiveInteger(resources.diskMb, 'exact process disk'),\n })\n}\n\nfunction positiveInteger(value: number, label: string): number {\n if (!Number.isSafeInteger(value) || value < 1)\n throw new Error(`${label} must be a positive integer`)\n return value\n}\n\nfunction beneath(root: string, relativePath: string): string {\n if (posix.isAbsolute(relativePath)) throw new Error('candidate input path must be relative')\n const path = posix.normalize(relativePath)\n if (path === '..' || path.startsWith('../')) {\n throw new Error('candidate input path escapes its execution root')\n }\n return posix.join(root, path)\n}\n\nfunction isSha256Digest(value: unknown): value is Sha256Digest {\n return typeof value === 'string' && /^sha256:[a-f0-9]{64}$/.test(value)\n}\n","import type {\n AgentCandidateModelAccessNetwork,\n AgentCandidateResolvedModel,\n Sha256Digest,\n} from '@tangle-network/agent-interface'\n\nimport { canonicalCandidateDigest, immutableCandidateValue } from './digest'\nimport { assertExactObjectKeys } from './exact-object'\nimport { sealAgentCandidateModelSettlement, usdToNanos } from './model-settlement'\nimport type {\n AgentCandidateModelLimits,\n AgentCandidateModelPort,\n AgentCandidateProtectedModelActivation,\n AgentCandidateProtectedModelReservation,\n AgentCandidateProtectedModelSettlement,\n} from './types'\n\nexport type AgentCandidateModelGrantReserveInput = Parameters<\n AgentCandidateModelPort['reserveGrant']\n>[0]\nexport type AgentCandidateModelGrantActivateInput = Parameters<\n AgentCandidateModelPort['activateGrant']\n>[0]\nexport type AgentCandidateModelGrantSettleInput = Parameters<\n AgentCandidateModelPort['settleGrant']\n>[0]\n\n/** Secret-free response from the service's reservation endpoint. */\nexport type AgentCandidateModelGrantReservation = AgentCandidateProtectedModelReservation\n\n/**\n * Narrow transport contract for a service that owns scoped model credentials\n * and the authoritative per-call usage ledger.\n *\n * An HTTP client can bind these methods to control-plane endpoints. Keeping\n * transport out of the runtime prevents parent credentials, endpoint paths,\n * and retry policy from becoming part of the portable candidate contract.\n */\nexport interface AgentCandidateModelGrantClient {\n reserve(input: AgentCandidateModelGrantReserveInput): Promise<AgentCandidateModelGrantReservation>\n activate(\n input: AgentCandidateModelGrantActivateInput,\n ): Promise<AgentCandidateProtectedModelActivation>\n settle(\n input: AgentCandidateModelGrantSettleInput,\n ): Promise<AgentCandidateProtectedModelSettlement>\n}\n\nexport interface CreateProtectedAgentCandidateModelPortOptions {\n client: AgentCandidateModelGrantClient\n /** Catalog/snapshot resolution stays separate from credential issuance. */\n resolveModel: AgentCandidateModelPort['resolve']\n /** The only public DNS name candidate processes may reach for inference. */\n gatewayDomain: string\n /** Exact environment names the activation endpoint must return, no more or fewer. */\n activationEnvNames: readonly string[]\n}\n\ninterface RememberedReservation {\n requestDigest: Sha256Digest\n responseDigest: Sha256Digest\n executionId: string\n preparationId: string\n grantDigest: Sha256Digest\n expiresAtMs: number\n resolved: AgentCandidateResolvedModel\n limits: AgentCandidateModelLimits\n maxCostUsdNanos: number\n activation: 'reserved' | 'activating' | 'activated'\n settlementDigest?: Sha256Digest\n settlementReason?: AgentCandidateModelGrantSettleInput['reason']\n}\n\ninterface RememberedSettlement {\n settlementDigest: Sha256Digest\n settlementReason: AgentCandidateModelGrantSettleInput['reason']\n expiresAtMs: number\n}\n\nconst MAX_RECENT_SETTLEMENTS = 4_096\nconst RECOVERED_SETTLEMENT_RETENTION_MS = 15 * 60 * 1_000\n\n/**\n * Bind a protected model-grant service to the immutable candidate runtime.\n *\n * The service remains the authority for expiry, admission, revocation, and\n * metering. This adapter independently checks every response before allowing\n * it to cross into candidate execution or durable receipt finalization.\n */\nexport function createProtectedAgentCandidateModelPort(\n options: CreateProtectedAgentCandidateModelPortOptions,\n): AgentCandidateModelPort {\n const gatewayDomain = assertGatewayDomain(options.gatewayDomain)\n const activationEnvNames = exactEnvironmentNames(options.activationEnvNames)\n const reservations = new Map<string, RememberedReservation>()\n const expiredReservations = new Map<\n string,\n { state: RememberedReservation; retainedUntilMs: number }\n >()\n const recentSettlements = new Map<string, RememberedSettlement>()\n\n return {\n resolve: async (input) => {\n const request = immutableCandidateValue(input)\n const resolved = validateResolvedModel(await options.resolveModel(request), request)\n return immutableCandidateValue(resolved)\n },\n\n reserveGrant: async (input) => {\n pruneExpiredState(reservations, expiredReservations, recentSettlements, Date.now())\n const request = immutableCandidateValue(input)\n validateReserveInput(request)\n const requestDigest = canonicalCandidateDigest(request)\n const key = reservationKey(request.executionId, request.preparationId)\n if (recentSettlements.has(key)) {\n throw new Error('protected model reservation is already settled')\n }\n const expired = expiredReservations.get(key)\n if (expired) throw new Error('protected model reservation has expired')\n const previous = reservations.get(key)\n if (previous && previous.requestDigest !== requestDigest) {\n throw new Error('protected model reservation retry changed immutable input')\n }\n\n const reservation = validateReservation(\n await options.client.reserve(request),\n request,\n gatewayDomain,\n )\n const responseDigest = canonicalCandidateDigest(reservation)\n if (recentSettlements.has(key)) {\n throw new Error('protected model reservation completed after the grant was settled')\n }\n const recorded = previous ?? reservations.get(key)\n if (recorded && recorded.requestDigest !== requestDigest) {\n throw new Error('protected model reservation retry changed immutable input')\n }\n if (recorded && recorded.responseDigest !== responseDigest) {\n throw new Error('protected model reservation retry returned different evidence')\n }\n if (!recorded) {\n reservations.set(key, {\n requestDigest,\n responseDigest,\n executionId: request.executionId,\n preparationId: request.preparationId,\n grantDigest: reservation.digest,\n expiresAtMs: request.expiresAtMs,\n resolved: immutableCandidateValue(request.resolved),\n limits: immutableCandidateValue(request.limits),\n maxCostUsdNanos: usdToNanos(request.limits.maxCostUsd, 'reserved maxCostUsd'),\n activation: 'reserved',\n })\n }\n return reservation\n },\n\n activateGrant: async (input) => {\n pruneExpiredState(reservations, expiredReservations, recentSettlements, Date.now())\n const request = immutableCandidateValue(input)\n const key = reservationKey(request.executionId, request.preparationId)\n if (recentSettlements.has(key)) throw new Error('protected model grant is already settled')\n const state = reservations.get(key)\n if (!state && expiredReservations.has(key)) {\n throw new Error('protected model grant reservation has expired')\n }\n if (!state) throw new Error('protected model grant was not reserved by this port')\n assertGrantIdentity(state, request)\n if (state.settlementDigest) throw new Error('protected model grant is already settled')\n if (state.activation !== 'reserved') {\n throw new Error('protected model grant activation is single-use')\n }\n if (!Number.isSafeInteger(request.deadlineAtMs) || request.deadlineAtMs <= 0) {\n throw new Error('protected model activation deadline must be a positive safe integer')\n }\n if (request.deadlineAtMs <= Date.now()) {\n throw new Error('protected model activation deadline must be in the future')\n }\n if (request.deadlineAtMs > state.expiresAtMs) {\n throw new Error('protected model activation deadline exceeds the reserved expiry')\n }\n state.activation = 'activating'\n try {\n const activation = validateActivation(\n await options.client.activate(request),\n state.limits.maxModelCalls === 0 ? [] : activationEnvNames,\n )\n if (recentSettlements.has(key) || reservations.get(key) !== state) {\n throw new Error('protected model grant settled while activation was in flight')\n }\n state.activation = 'activated'\n return activation\n } catch (error) {\n state.activation = 'reserved'\n throw error\n }\n },\n\n settleGrant: async (input) => {\n const now = Date.now()\n pruneExpiredState(reservations, expiredReservations, recentSettlements, now)\n const request = immutableCandidateValue(input)\n const key = reservationKey(request.executionId, request.preparationId)\n const state = reservations.get(key) ?? expiredReservations.get(key)?.state\n if (state) assertGrantIdentity(state, request)\n const remembered = state ?? recentSettlements.get(key)\n if (remembered?.settlementReason && remembered.settlementReason !== request.reason) {\n throw new Error('protected model settlement retry changed the termination reason')\n }\n\n const sealed = sealAgentCandidateModelSettlement(await options.client.settle(request), {\n preparationId: request.preparationId,\n grantDigest: request.grantDigest,\n model: request.resolved.model,\n })\n if (state) assertWithinReservedLimits(sealed.usage, state)\n\n const settlementDigest = canonicalCandidateDigest(sealed.value)\n if (remembered?.settlementDigest && remembered.settlementDigest !== settlementDigest) {\n throw new Error('protected model settlement retry returned a different final ledger')\n }\n if (remembered?.settlementReason && remembered.settlementReason !== request.reason) {\n throw new Error('protected model settlement retry changed the termination reason')\n }\n const expiresAtMs = state?.expiresAtMs ?? now + RECOVERED_SETTLEMENT_RETENTION_MS\n if (state) {\n state.settlementDigest = settlementDigest\n state.settlementReason = request.reason\n }\n reservations.delete(key)\n expiredReservations.delete(key)\n rememberSettlement(recentSettlements, key, {\n settlementDigest,\n settlementReason: request.reason,\n expiresAtMs,\n })\n return sealed.value\n },\n }\n}\n\nfunction validateReserveInput(input: AgentCandidateModelGrantReserveInput): void {\n if (!Number.isSafeInteger(input.expiresAtMs) || input.expiresAtMs <= 0) {\n throw new Error('protected model reservation expiry must be a positive safe integer')\n }\n if (input.expiresAtMs <= Date.now()) {\n throw new Error('protected model reservation expiry must be in the future')\n }\n for (const [name, value] of [\n ['maxModelCalls', input.limits.maxModelCalls],\n ['maxInputTokens', input.limits.maxInputTokens],\n ['maxOutputTokens', input.limits.maxOutputTokens],\n ['maxTotalTokens', input.limits.maxTotalTokens],\n ] as const) {\n if (value === undefined) continue\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`protected model reservation ${name} must be a nonnegative safe integer`)\n }\n }\n usdToNanos(input.limits.maxCostUsd, 'reserved maxCostUsd')\n}\n\nfunction validateReservation(\n value: unknown,\n expected: AgentCandidateModelGrantReserveInput,\n gatewayDomain: string,\n): AgentCandidateModelGrantReservation {\n const source = exactRecord(\n value,\n ['preparationId', 'digest', 'expiresAtMs', 'enforcedLimits', 'network'],\n 'protected model reservation response',\n )\n if (source.preparationId !== expected.preparationId) {\n throw new Error('protected model reservation response changed preparation identity')\n }\n if (!isSha256Digest(source.digest)) {\n throw new Error('protected model reservation response has an invalid digest')\n }\n if (source.expiresAtMs !== expected.expiresAtMs) {\n throw new Error('protected model reservation response changed expiry')\n }\n exactRecord(\n source.enforcedLimits,\n modelLimitKeys(expected.limits),\n 'protected model reservation enforced limits',\n )\n if (\n canonicalCandidateDigest(source.enforcedLimits) !== canonicalCandidateDigest(expected.limits)\n ) {\n throw new Error('protected model reservation response changed enforced limits')\n }\n\n const network = validateReservationNetwork(\n source.network,\n expected.limits.maxModelCalls,\n gatewayDomain,\n )\n return immutableCandidateValue({\n preparationId: source.preparationId,\n digest: source.digest,\n expiresAtMs: source.expiresAtMs,\n enforcedLimits: source.enforcedLimits,\n network,\n }) as AgentCandidateModelGrantReservation\n}\n\nfunction validateReservationNetwork(\n value: unknown,\n maxModelCalls: number,\n gatewayDomain: string,\n): AgentCandidateModelAccessNetwork {\n if (maxModelCalls === 0) {\n const source = exactRecord(value, ['mode'], 'protected model reservation network')\n if (source.mode !== 'disabled') {\n throw new Error('zero-call protected model reservation must disable gateway access')\n }\n return { mode: 'disabled' }\n }\n\n const source = exactRecord(value, ['mode', 'domains'], 'protected model reservation network')\n if (source.mode !== 'gateway-only') {\n throw new Error('protected model reservation must allow only its model gateway')\n }\n if (\n !Array.isArray(source.domains) ||\n source.domains.length !== 1 ||\n source.domains[0] !== gatewayDomain\n ) {\n throw new Error('protected model reservation returned an unexpected gateway domain')\n }\n return { mode: 'gateway-only', domains: [gatewayDomain] }\n}\n\nfunction validateActivation(\n value: unknown,\n expectedNames: readonly string[],\n): AgentCandidateProtectedModelActivation {\n const source = exactRecord(value, ['env'], 'protected model activation response')\n const env = record(source.env, 'protected model activation environment')\n const actualNames = Object.keys(env).sort()\n if (\n actualNames.length !== expectedNames.length ||\n actualNames.some((name, index) => name !== expectedNames[index])\n ) {\n throw new Error('protected model activation returned unexpected environment names')\n }\n const detached: Record<string, string> = Object.create(null) as Record<string, string>\n for (const name of expectedNames) {\n const value = env[name]\n if (typeof value !== 'string' || value.length < 8 || value.length > 65_536) {\n throw new Error(`protected model activation ${name} must be a non-empty protected value`)\n }\n detached[name] = value\n }\n return Object.freeze({ env: Object.freeze(detached) })\n}\n\nfunction validateResolvedModel(\n value: unknown,\n expected: Parameters<AgentCandidateModelPort['resolve']>[0],\n): AgentCandidateResolvedModel {\n const source = exactRecord(\n value,\n ['requested', 'provider', 'model', 'snapshot', 'reasoningEffort'],\n 'resolved candidate model',\n )\n if (source.requested !== expected.requested) {\n throw new Error('model resolver changed the evaluator-owned request')\n }\n if (source.reasoningEffort !== expected.reasoningEffort) {\n throw new Error('model resolver changed the evaluator-owned reasoning effort')\n }\n for (const name of ['requested', 'provider', 'model', 'snapshot'] as const) {\n if (typeof source[name] !== 'string' || source[name].length === 0) {\n throw new Error(`resolved candidate model ${name} must be non-empty`)\n }\n }\n return source as unknown as AgentCandidateResolvedModel\n}\n\nfunction assertGrantIdentity(\n expected: RememberedReservation,\n actual: AgentCandidateModelGrantActivateInput | AgentCandidateModelGrantSettleInput,\n): void {\n if (\n actual.executionId !== expected.executionId ||\n actual.preparationId !== expected.preparationId ||\n actual.grantDigest !== expected.grantDigest ||\n canonicalCandidateDigest(actual.resolved) !== canonicalCandidateDigest(expected.resolved)\n ) {\n throw new Error('protected model grant input does not match its immutable reservation')\n }\n}\n\nfunction assertWithinReservedLimits(\n usage: {\n modelCalls: number\n inputTokens: number\n outputTokens: number\n costUsdNanos: number\n },\n reservation: RememberedReservation,\n): void {\n for (const [name, actual, limit] of [\n ['model calls', usage.modelCalls, reservation.limits.maxModelCalls],\n ['input tokens', usage.inputTokens, reservation.limits.maxInputTokens],\n ['output tokens', usage.outputTokens, reservation.limits.maxOutputTokens],\n ['cost USD nanos', usage.costUsdNanos, reservation.maxCostUsdNanos],\n ] as const) {\n if (actual > limit) {\n throw new Error(`protected model settlement ${name} ${actual} exceeds reserved ${limit}`)\n }\n }\n const maxTotalTokens = reservation.limits.maxTotalTokens\n if (maxTotalTokens !== undefined) {\n const totalTokens = usage.inputTokens + usage.outputTokens\n if (!Number.isSafeInteger(totalTokens)) {\n throw new Error('protected model settlement total token usage is incomplete')\n }\n if (totalTokens > maxTotalTokens) {\n throw new Error(\n `protected model settlement total tokens ${totalTokens} exceeds reserved ${maxTotalTokens}`,\n )\n }\n }\n}\n\nfunction modelLimitKeys(limits: AgentCandidateModelLimits): readonly string[] {\n return limits.maxTotalTokens === undefined\n ? ['maxModelCalls', 'maxInputTokens', 'maxOutputTokens', 'maxCostUsd']\n : ['maxModelCalls', 'maxInputTokens', 'maxOutputTokens', 'maxTotalTokens', 'maxCostUsd']\n}\n\nfunction exactEnvironmentNames(values: readonly string[]): readonly string[] {\n if (values.length === 0) {\n throw new Error('protected model activation environment names must not be empty')\n }\n const names = [...values].sort()\n if (new Set(names).size !== names.length) {\n throw new Error('protected model activation environment names must be unique')\n }\n for (const name of names) {\n if (\n !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) ||\n ['__proto__', 'constructor', 'prototype'].includes(name)\n ) {\n throw new Error(`protected model activation environment name is invalid: ${name}`)\n }\n }\n return Object.freeze(names)\n}\n\nfunction assertGatewayDomain(value: string): string {\n if (\n value.length > 253 ||\n value !== value.toLowerCase() ||\n value.endsWith('.') ||\n value.includes(':') ||\n value === 'localhost' ||\n value.endsWith('.localhost') ||\n value === 'metadata.google' ||\n value === 'metadata.google.internal'\n ) {\n throw new Error('protected model gateway must be an exact lowercase public DNS name')\n }\n const labels = value.split('.')\n if (\n labels.length < 2 ||\n !labels.every(\n (label) =>\n label.length >= 1 && label.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label),\n ) ||\n !/[a-z]/.test(labels.at(-1) ?? '')\n ) {\n throw new Error('protected model gateway must be an exact lowercase public DNS name')\n }\n return value\n}\n\nfunction reservationKey(executionId: string, preparationId: string): string {\n return canonicalCandidateDigest({ executionId, preparationId })\n}\n\nfunction pruneExpiredState(\n reservations: Map<string, RememberedReservation>,\n expiredReservations: Map<string, { state: RememberedReservation; retainedUntilMs: number }>,\n settlements: Map<string, RememberedSettlement>,\n now: number,\n): void {\n for (const [key, value] of reservations) {\n if (value.expiresAtMs <= now) {\n reservations.delete(key)\n expiredReservations.set(key, {\n state: value,\n retainedUntilMs: now + RECOVERED_SETTLEMENT_RETENTION_MS,\n })\n }\n }\n for (const [key, value] of expiredReservations) {\n if (value.retainedUntilMs <= now) expiredReservations.delete(key)\n }\n for (const [key, value] of settlements) {\n if (value.expiresAtMs <= now) settlements.delete(key)\n }\n}\n\nfunction rememberSettlement(\n settlements: Map<string, RememberedSettlement>,\n key: string,\n value: RememberedSettlement,\n): void {\n settlements.delete(key)\n settlements.set(key, value)\n while (settlements.size > MAX_RECENT_SETTLEMENTS) {\n const oldest = settlements.keys().next().value\n if (oldest === undefined) return\n settlements.delete(oldest)\n }\n}\n\nfunction isSha256Digest(value: unknown): value is Sha256Digest {\n return typeof value === 'string' && /^sha256:[a-f0-9]{64}$/.test(value)\n}\n\nfunction exactRecord(\n value: unknown,\n keys: readonly string[],\n label: string,\n): Record<string, unknown> {\n const source = record(value, label)\n assertExactObjectKeys(source, keys, label)\n return source\n}\n\nfunction record(value: unknown, label: string): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${label} must be an object`)\n }\n const prototype = Object.getPrototypeOf(value)\n if (prototype !== Object.prototype && prototype !== null) {\n throw new Error(`${label} must be a plain object`)\n }\n return value as Record<string, unknown>\n}\n"],"mappings":";;;;;;AAqCA,MAAM,+BAA+B;AACrC,MAAM,gCAAgC,KAAK;;AA2B3C,SAAgB,wCACd,SAC4B;CAC5B,OAAO,IAAI,mCAAmC,OAAO;AACvD;AAEA,IAAM,qCAAN,MAA+E;CAShD;CAR7B,yBAA0B,IAAI,IAAkC;CAChE;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,SAAgE;EAA/C,KAAA,UAAA;EAC3B,IAAI,CAAC,QAAQ,SAAS,cACpB,MAAM,IAAI,MACR,+BAA+B,QAAQ,SAAS,KAAK,qCACvD;EAEF,KAAK,eAAe,QAAQ,SAAS;EACrC,KAAK,YAAY,eAAe,QAAQ,SAAS;EACjD,KAAK,qBAAqB,gBACxB,QAAQ,sBAAsB,8BAC9B,iCACF;EACA,KAAK,sBAAsB,gBACzB,QAAQ,uBAAuB,+BAC/B,kCACF;EACA,KAAK,kBAAkB,QAAQ,kBAC3B,wBAAwB,QAAQ,eAAe,IAC/C,KAAA;CACN;CAEA,MAAM,QACJ,SACA,SACA;EACA,uBAAuB,OAAO;EAC9B,MAAM,UAAU,QAAQ,UAAU,KAAK;EACvC,IAAI,QAAQ,SAAS,UAAU,MAAM,IAAI,MAAM,gDAAgD;EAC/F,MAAM,UAAU,QAAQ,cAAc,MAAM,SAAS,MAAM,OAAO;EAClE,MAAM,SACJ,QAAQ,SAAS,aACZ,EAAE,MAAM,UAAU,IAClB;GAAE,MAAM;GAAU,cAAc,CAAC,GAAG,QAAQ,OAAO;EAAE;EAC5D,MAAM,KAAK,iBAAiB,OAAO,IAAI;EACvC,QAAQ,OAAO,eAAe;EAE9B,MAAM,MAAM,aA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