@tangle-network/sandbox 1.0.215 → 1.0.216

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 (46) hide show
  1. package/dist/agent/index.d.ts +4 -4
  2. package/dist/agent/index.js +5 -5
  3. package/dist/agent/preview.d.ts +1 -1
  4. package/dist/agent/preview.js +1 -1
  5. package/dist/{agent-run-outcome-CP2N40aT.d.ts → agent-run-outcome-DW_S8f-u.d.ts} +2 -2
  6. package/dist/{api-request-BKzR6BJ4.js → api-request-C_bupPUV.js} +1 -1
  7. package/dist/{browser-interactive-control-controller-7wyaNSvi.d.ts → browser-interactive-control-controller-s9d82qc9.d.ts} +1 -1
  8. package/dist/{chunked-upload-D6ZCQ-iN.js → chunked-upload-4QOzIF2U.js} +1 -1
  9. package/dist/{chunked-upload-file-D3YxQdAl.js → chunked-upload-file-FxIlaF8n.js} +1 -1
  10. package/dist/{client-DBfpAz8x.js → client-BO6CLWUk.js} +5 -5
  11. package/dist/{client-DiLd0XGB.d.ts → client-CSMb6fHz.d.ts} +23 -6
  12. package/dist/collaboration/index.js +1 -1
  13. package/dist/{collaboration-BgSGO1KD.js → collaboration-Bv22hvgZ.js} +1 -1
  14. package/dist/{core-HKoYifvH.js → core-lu45UrVr.js} +2 -2
  15. package/dist/core.d.ts +6 -6
  16. package/dist/core.js +5 -5
  17. package/dist/{errors-CNszZUZ2.js → errors-Bh1udpJ0.js} +2 -0
  18. package/dist/{file-download-DrzpcvdM.js → file-download-B9UceD-P.js} +1 -1
  19. package/dist/{index-DyFU9hy7.d.ts → index-DB4MbfIb.d.ts} +5 -5
  20. package/dist/index.d.ts +10 -10
  21. package/dist/index.js +49 -10
  22. package/dist/intelligence/index.js +3 -3
  23. package/dist/interactive-control.d.ts +1 -1
  24. package/dist/{interactive-controller-BzObb8aT.d.ts → interactive-controller-Cl9Ablmg.d.ts} +3 -3
  25. package/dist/{interactive-controller-C-CuPVMA.js → interactive-controller-DzlxPT5W.js} +2 -2
  26. package/dist/{lines-D0dHQ3X5.d.ts → lines-DXdAUnUf.d.ts} +1 -1
  27. package/dist/{lines-DHOIUO-t.js → lines-DvSNh5dD.js} +1 -1
  28. package/dist/lines.d.ts +1 -1
  29. package/dist/lines.js +1 -1
  30. package/dist/{mcp-local-YFGnFNBR.js → mcp-local-CPZ9Ya53.js} +2 -2
  31. package/dist/{preview-CrXG9Y8a.d.ts → preview-DhFcCERz.d.ts} +3 -3
  32. package/dist/{public-templates-Ba-DTf2O.d.ts → public-templates-D0QpNlni.d.ts} +2 -2
  33. package/dist/public-templates.d.ts +1 -1
  34. package/dist/public-templates.js +1 -1
  35. package/dist/{raw-evidence-archive-DrgeV9_0.js → raw-evidence-archive-BqN1_X-V.js} +1 -1
  36. package/dist/runtime.d.ts +5 -5
  37. package/dist/runtime.js +4 -4
  38. package/dist/{sandbox-CUPiQpiD.js → sandbox-B_5sumhE.js} +3383 -123
  39. package/dist/select-seat-command.d.ts +1 -1
  40. package/dist/select-seat-command.js +1 -1
  41. package/dist/tangle/index.d.ts +1 -1
  42. package/dist/tangle/index.js +1 -1
  43. package/dist/{tangle-Bo9s-kSv.js → tangle-rniKWozO.js} +2 -2
  44. package/dist/{terminal-stream-types-DeH8FF0d.d.ts → terminal-stream-types-B74nb8jV.d.ts} +3 -1
  45. package/dist/{types-BE70nj5h.d.ts → types-DzB-PS9p.d.ts} +1 -1
  46. package/package.json +5 -5
@@ -1,26 +1,26 @@
1
- import { A as normalizeRuntimeBackendConfig, C as encodeTextForWire, D as applyRequestedModel, F as withoutRuntimeSecrets, I as createAgentRunOutcomeTracker, L as deriveAgentResultOutcome, M as requestedSecretProfilePublicDigest, O as assertCurrentBackendType, S as encodePromptForWire, T as canUseNodeHttp2, W as normalizeEffectiveBackend, _ as isTraceId, a as assertScopedTokenActive, b as resolveDispatchRunIdentity, c as SandboxRuntimeApi, d as appendSessionIdQuery, f as callHeaders, g as TRACE_ID_HEADER, h as isRetryableCredentialRefusal, i as terminalUpgradeHeadersSupported, j as requestedPublicProfileDigest, k as mergeRuntimeBackendConfig, l as normalizeSessionInfo, m as assertFileWritePreconditions, n as InteractiveSessionController, p as sessionHeaders, r as TerminalStream, s as requestScopedToken, u as sessionMessageRequestBody, v as mintTraceId, w as runtimeFilesystemPath, x as validateAcceptedDispatchRunRef, y as resolveTraceId } from "./interactive-controller-C-CuPVMA.js";
2
- import { C as boundedIdentifierSchema, E as boundedStringSchema, g as sha256DigestSchema$1, o as canonicalCandidateDigest$1, s as canonicalCandidateJson$1, u as isCanonicalJsonValue$1 } from "./harness-DMaNgn0S.js";
3
- import { t as sha256 } from "./sha2-vu4U-x2L.js";
1
+ import { A as normalizeRuntimeBackendConfig, C as encodeTextForWire, D as applyRequestedModel, F as withoutRuntimeSecrets, I as createAgentRunOutcomeTracker, L as deriveAgentResultOutcome, M as requestedSecretProfilePublicDigest, O as assertCurrentBackendType, S as encodePromptForWire, T as canUseNodeHttp2, W as normalizeEffectiveBackend, _ as isTraceId, a as assertScopedTokenActive, b as resolveDispatchRunIdentity, c as SandboxRuntimeApi, d as appendSessionIdQuery, f as callHeaders, g as TRACE_ID_HEADER, h as isRetryableCredentialRefusal, i as terminalUpgradeHeadersSupported, j as requestedPublicProfileDigest, k as mergeRuntimeBackendConfig, l as normalizeSessionInfo, m as assertFileWritePreconditions, n as InteractiveSessionController, p as sessionHeaders, r as TerminalStream, s as requestScopedToken, u as sessionMessageRequestBody, v as mintTraceId, w as runtimeFilesystemPath, x as validateAcceptedDispatchRunRef, y as resolveTraceId } from "./interactive-controller-DzlxPT5W.js";
2
+ import { C as boundedIdentifierSchema$1, E as boundedStringSchema$1, g as sha256DigestSchema$1, o as canonicalCandidateDigest$1, s as canonicalCandidateJson$1, u as isCanonicalJsonValue$1 } from "./harness-DMaNgn0S.js";
3
+ import { t as sha256$1 } from "./sha2-vu4U-x2L.js";
4
4
  import { A as agentInteractiveSessionStatusMatchesRef, B as PlanContinuationSchema, C as AgentInteractiveSessionStopAcknowledgementSchema, D as agentInteractiveSessionControlClaimMatchesRef, E as agentInteractiveSessionControlClaimIsNewer, F as AgentRunCancellationAcknowledgementSchema, G as InteractionResponseSchema, H as InteractionBindingSchema, I as AgentRunCancellationRequestSchema, L as agentRunCancellationAcknowledgementMatchesRequest, M as agentInteractiveDimensionSchema, N as sameAgentExactRun, O as agentInteractiveSessionPromptAcknowledgementMatchesCommand, P as AgentExactRunControlRefSchema, S as AgentInteractiveSessionStatusSchema, T as agentInteractiveSessionControlClaimAcknowledgementMatchesRequest, U as InteractionRequestSchema, V as InteractionAcknowledgementSchema, W as InteractionResponseCommandSchema, _ as AgentInteractiveSessionControlClaimRequestSchema, b as AgentInteractiveSessionPromptCommandSchema, d as interactiveSessionControlClaimResponseSchema, f as interactiveSessionControlReleaseResponseSchema, g as AgentInteractiveSessionControlClaimAcknowledgementSchema, h as AgentInteractiveSessionAttachSchema, j as agentInteractiveSessionStopAcknowledgementMatchesCommand, l as createInteractiveControlHolderId, m as interactiveSessionStatusResponseSchema, p as interactiveSessionControlValidationResponseSchema, v as AgentInteractiveSessionControlClaimSchema, w as AgentInteractiveSessionStopCommandSchema, x as AgentInteractiveSessionRefSchema, y as AgentInteractiveSessionPromptAcknowledgementSchema } from "./browser-interactive-control-controller-BiP6TJFP.js";
5
- import { a as ProxySecretReceiptSchema, o as canonicalAgentProfileValue, r as agentProfileSchema } from "./profile-schema-C1KpT-wS.js";
6
- import { C as ServerError, D as ValidationError, E as TimeoutError, S as SandboxError, T as StreamInterruptedError, _ as NotFoundError, a as readResponseJson, d as EdgeNotReadyError, g as NetworkError, i as parseResponseError, l as CapabilityError, n as isTransientWrite, o as retryWhen, r as parseErrorResponse, s as AuthError, t as TerminalStreamError, w as StateError, y as ProfileFileMountPathError } from "./errors-CNszZUZ2.js";
5
+ import { a as ProxySecretReceiptSchema$1, o as canonicalAgentProfileValue$1, r as agentProfileSchema$1 } from "./profile-schema-C1KpT-wS.js";
6
+ import { C as ServerError, D as ValidationError, E as TimeoutError, S as SandboxError, T as StreamInterruptedError, _ as NotFoundError, a as readResponseJson, d as EdgeNotReadyError, g as NetworkError, i as parseResponseError, l as CapabilityError, n as isTransientWrite, o as retryWhen, r as parseErrorResponse, s as AuthError, t as TerminalStreamError, w as StateError, y as ProfileFileMountPathError } from "./errors-Bh1udpJ0.js";
7
7
  import { n as combineAbortSignals, t as awaitWithAbort } from "./abort-signal-BbJTt2QJ.js";
8
8
  import { a as backoffDelayMs, r as abortableSleep } from "./retry-policy-0_NCh5OB.js";
9
9
  import { a as SANDBOX_PROXY_REQUEST_MAX_BYTES, c as PROFILE_FILE_MOUNT_OUTSIDE_ROOTS_CODE, d as isProfileFileMountOutsideRoots, f as profileFileMountOutsideRootsMessage, l as SANDBOX_AGENT_HOME, o as FILE_OPERATION_LIMITS, u as SANDBOX_FILE_API_ABSOLUTE_ROOTS } from "./file-transfer-BSe4ayU9.js";
10
- import { c as awaitSdkResend, l as countSdkRequest, s as uploadChunked, u as takeSdkTurn } from "./chunked-upload-D6ZCQ-iN.js";
11
- import { a as rewrapResponse, i as isReplayableBody, t as IDEMPOTENT_METHODS } from "./api-request-BKzR6BJ4.js";
10
+ import { c as awaitSdkResend, l as countSdkRequest, s as uploadChunked, u as takeSdkTurn } from "./chunked-upload-4QOzIF2U.js";
11
+ import { a as rewrapResponse, i as isReplayableBody, t as IDEMPOTENT_METHODS } from "./api-request-C_bupPUV.js";
12
12
  import { n as fetchWithKeepAlive, t as emitTiming } from "./keep-alive-fetch-BIaDMUtu.js";
13
13
  import { t as SIDECAR_PROXY_ERROR_HEADER } from "./sidecar-proxy-error-DpBLxIof.js";
14
14
  import { t as parseSSEStream } from "./sse-parser-DOCszo1K.js";
15
15
  import { t as runPreparedProcess } from "./prepared-process-N-y0xr9S.js";
16
16
  import { a as isBackendType, r as cliAuthReferenceSchema } from "./cli-auth-bundle-C6DtK7GX-BbbiAn-Z.js";
17
17
  import "./cli-auth-bundle-CMJWI99l.js";
18
- import { n as SandboxLines } from "./lines-DHOIUO-t.js";
19
- import { t as downloadFile } from "./file-download-DrzpcvdM.js";
18
+ import { n as SandboxLines } from "./lines-DvSNh5dD.js";
19
+ import { t as downloadFile } from "./file-download-B9UceD-P.js";
20
20
  import { z } from "zod";
21
21
  import { createHash } from "node:crypto";
22
22
  import { constants } from "node:fs";
23
- import "node:path";
23
+ import { isAbsolute, win32 } from "node:path";
24
24
  import "node:fs/promises";
25
25
  import { PART_TEXT, PART_TEXT_SUFFIX, locatePart } from "@tangle-network/agent-core/sse";
26
26
  import { readTokenUsage } from "@tangle-network/agent-core";
@@ -36,17 +36,17 @@ import { OTLP_SPAN_KIND, OTLP_STATUS_CODE, msToUnixNano, otlpTraceExport, toOtlp
36
36
  * references only after this public identity is fixed.
37
37
  */
38
38
  function canonicalAgentProfileDigest(profile) {
39
- const material = canonicalAgentProfileValue(agentProfileSchema.parse(profile));
39
+ const material = canonicalAgentProfileValue$1(agentProfileSchema$1.parse(profile));
40
40
  if (material === void 0 || !isCanonicalJsonValue$1(material)) throw new Error("AgentProfile must contain finite, acyclic RFC 8785 JSON values");
41
41
  return canonicalCandidateDigest$1(material);
42
42
  }
43
43
  //#endregion
44
44
  //#region ../../../node_modules/.pnpm/@tangle-network+agent-interface@5.10.13/node_modules/@tangle-network/agent-interface/dist/environment-interactive-start.js
45
45
  const AgentInteractiveSessionRunCoordinatesSchema = z.strictObject({
46
- provider: boundedIdentifierSchema,
47
- environmentId: boundedIdentifierSchema,
48
- sessionId: boundedIdentifierSchema,
49
- executionId: boundedIdentifierSchema
46
+ provider: boundedIdentifierSchema$1,
47
+ environmentId: boundedIdentifierSchema$1,
48
+ sessionId: boundedIdentifierSchema$1,
49
+ executionId: boundedIdentifierSchema$1
50
50
  });
51
51
  /**
52
52
  * Start one native coding-agent TUI from caller-owned request material.
@@ -57,11 +57,11 @@ const AgentInteractiveSessionRunCoordinatesSchema = z.strictObject({
57
57
  */
58
58
  const AgentInteractiveSessionStartSchema = z.strictObject({
59
59
  run: AgentExactRunControlRefSchema,
60
- profile: agentProfileSchema,
60
+ profile: agentProfileSchema$1,
61
61
  requestedProfileDigest: sha256DigestSchema$1,
62
62
  authMode: z.literal("oauth").optional(),
63
- initialPrompt: boundedStringSchema.optional(),
64
- cwd: boundedStringSchema.min(1).optional(),
63
+ initialPrompt: boundedStringSchema$1.optional(),
64
+ cwd: boundedStringSchema$1.min(1).optional(),
65
65
  cols: agentInteractiveDimensionSchema.optional(),
66
66
  rows: agentInteractiveDimensionSchema.optional()
67
67
  });
@@ -129,39 +129,39 @@ const terminalDimensionSchema = z.number().int().positive().max(1e4);
129
129
  * or an expired terminal fails closed at the call sites that read it.
130
130
  */
131
131
  const TerminalSessionRefSchema = z.strictObject({
132
- terminalSessionId: boundedIdentifierSchema,
133
- parentExecutionId: boundedIdentifierSchema,
134
- name: boundedIdentifierSchema,
135
- shell: boundedStringSchema.min(1),
136
- command: boundedStringSchema.optional(),
137
- cwd: boundedStringSchema.min(1),
132
+ terminalSessionId: boundedIdentifierSchema$1,
133
+ parentExecutionId: boundedIdentifierSchema$1,
134
+ name: boundedIdentifierSchema$1,
135
+ shell: boundedStringSchema$1.min(1),
136
+ command: boundedStringSchema$1.optional(),
137
+ cwd: boundedStringSchema$1.min(1),
138
138
  cols: terminalDimensionSchema,
139
139
  rows: terminalDimensionSchema,
140
- connectionId: boundedIdentifierSchema.optional(),
140
+ connectionId: boundedIdentifierSchema$1.optional(),
141
141
  createdAt: z.iso.datetime().max(64),
142
142
  lastActivityAt: z.iso.datetime().max(64),
143
143
  expiresAt: z.iso.datetime().max(64),
144
144
  isRunning: z.boolean(),
145
145
  exitCode: z.number().int().optional(),
146
- exitSignal: boundedIdentifierSchema.optional(),
146
+ exitSignal: boundedIdentifierSchema$1.optional(),
147
147
  attachCount: z.number().int().nonnegative()
148
148
  });
149
149
  /** Raw bytes written to the terminal, normalized to UTF-8 text. */
150
- const TerminalInputSchema = z.strictObject({ data: boundedStringSchema });
150
+ const TerminalInputSchema = z.strictObject({ data: boundedStringSchema$1 });
151
151
  /** New terminal geometry. */
152
152
  const TerminalResizeSchema = z.strictObject({
153
153
  cols: terminalDimensionSchema,
154
154
  rows: terminalDimensionSchema
155
155
  });
156
156
  z.strictObject({
157
- parentExecutionId: boundedIdentifierSchema,
158
- terminalSessionId: boundedIdentifierSchema.optional(),
159
- connectionId: boundedIdentifierSchema.optional(),
157
+ parentExecutionId: boundedIdentifierSchema$1,
158
+ terminalSessionId: boundedIdentifierSchema$1.optional(),
159
+ connectionId: boundedIdentifierSchema$1.optional(),
160
160
  mode: z.enum(["attach", "logical"]),
161
161
  cols: terminalDimensionSchema.optional(),
162
162
  rows: terminalDimensionSchema.optional(),
163
- command: boundedStringSchema.optional(),
164
- cwd: boundedStringSchema.optional()
163
+ command: boundedStringSchema$1.optional(),
164
+ cwd: boundedStringSchema$1.optional()
165
165
  });
166
166
  z.discriminatedUnion("status", [
167
167
  z.strictObject({
@@ -172,11 +172,11 @@ z.discriminatedUnion("status", [
172
172
  }),
173
173
  z.strictObject({
174
174
  status: z.literal("unavailable"),
175
- reason: boundedStringSchema.min(1)
175
+ reason: boundedStringSchema$1.min(1)
176
176
  }),
177
177
  z.strictObject({
178
178
  status: z.literal("unknown"),
179
- message: boundedStringSchema.min(1),
179
+ message: boundedStringSchema$1.min(1),
180
180
  retryable: z.boolean()
181
181
  })
182
182
  ]);
@@ -194,7 +194,7 @@ const TerminalOutputEventSchema = z.discriminatedUnion("type", [
194
194
  z.strictObject({
195
195
  type: z.literal("output"),
196
196
  seq: z.number().int().nonnegative(),
197
- data: boundedStringSchema
197
+ data: boundedStringSchema$1
198
198
  }),
199
199
  z.strictObject({
200
200
  type: z.literal("resize"),
@@ -204,29 +204,29 @@ const TerminalOutputEventSchema = z.discriminatedUnion("type", [
204
204
  z.strictObject({
205
205
  type: z.literal("exit"),
206
206
  exitCode: z.number().int().optional(),
207
- exitSignal: boundedIdentifierSchema.optional()
207
+ exitSignal: boundedIdentifierSchema$1.optional()
208
208
  }),
209
209
  z.strictObject({
210
210
  type: z.literal("error"),
211
- message: boundedStringSchema.min(1)
211
+ message: boundedStringSchema$1.min(1)
212
212
  })
213
213
  ]);
214
214
  z.discriminatedUnion("status", [
215
215
  z.strictObject({
216
216
  status: z.literal("detached"),
217
- terminalSessionId: boundedIdentifierSchema,
218
- connectionId: boundedIdentifierSchema.optional()
217
+ terminalSessionId: boundedIdentifierSchema$1,
218
+ connectionId: boundedIdentifierSchema$1.optional()
219
219
  }),
220
220
  z.strictObject({
221
221
  status: z.literal("closed"),
222
- terminalSessionId: boundedIdentifierSchema,
222
+ terminalSessionId: boundedIdentifierSchema$1,
223
223
  exitCode: z.number().int().optional(),
224
- exitSignal: boundedIdentifierSchema.optional()
224
+ exitSignal: boundedIdentifierSchema$1.optional()
225
225
  }),
226
226
  z.strictObject({
227
227
  status: z.literal("unknown"),
228
- terminalSessionId: boundedIdentifierSchema,
229
- message: boundedStringSchema.min(1),
228
+ terminalSessionId: boundedIdentifierSchema$1,
229
+ message: boundedStringSchema$1.min(1),
230
230
  retryable: z.boolean()
231
231
  })
232
232
  ]);
@@ -433,7 +433,7 @@ function normalizeEgressPolicyFields(data) {
433
433
  /** Shape and resource identity are required before exposing current credential metadata. */
434
434
  function normalizeProxySecretReceipt(raw, sandboxId) {
435
435
  if (raw === void 0) return void 0;
436
- const receipt = ProxySecretReceiptSchema.parse(raw);
436
+ const receipt = ProxySecretReceiptSchema$1.parse(raw);
437
437
  if (receipt.sandboxId !== sandboxId) throw new ServerError("Proxy secret receipt names another sandbox", { status: 502 });
438
438
  return receipt;
439
439
  }
@@ -3107,6 +3107,164 @@ async function isRefusedBearer(response) {
3107
3107
  }
3108
3108
  }
3109
3109
  //#endregion
3110
+ //#region ../../../node_modules/.pnpm/@tangle-network+agent-interface@5.10.11/node_modules/@tangle-network/agent-interface/dist/provider-config.js
3111
+ const nativeWebSearchKeys = new Set(["websearch"]);
3112
+ const nativeWebFetchKeys = new Set(["webfetch", "fetch"]);
3113
+ function resolveNativeWebTools(tools) {
3114
+ if (!tools) return {};
3115
+ const posture = {};
3116
+ for (const [key, value] of Object.entries(tools)) {
3117
+ if (typeof value !== "boolean") continue;
3118
+ const normalized = key.replace(/[^a-z0-9]/gi, "").toLowerCase();
3119
+ if (nativeWebSearchKeys.has(normalized)) posture.search = value;
3120
+ else if (nativeWebFetchKeys.has(normalized)) posture.fetch = value;
3121
+ }
3122
+ return posture;
3123
+ }
3124
+ //#endregion
3125
+ //#region ../../../node_modules/.pnpm/@tangle-network+agent-interface@5.10.11/node_modules/@tangle-network/agent-interface/dist/contract-limits.js
3126
+ /** Limits applied before a value is hashed, copied, or sent to a provider. */
3127
+ const CONTRACT_MAX_STRING_LENGTH = 16384;
3128
+ /** Maximum length of one canonical confidential-attestation quote. */
3129
+ const CONTRACT_MAX_CONFIDENTIAL_ATTESTATION_QUOTE_LENGTH = 32768;
3130
+ const CONTRACT_MAX_ARRAY_LENGTH = 1024;
3131
+ const CONTRACT_MAX_JSON_NODES = 8192;
3132
+ const boundedStringSchema = z.string().max(CONTRACT_MAX_STRING_LENGTH);
3133
+ z.string().max(CONTRACT_MAX_CONFIDENTIAL_ATTESTATION_QUOTE_LENGTH);
3134
+ const boundedIdentifierSchema = boundedStringSchema.min(1).max(512).refine((value) => value.trim() === value, "identifier cannot have outer whitespace");
3135
+ /** Admit ordinary JSON before recursive parsing, copying or hashing. */
3136
+ function isBoundedJsonValue(value) {
3137
+ return boundedJson(value);
3138
+ }
3139
+ /** Exact serialized JSON UTF-8 byte count for one string scalar. */
3140
+ function serializedJsonStringBytes(value) {
3141
+ let bytes = 2;
3142
+ for (let index = 0; index < value.length; index += 1) {
3143
+ const code = value.charCodeAt(index);
3144
+ if (code === 34 || code === 92 || code === 8 || code === 12 || code === 10 || code === 13 || code === 9) bytes += 2;
3145
+ else if (code < 32) bytes += 6;
3146
+ else if (code >= 55296 && code <= 56319 && index + 1 < value.length) {
3147
+ const next = value.charCodeAt(index + 1);
3148
+ if (next >= 56320 && next <= 57343) {
3149
+ bytes += 4;
3150
+ index += 1;
3151
+ } else bytes += 6;
3152
+ } else if (code >= 55296 && code <= 57343) bytes += 6;
3153
+ else if (code < 128) bytes += 1;
3154
+ else if (code < 2048) bytes += 2;
3155
+ else bytes += 3;
3156
+ if (bytes > 1048576) return bytes;
3157
+ }
3158
+ return bytes;
3159
+ }
3160
+ /** Event content permits large strings within the exact serialized UTF-8 budget. */
3161
+ function isBoundedEventContentJson(value, { omitUndefinedObjectFields = false } = {}) {
3162
+ return boundedJson(value, {
3163
+ content: true,
3164
+ omitUndefinedObjectFields
3165
+ });
3166
+ }
3167
+ /**
3168
+ * Digest material omits undefined object fields; portable profile values require data properties.
3169
+ * `content` bounds strings by the serialized UTF-8 budget instead of each string's length, for
3170
+ * opaque values that may legitimately copy unbounded typed fields such as inline file content.
3171
+ */
3172
+ function isBoundedJsonMaterial(value, { dataPropertiesOnly = false, content = false } = {}) {
3173
+ return boundedJson(value, {
3174
+ material: true,
3175
+ omitUndefinedObjectFields: true,
3176
+ dataPropertiesOnly,
3177
+ content
3178
+ });
3179
+ }
3180
+ /** One iterative walker owns structural admission; typed domains keep their own schema limits. */
3181
+ function boundedJson(value, options = {}) {
3182
+ const pending = [{
3183
+ value,
3184
+ depth: 0
3185
+ }];
3186
+ const ancestors = /* @__PURE__ */ new Set();
3187
+ let nodes = 0;
3188
+ let bytes = 0;
3189
+ const addBytes = (count) => !options.content || (bytes += count) <= 1048576;
3190
+ while (pending.length) {
3191
+ const item = pending.pop();
3192
+ const current = item.value;
3193
+ if ((!item.leave || !options.material) && ++nodes > 8192) return false;
3194
+ if (current === void 0 && item.omitUndefined) continue;
3195
+ if (item.leave) {
3196
+ ancestors.delete(current);
3197
+ continue;
3198
+ }
3199
+ if (current === null || typeof current === "boolean") {
3200
+ if (!addBytes(current === null ? 4 : current ? 4 : 5)) return false;
3201
+ continue;
3202
+ }
3203
+ if (typeof current === "string") {
3204
+ if (options.content ? !addBytes(serializedJsonStringBytes(current)) : current.length > 16384) return false;
3205
+ continue;
3206
+ }
3207
+ if (typeof current === "number") {
3208
+ if (!Number.isFinite(current) || !addBytes(JSON.stringify(current).length)) return false;
3209
+ continue;
3210
+ }
3211
+ if (typeof current !== "object" || item.depth >= 16 || ancestors.has(current)) return false;
3212
+ ancestors.add(current);
3213
+ pending.push({
3214
+ value: current,
3215
+ depth: item.depth,
3216
+ leave: true
3217
+ });
3218
+ const array = Array.isArray(current);
3219
+ if (array && current.length > 1024) return false;
3220
+ const prototype = Object.getPrototypeOf(current);
3221
+ if (!array && prototype !== Object.prototype && prototype !== null || array && options.content && prototype !== Array.prototype && prototype !== null) return false;
3222
+ if (options.content || options.dataPropertiesOnly) {
3223
+ const keys = Reflect.ownKeys(current).filter((key) => !array || key !== "length");
3224
+ if (array ? keys.length !== current.length : keys.length > 256) return false;
3225
+ let entries = 0;
3226
+ for (const key of keys) {
3227
+ if (typeof key !== "string" || !array && key.length > 512) return false;
3228
+ if (array && (!/^(?:0|[1-9][0-9]*)$/u.test(key) || Number(key) >= current.length || Number(key) >= 4294967295)) return false;
3229
+ const descriptor = Object.getOwnPropertyDescriptor(current, key);
3230
+ if (!descriptor?.enumerable || !("value" in descriptor)) return false;
3231
+ if (!array && descriptor.value === void 0 && options.omitUndefinedObjectFields) {
3232
+ if (++nodes > 8192) return false;
3233
+ continue;
3234
+ }
3235
+ if (++entries > (array ? 1024 : 256)) return false;
3236
+ if (!array && !addBytes(serializedJsonStringBytes(key) + 1)) return false;
3237
+ pending.push({
3238
+ value: descriptor.value,
3239
+ depth: item.depth + 1
3240
+ });
3241
+ }
3242
+ if (!addBytes(2 + Math.max(entries - 1, 0))) return false;
3243
+ } else if (array) for (const entry of current) pending.push({
3244
+ value: entry,
3245
+ depth: item.depth + 1
3246
+ });
3247
+ else {
3248
+ const keys = Object.keys(current);
3249
+ if (keys.length > 256) return false;
3250
+ for (const key of keys) {
3251
+ if (key.length > 512) return false;
3252
+ pending.push({
3253
+ value: current[key],
3254
+ depth: item.depth + 1,
3255
+ omitUndefined: options.omitUndefinedObjectFields
3256
+ });
3257
+ }
3258
+ }
3259
+ }
3260
+ return true;
3261
+ }
3262
+ const boundedJsonSchema = z.custom(isBoundedJsonValue, { message: "value exceeds the contract bounds or is not finite JSON" });
3263
+ z.custom((value) => typeof value === "object" && value !== null && !Array.isArray(value) && isBoundedJsonValue(value), { message: "metadata exceeds the contract bounds or is not a JSON object" });
3264
+ z.custom(isBoundedEventContentJson, { message: "event content exceeds its serialized byte bound or is not finite JSON" });
3265
+ z.custom((value) => typeof value === "object" && value !== null && !Array.isArray(value) && isBoundedEventContentJson(value), { message: "event content exceeds its serialized byte bound or is not a JSON object" });
3266
+ z.custom((value) => typeof value === "string" && isBoundedEventContentJson(value), { message: "event content exceeds its serialized byte bound or is not a string" });
3267
+ //#endregion
3110
3268
  //#region ../../../node_modules/.pnpm/@tangle-network+agent-interface@5.10.11/node_modules/@tangle-network/agent-interface/dist/agent-candidate-schema-common.js
3111
3269
  const sha256Pattern = /^sha256:[a-f0-9]{64}$/;
3112
3270
  const gitObjectPattern = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/;
@@ -3116,14 +3274,25 @@ const mediaTypePattern = /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&
3116
3274
  const githubComponentPattern = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/;
3117
3275
  const secretNamePattern = /(?:^|[_-])(?:api[_-]?key|access[_-]?key|private[_-]?key|token|secret|password|credentials?|authorization|cookie|database[_-]?url|dsn|pat)(?:[_-]|$)/i;
3118
3276
  const obviousSecretValuePattern = /(?:\bsk[-_][-_A-Za-z0-9]{10,}\b|\bgh[pousr]_[A-Za-z0-9]{12,}\b|\bgithub_pat_[A-Za-z0-9_]{12,}\b|\bAKIA[A-Z0-9]{12,}\b|-----BEGIN [A-Z ]*PRIVATE KEY-----|\bBearer\s+\S+)/;
3119
- const controlCharacterPattern = /[\u0000-\u001f\u007f]/;
3120
- z.string().regex(sha256Pattern);
3277
+ const controlCharacterPattern$1 = /[\u0000-\u001f\u007f]/;
3278
+ const reservedWorkspaceRoots = new Set([".git", ".sidecar"]);
3279
+ const shellNames = new Set([
3280
+ "sh",
3281
+ "bash",
3282
+ "zsh",
3283
+ "fish",
3284
+ "cmd",
3285
+ "cmd.exe",
3286
+ "powershell",
3287
+ "pwsh"
3288
+ ]);
3289
+ const sha256DigestSchema = z.string().regex(sha256Pattern);
3121
3290
  z.string().regex(gitObjectPattern);
3122
3291
  const environmentNameSchema = z.string().regex(environmentNamePattern);
3123
- z.string().regex(headerNamePattern);
3292
+ const headerNameSchema = z.string().regex(headerNamePattern);
3124
3293
  z.string().regex(mediaTypePattern);
3125
3294
  function sha256Bytes(value) {
3126
- const bytes = sha256(value);
3295
+ const bytes = sha256$1(value);
3127
3296
  return `sha256:${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
3128
3297
  }
3129
3298
  /** RFC 8785 serialization used by every candidate-producing package. */
@@ -3154,6 +3323,35 @@ function isWellFormedUnicode(value) {
3154
3323
  }
3155
3324
  return true;
3156
3325
  }
3326
+ /** Return shared boundary violations for path strings. */
3327
+ function pathSafetyIssues(value) {
3328
+ const issues = [];
3329
+ if (controlCharacterPattern$1.test(value)) issues.push("control-character");
3330
+ if (!isWellFormedUnicode(value)) issues.push("malformed-unicode");
3331
+ return issues;
3332
+ }
3333
+ /** Return shared boundary violations for paths that must stay inside a workspace. */
3334
+ function relativePathSafetyIssues(value) {
3335
+ const issues = [...pathSafetyIssues(value)];
3336
+ if (value.length === 0) issues.push("empty");
3337
+ if (value.startsWith("/") || /^[A-Za-z]:/.test(value)) issues.push("absolute");
3338
+ if (value.includes("\\")) issues.push("backslash");
3339
+ if (value.split("/").includes("..")) issues.push("parent-traversal");
3340
+ return issues;
3341
+ }
3342
+ function isSafeRelativePath(value, allowDot) {
3343
+ if (relativePathSafetyIssues(value).length > 0) return false;
3344
+ if (value === ".") return allowDot;
3345
+ const parts = value.split("/");
3346
+ return parts.every((part) => part.length > 0 && part !== ".") && !parts.some((part) => reservedWorkspaceRoots.has(part));
3347
+ }
3348
+ function isSafeExecutable(value) {
3349
+ if (value.length === 0 || controlCharacterPattern$1.test(value) || !isWellFormedUnicode(value) || /\s/.test(value) || value.includes("\\") || !/^[A-Za-z0-9._+/-]+$/.test(value)) return false;
3350
+ const parts = value.split("/");
3351
+ if (value.startsWith("/")) parts.shift();
3352
+ if (parts.length === 0 || parts.some((part) => part.length === 0 || part === "." || part === "..")) return false;
3353
+ return !shellNames.has(parts.at(-1)?.toLowerCase() ?? "");
3354
+ }
3157
3355
  function isCanonicalJsonValue(value, ancestors = /* @__PURE__ */ new Set()) {
3158
3356
  if (value === null || typeof value === "boolean") return true;
3159
3357
  if (typeof value === "string") return isWellFormedUnicode(value);
@@ -3190,7 +3388,7 @@ function looksLikeCredential(value) {
3190
3388
  return obviousSecretValuePattern.test(value) || hasCredentialBearingUrl(value);
3191
3389
  }
3192
3390
  function isPublicConfigValue(value) {
3193
- return !controlCharacterPattern.test(value) && isWellFormedUnicode(value) && !looksLikeCredential(value);
3391
+ return !controlCharacterPattern$1.test(value) && isWellFormedUnicode(value) && !looksLikeCredential(value);
3194
3392
  }
3195
3393
  /** Shared public reference owner; resolution belongs to the trusted executor. */
3196
3394
  const agentCandidateSecretRefSchema = z.strictObject({
@@ -3219,12 +3417,1386 @@ z.object({
3219
3417
  repo: z.string().regex(githubComponentPattern).refine((value) => value !== "." && value !== "..")
3220
3418
  }).strict();
3221
3419
  //#endregion
3420
+ //#region ../../../node_modules/.pnpm/@tangle-network+agent-interface@5.10.11/node_modules/@tangle-network/agent-interface/dist/agent-profile.js
3421
+ /**
3422
+ * Portable reasoning/thinking effort. Backends map it to their native control at materialization:
3423
+ * codex `model_reasoning_effort`, kimi `--thinking`/`--no-thinking`, claude thinking budget.
3424
+ * Ordered low→high:
3425
+ * - `none` — extended thinking OFF (no reasoning budget at all)
3426
+ * - `minimal` — thinking ON, the lowest budget (distinct from `none`)
3427
+ * - `low` / `medium` / `high` / `xhigh`
3428
+ * - `ultracode` — maximum (Claude Code's `max` and Codex's `ultra` reconcile here).
3429
+ * A backend without a matching native tier may clamp down to its strongest supported level, but it
3430
+ * must never turn reasoning on for `none` or silently increase a requested effort.
3431
+ */
3432
+ const REASONING_EFFORTS = Object.freeze([
3433
+ "none",
3434
+ "minimal",
3435
+ "low",
3436
+ "medium",
3437
+ "high",
3438
+ "xhigh",
3439
+ "ultracode"
3440
+ ]);
3441
+ /** Router namespace reserved for checkpoint-backed models. Receipt-free profiles cannot use it. */
3442
+ const TRAINED_MODEL_PREFIX = "tangle-trained/";
3443
+ /** An immutable Router alias; serving must independently attest this artifact-to-route binding. */
3444
+ function trainedModelIdForArtifact(digest) {
3445
+ return `${TRAINED_MODEL_PREFIX}${digest.slice(7)}`;
3446
+ }
3447
+ //#endregion
3448
+ //#region ../../../node_modules/.pnpm/@tangle-network+agent-interface@5.10.11/node_modules/@tangle-network/agent-interface/dist/profile-knowledge.js
3449
+ /** Immutable Hub generation identities, never aliases such as latest or a caller's scope. */
3450
+ const agentProfileKnowledgeRefSchema = z.strictObject({
3451
+ sourceId: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
3452
+ generation: z.string().regex(/^kg_[a-f0-9]{64}$/)
3453
+ });
3454
+ const agentProfileKnowledgeRefsSchema = z.array(agentProfileKnowledgeRefSchema).max(16).superRefine((refs, context) => {
3455
+ const seen = /* @__PURE__ */ new Set();
3456
+ refs.forEach((ref, index) => {
3457
+ if (seen.has(ref.sourceId)) context.addIssue({
3458
+ code: "custom",
3459
+ path: [index, "sourceId"],
3460
+ message: "A profile must pin exactly one generation per knowledge source"
3461
+ });
3462
+ seen.add(ref.sourceId);
3463
+ });
3464
+ });
3465
+ //#endregion
3466
+ //#region ../../../node_modules/.pnpm/@tangle-network+agent-interface@5.10.11/node_modules/@tangle-network/agent-interface/dist/harness.js
3467
+ /**
3468
+ * Recognized execution identities, not a deployment's list of installed runners.
3469
+ * A profile's authored harness remains part of its canonical identity; execution
3470
+ * receipts record authored identity, effective identity and selected harness
3471
+ * separately. Retiring an executable must not invalidate historical profiles,
3472
+ * sessions or receipts. Availability is admitted against the selected deployment.
3473
+ *
3474
+ * `cli-base` names router-backed execution without a full coding-agent harness.
3475
+ * `prime` is a distinct Pi-line fork. A shared identity does not assert protocol compatibility.
3476
+ */
3477
+ const harnessTypeSchema = z.enum([
3478
+ "claude-code",
3479
+ "nanoclaw",
3480
+ "codex",
3481
+ "opencode",
3482
+ "kimi-code",
3483
+ "pi",
3484
+ "prime",
3485
+ "gemini",
3486
+ "hermes",
3487
+ "openclaw",
3488
+ "amp",
3489
+ "factory-droids",
3490
+ "forge",
3491
+ "cursor",
3492
+ "grok",
3493
+ "acp",
3494
+ "cli-base"
3495
+ ]);
3496
+ //#endregion
3497
+ //#region ../../../node_modules/.pnpm/@tangle-network+agent-interface@5.10.11/node_modules/@tangle-network/agent-interface/dist/agent-profile-canonical.js
3498
+ /** Why a value cannot be AgentProfile JSON, with the path of the offending entry. */
3499
+ var AgentProfileValueError = class extends Error {
3500
+ path;
3501
+ constructor(path, reason) {
3502
+ super(`AgentProfile ${renderPath(path)} ${reason}`);
3503
+ this.path = path;
3504
+ this.name = "AgentProfileValueError";
3505
+ }
3506
+ };
3507
+ /**
3508
+ * Normalize profile-shaped data into the canonical JSON domain used for public
3509
+ * profile identity. Undefined object entries are omitted; unsupported values,
3510
+ * sparse arrays, and cycles are rejected with their profile path.
3511
+ *
3512
+ * This module is intentionally internal. Public callers should use the
3513
+ * profile-level operations that own validation, identity, or diff semantics.
3514
+ */
3515
+ function canonicalAgentProfileValue(value) {
3516
+ return normalizeAgentProfileValue(value, [], /* @__PURE__ */ new Set());
3517
+ }
3518
+ /**
3519
+ * Throw the path-specific reason a value refused by the bounded admission walker is
3520
+ * not profile JSON. Reads no accessor and throws at the contract node and depth
3521
+ * bounds, so hostile input stays cheap; returns only when the refusal was a bound
3522
+ * this walker does not model, such as string or entry length.
3523
+ */
3524
+ function assertAgentProfileValue(value, path) {
3525
+ normalizeAgentProfileValue(value, path, /* @__PURE__ */ new Set(), {
3526
+ nodes: CONTRACT_MAX_JSON_NODES,
3527
+ base: path.length
3528
+ });
3529
+ }
3530
+ /** Canonical serialization after applying AgentProfile normalization rules. */
3531
+ function canonicalAgentProfileJson(value) {
3532
+ const normalized = canonicalAgentProfileValue(value);
3533
+ return normalized === void 0 ? void 0 : canonicalCandidateJson(normalized);
3534
+ }
3535
+ function normalizeAgentProfileValue(value, path, ancestors, bounds) {
3536
+ const refuse = (reason, at = path) => {
3537
+ throw new AgentProfileValueError(at, reason);
3538
+ };
3539
+ if (bounds && --bounds.nodes < 0) refuse("exceeds the contract node bound");
3540
+ if (value === void 0 || value === null || typeof value === "boolean" || typeof value === "string") return value;
3541
+ if (typeof value === "number") return Number.isFinite(value) ? value : refuse("must be finite");
3542
+ if (typeof value !== "object") return refuse("is not JSON serializable");
3543
+ if (ancestors.has(value)) refuse("must be acyclic");
3544
+ const prototype = Object.getPrototypeOf(value);
3545
+ if (!Array.isArray(value) && prototype !== Object.prototype && prototype !== null) refuse("must be a plain JSON object");
3546
+ if (bounds && path.length - bounds.base >= 16) refuse("exceeds the contract depth");
3547
+ const nextAncestors = new Set(ancestors).add(value);
3548
+ const entry = (key) => {
3549
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
3550
+ if (!descriptor) return refuse("cannot be a sparse array hole", [...path, key]);
3551
+ if (!("value" in descriptor)) return refuse("must be a data property", [...path, key]);
3552
+ const normalized = normalizeAgentProfileValue(descriptor.value, [...path, key], nextAncestors, bounds);
3553
+ return normalized === void 0 && typeof key === "number" ? refuse("cannot be undefined", [...path, key]) : normalized;
3554
+ };
3555
+ if (Array.isArray(value)) return Array.from({ length: value.length }, (_, index) => entry(index));
3556
+ const material = Object.create(null);
3557
+ for (const key of Object.keys(value)) {
3558
+ if (!isWellFormedUnicode(key)) refuse("has a record key that is not valid Unicode");
3559
+ const normalized = entry(key);
3560
+ if (normalized !== void 0) Object.defineProperty(material, key, {
3561
+ value: normalized,
3562
+ enumerable: true,
3563
+ configurable: true,
3564
+ writable: true
3565
+ });
3566
+ }
3567
+ return material;
3568
+ }
3569
+ function renderPath(path) {
3570
+ return path.length === 0 ? "root" : path.join(".");
3571
+ }
3572
+ //#endregion
3573
+ //#region ../../../node_modules/.pnpm/@tangle-network+agent-interface@5.10.11/node_modules/@tangle-network/agent-interface/dist/own-property-record.js
3574
+ /**
3575
+ * Zod records currently assign parsed values onto an ordinary object. The
3576
+ * special own key `__proto__` therefore invokes the legacy prototype setter
3577
+ * and disappears instead of being validated. Encode every own key before Zod
3578
+ * sees it, then restore the exact UTF-16 key with defineProperty so all string
3579
+ * keys allowed by `Record<string, ...>` remain data rather than object syntax.
3580
+ */
3581
+ function ownPropertyRecordSchema(valueSchema, { maxEntries = 256, prepareValue } = {}) {
3582
+ return z.preprocess((value, context) => {
3583
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return value;
3584
+ const prototype = Object.getPrototypeOf(value);
3585
+ if (prototype !== Object.prototype && prototype !== null) return [];
3586
+ let entries = 0;
3587
+ for (const key in value) {
3588
+ if (!Object.hasOwn(value, key)) continue;
3589
+ if (++entries > maxEntries || key.length > 512) {
3590
+ context.addIssue({
3591
+ code: "custom",
3592
+ message: "record exceeds the contract bounds"
3593
+ });
3594
+ return z.NEVER;
3595
+ }
3596
+ }
3597
+ const encoded = Object.create(null);
3598
+ for (const key of Object.keys(value)) {
3599
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
3600
+ if (!descriptor || !("value" in descriptor)) {
3601
+ context.addIssue({
3602
+ code: "custom",
3603
+ message: "record entries must be data properties"
3604
+ });
3605
+ return z.NEVER;
3606
+ }
3607
+ let entry;
3608
+ try {
3609
+ entry = prepareValue ? prepareValue(key, descriptor.value) : descriptor.value;
3610
+ } catch (error) {
3611
+ if (!(error instanceof AgentProfileValueError)) throw error;
3612
+ context.addIssue({
3613
+ code: "custom",
3614
+ path: [...error.path],
3615
+ message: error.message
3616
+ });
3617
+ return z.NEVER;
3618
+ }
3619
+ if (entry === z.NEVER) {
3620
+ context.addIssue({
3621
+ code: "custom",
3622
+ message: "record value exceeds the contract bounds or is not portable JSON"
3623
+ });
3624
+ return z.NEVER;
3625
+ }
3626
+ encoded[encodeRecordKey(key)] = entry;
3627
+ }
3628
+ return encoded;
3629
+ }, z.record(z.string().regex(/^u(?:[0-9a-f]{4})*$/, "record keys must contain valid Unicode"), valueSchema).superRefine((_record, context) => {
3630
+ for (const issue of context.issues) {
3631
+ const key = issue.path?.[0];
3632
+ if (typeof key === "string" && /^[ui](?:[0-9a-f]{4})*$/.test(key)) issue.path[0] = decodeRecordKey(key);
3633
+ }
3634
+ }, { when: () => true }).transform((record) => {
3635
+ const restored = {};
3636
+ for (const [encodedKey, value] of Object.entries(record)) Object.defineProperty(restored, decodeRecordKey(encodedKey), {
3637
+ value,
3638
+ enumerable: true,
3639
+ configurable: true,
3640
+ writable: true
3641
+ });
3642
+ return restored;
3643
+ }));
3644
+ }
3645
+ function encodeRecordKey(value) {
3646
+ let encoded = isWellFormedUnicode(value) ? "u" : "i";
3647
+ for (let index = 0; index < value.length; index += 1) encoded += value.charCodeAt(index).toString(16).padStart(4, "0");
3648
+ return encoded;
3649
+ }
3650
+ function decodeRecordKey(value) {
3651
+ let decoded = "";
3652
+ for (let index = 1; index < value.length; index += 4) decoded += String.fromCharCode(Number.parseInt(value.slice(index, index + 4), 16));
3653
+ return decoded;
3654
+ }
3655
+ //#endregion
3656
+ //#region ../../../node_modules/.pnpm/@tangle-network+agent-interface@5.10.11/node_modules/@tangle-network/agent-interface/dist/proxy-secrets.js
3657
+ /**
3658
+ * Declarations request authority. The issuer intersects scope/expiry with authenticated tenant,
3659
+ * issuer policy and lineage, without personal/team fallback, pinning immutable secret ID/revision.
3660
+ * Trusted lifecycle owners mint unpredictable per-epoch placeholders, never from secret/public
3661
+ * refs. JWT claims are synthetic public sub/aud/exp, without upstream identity or authority.
3662
+ * The sandbox is the isolation boundary; schemas cannot authenticate guest processes.
3663
+ */
3664
+ const unique = (values) => new Set(values).size === values.length;
3665
+ const hostSchema = z.string().max(253).regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/, "host must be an exact lowercase FQDN without scheme, port, wildcard or trailing dot");
3666
+ const methodSchema = z.string().max(32).regex(/^[A-Z]+$/);
3667
+ /** Paths are exact or terminal slash-star subtrees. /v1/* includes /v1/ and /v1/a, never /v1
3668
+ * or /v10. V1 rejects all percent encoding, dot segments, repeated slashes, query, fragments,
3669
+ * semicolons, backslashes, non-ASCII and controls, rather than normalizing ambiguous spellings.
3670
+ */
3671
+ const pathSchema = z.string().max(2048).refine((path) => {
3672
+ const exact = path.endsWith("/*") ? path.slice(0, -1) : path;
3673
+ return /^\/[A-Za-z0-9._~!$&'()+,=:@/-]*$/.test(exact) && !exact.includes("//") && !exact.split("/").some((part) => part === "." || part === "..");
3674
+ }, "path must be canonical ASCII, exact or a terminal /* subtree");
3675
+ const list = (schema) => z.array(schema).min(1).max(CONTRACT_MAX_ARRAY_LENGTH).refine(unique, "selectors must be unique");
3676
+ const envNameSchema = z.string().max(256).regex(/^[A-Za-z_][A-Za-z0-9_]*$/);
3677
+ const headerSchema = z.string().max(256).regex(/^[!#$%&'*+.^_\x60|~0-9A-Za-z-]+$/).refine((name) => ![
3678
+ "authorization",
3679
+ "proxy-authorization",
3680
+ "proxy-authenticate",
3681
+ "host",
3682
+ "connection",
3683
+ "keep-alive",
3684
+ "proxy-connection",
3685
+ "content-length",
3686
+ "transfer-encoding",
3687
+ "trailer",
3688
+ "upgrade",
3689
+ "te"
3690
+ ].includes(name.toLowerCase()), "use bearer/basic for Authorization; routing and framing headers cannot carry secrets");
3691
+ /** Match complete components only. Selected header names are case-insensitive; duplicate fields
3692
+ * are refused before coalescing. Query names are case-sensitive after one strict UTF-8 percent
3693
+ * decode (+ means space); malformed encoding and duplicate decoded selector names are refused.
3694
+ * Never scan other query fields. Basic is one strict base64 value decoding to exactly public
3695
+ * username:placeholder; the username is printable ASCII without colon. Bearer is exactly
3696
+ * "Bearer SP placeholder". Embedded placeholders never match. Authority, TLS SNI and validated
3697
+ * destination must agree on the declared FQDN and effective port over HTTPS.
3698
+ */
3699
+ const ProxySecretPresentationSchema = z.discriminatedUnion("type", [
3700
+ z.strictObject({ type: z.literal("bearer") }),
3701
+ z.strictObject({
3702
+ type: z.literal("basic"),
3703
+ username: z.string().min(1).max(256).regex(/^[\x21-\x39\x3b-\x7e]+$/)
3704
+ }),
3705
+ z.strictObject({
3706
+ type: z.literal("header"),
3707
+ name: headerSchema
3708
+ }),
3709
+ z.strictObject({
3710
+ type: z.literal("query"),
3711
+ name: z.string().max(256).regex(/^[A-Za-z0-9._~-]+$/)
3712
+ })
3713
+ ]);
3714
+ const ProxySecretScopeSchema = z.strictObject({
3715
+ hosts: list(hostSchema).readonly(),
3716
+ methods: list(methodSchema).readonly().optional(),
3717
+ paths: list(pathSchema).readonly().optional()
3718
+ });
3719
+ ProxySecretScopeSchema.strip();
3720
+ const ProxySecretBindingSchema = ProxySecretScopeSchema.extend({
3721
+ envName: envNameSchema,
3722
+ secretRef: agentCandidateSecretRefSchema.omit({ format: true }),
3723
+ presentation: ProxySecretPresentationSchema,
3724
+ placeholderFormat: z.enum(["opaque", "jwt"]).optional(),
3725
+ ttlSeconds: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional()
3726
+ });
3727
+ const ProxySecretsSchema = z.array(ProxySecretBindingSchema).max(CONTRACT_MAX_ARRAY_LENGTH).refine((bindings) => unique(bindings.map((binding) => binding.envName)), "proxy secret env names must be unique");
3728
+ ownPropertyRecordSchema(boundedIdentifierSchema.nullable(), { maxEntries: CONTRACT_MAX_ARRAY_LENGTH }).refine((parents) => Object.keys(parents).every((name) => envNameSchema.safeParse(name).success), "invalid parent selection keys");
3729
+ z.literal(1);
3730
+ const ProxySecretResolvedIdentitySchema = z.strictObject({
3731
+ tenantId: boundedIdentifierSchema,
3732
+ issuerId: boundedIdentifierSchema,
3733
+ secretId: boundedIdentifierSchema,
3734
+ revision: boundedIdentifierSchema
3735
+ });
3736
+ const timestamp = z.iso.datetime();
3737
+ const ProxySecretGrantSchema = z.strictObject({
3738
+ protocolVersion: z.literal(1),
3739
+ grantId: boundedIdentifierSchema,
3740
+ sandboxId: boundedIdentifierSchema,
3741
+ epoch: boundedIdentifierSchema,
3742
+ identity: ProxySecretResolvedIdentitySchema,
3743
+ scope: ProxySecretScopeSchema,
3744
+ presentation: ProxySecretPresentationSchema,
3745
+ placeholderFormat: z.enum(["opaque", "jwt"]),
3746
+ issuedAt: timestamp,
3747
+ expiresAt: timestamp,
3748
+ sourceExpiresAt: timestamp.optional(),
3749
+ parentGrantId: boundedIdentifierSchema.optional()
3750
+ }).refine((grant) => grant.parentGrantId !== grant.grantId && Date.parse(grant.expiresAt) > Date.parse(grant.issuedAt) && (grant.sourceExpiresAt === void 0 || Date.parse(grant.expiresAt) <= Date.parse(grant.sourceExpiresAt)), "grant expiry must follow issuance");
3751
+ const receiptShape = {
3752
+ protocolVersion: z.literal(1),
3753
+ sandboxId: boundedIdentifierSchema,
3754
+ generation: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
3755
+ bindings: z.array(z.strictObject({
3756
+ envName: envNameSchema,
3757
+ secretRef: agentCandidateSecretRefSchema.omit({ format: true }),
3758
+ grant: ProxySecretGrantSchema
3759
+ })).max(CONTRACT_MAX_ARRAY_LENGTH),
3760
+ proxyAcknowledged: z.literal(true)
3761
+ };
3762
+ z.discriminatedUnion("status", [
3763
+ z.strictObject({
3764
+ ...receiptShape,
3765
+ status: z.literal("proxy-installed"),
3766
+ materializationAcknowledged: z.literal(false)
3767
+ }),
3768
+ z.strictObject({
3769
+ ...receiptShape,
3770
+ status: z.literal("installed"),
3771
+ materializationAcknowledged: z.literal(true)
3772
+ }),
3773
+ z.strictObject({
3774
+ ...receiptShape,
3775
+ status: z.literal("revoked"),
3776
+ materializationAcknowledged: z.literal(true)
3777
+ })
3778
+ ]).superRefine((receipt, ctx) => {
3779
+ if (!unique(receipt.bindings.map((binding) => binding.envName)) || !unique(receipt.bindings.map((binding) => binding.grant.grantId))) ctx.addIssue({
3780
+ code: "custom",
3781
+ path: ["bindings"],
3782
+ message: "receipt binding names and grant IDs must be unique"
3783
+ });
3784
+ if (receipt.bindings.some((binding) => binding.grant.sandboxId !== receipt.sandboxId)) ctx.addIssue({
3785
+ code: "custom",
3786
+ path: ["bindings"],
3787
+ message: "receipt grants must belong to its sandbox"
3788
+ });
3789
+ if (new Set(receipt.bindings.map((binding) => binding.grant.epoch)).size > 1) ctx.addIssue({
3790
+ code: "custom",
3791
+ path: ["bindings"],
3792
+ message: "receipt grants must share one sandbox lifecycle epoch"
3793
+ });
3794
+ if (receipt.status === "revoked" && receipt.bindings.length !== 0) ctx.addIssue({
3795
+ code: "custom",
3796
+ path: ["bindings"],
3797
+ message: "revoked receipt cannot retain bindings"
3798
+ });
3799
+ });
3800
+ z.strictObject({
3801
+ protocolVersion: z.literal(1),
3802
+ supportedDrivers: list(boundedIdentifierSchema),
3803
+ presentations: list(z.enum([
3804
+ "bearer",
3805
+ "basic",
3806
+ "header",
3807
+ "query"
3808
+ ])),
3809
+ placeholderFormats: list(z.enum(["opaque", "jwt"])),
3810
+ enforcement: z.literal("exact"),
3811
+ transports: z.tuple([z.enum(["https:443", "https"])]),
3812
+ lifecycle: z.literal(true),
3813
+ placementReceiptRequired: z.literal(true)
3814
+ });
3815
+ z.strictObject({
3816
+ expectedProxySecretGeneration: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(),
3817
+ requireInPlace: z.boolean().optional()
3818
+ });
3819
+ //#endregion
3820
+ //#region ../../../node_modules/.pnpm/@tangle-network+agent-interface@5.10.11/node_modules/@tangle-network/agent-interface/dist/harness-capabilities.js
3821
+ /** Canonical harness/model, effort and prompt controls. Model-specific capability comes from the serving catalog. */
3822
+ /** low → high. `none` = thinking off; `ultracode` = max (claude-code mode). */
3823
+ const reasoningLadder = REASONING_EFFORTS;
3824
+ /**
3825
+ * Vendor locks, before the measured {@link harnessModelExclusions}. Absent means router-backed.
3826
+ * Claude Code and Codex run any Router model: their native vendor wire passes through for vendor
3827
+ * models and translates others to chat completions (including images/tools; hosted tools drop).
3828
+ * A caller's vendor key/login remains vendor-limited; this table does not know credentials.
3829
+ * NanoClaw also routes every provider through the Router, so it has no Anthropic lock.
3830
+ * {@link vendorHarness} chooses a default harness; it is not a provider restriction.
3831
+ */
3832
+ const harnessProviderLock = { "kimi-code": ["moonshot"] };
3833
+ /** Provider prefix of a canonical model id (`anthropic/claude-…` → `anthropic`), or null. */
3834
+ function modelProvider(modelId) {
3835
+ const slash = modelId.indexOf("/");
3836
+ return slash > 0 ? modelId.slice(0, slash) : null;
3837
+ }
3838
+ /**
3839
+ * Model families whose bare ids belong to one provider. The Router catalog serves most ids without a
3840
+ * prefix (`claude-sonnet-5-5`, `gpt-5.5`, `glm-5.3`) and names the provider beside them, so a check
3841
+ * that read every bare id as "any provider" offered `claude-code` with `glm-5.3`.
3842
+ */
3843
+ const bareModelFamilyProviders = [
3844
+ [/^claude-/, "anthropic"],
3845
+ [/^(gpt-|chatgpt-|codex-|o\d+(-|$))/, "openai"],
3846
+ [/^(kimi-|moonshot-)/, "moonshot"],
3847
+ [/^gemini-/, "google"],
3848
+ [/^glm-/, "zai"],
3849
+ [/^deepseek-/, "deepseek"],
3850
+ [/^grok-/, "xai"]
3851
+ ];
3852
+ /**
3853
+ * The provider a model id belongs to: its explicit prefix, else the provider of its bare-id family
3854
+ * (`claude-sonnet-5-5` → `anthropic`). `null` for an id outside every family, such as the `default`
3855
+ * sentinel, whose provider only the serving harness knows.
3856
+ */
3857
+ function resolveModelProvider(modelId) {
3858
+ const explicit = modelProvider(modelId);
3859
+ if (explicit) return explicit;
3860
+ const id = modelId.trim().toLowerCase();
3861
+ for (const [family, provider] of bareModelFamilyProviders) if (family.test(id)) return provider;
3862
+ return null;
3863
+ }
3864
+ /** The providers a harness is locked to, or `null` when it is router-backed (any model). */
3865
+ function harnessProviders(harness) {
3866
+ return harnessProviderLock[harness] ?? null;
3867
+ }
3868
+ const SANDBOX_HARNESS_MATRIX_EVIDENCE = "https://github.com/tangle-network/agent-container/issues/9382";
3869
+ /**
3870
+ * Pairs a router-backed harness cannot run, measured on production with the Router credential: one
3871
+ * prompt per pair, profile reasoning effort `medium` (2026-10-05). The same run passed pi with
3872
+ * `openai/gpt-5.5` and `zai/glm-5.3`, and opencode with every model listed here. Pairs not listed
3873
+ * were not measured to fail. An entry is removed when its harness adapter or the Router is fixed and
3874
+ * the pair passes a new production measurement.
3875
+ *
3876
+ * pi's chat-completions client (pi-ai 0.85.1) marks a model as reasoning only when the profile asks
3877
+ * for a reasoning effort, and only a reasoning model is sent the `developer` role and
3878
+ * `reasoning_effort`; that is why the first two entries need a reasoning effort.
3879
+ */
3880
+ const harnessModelExclusions = [
3881
+ {
3882
+ harness: "pi",
3883
+ models: /^anthropic\//,
3884
+ onlyWithReasoningEffort: true,
3885
+ reason: "the Router's chat-completions route for Anthropic models rejects the \"developer\" role pi sends to a reasoning model (400 Unexpected role \"developer\")",
3886
+ measuredOn: "2026-10-05",
3887
+ evidence: SANDBOX_HARNESS_MATRIX_EVIDENCE
3888
+ },
3889
+ {
3890
+ harness: "pi",
3891
+ models: /^openai\/gpt-5\.6-luna$/,
3892
+ onlyWithReasoningEffort: true,
3893
+ reason: "OpenAI does not accept function tools together with reasoning_effort for this model on /v1/chat/completions, the only route pi speaks",
3894
+ measuredOn: "2026-10-05",
3895
+ evidence: SANDBOX_HARNESS_MATRIX_EVIDENCE
3896
+ },
3897
+ {
3898
+ harness: "pi",
3899
+ models: /^google\/gemini-3\.8-flash$/,
3900
+ onlyWithReasoningEffort: false,
3901
+ reason: "the model requires each function call to return its thought_signature, which pi's chat-completions client does not send back (400 Function call is missing a thought_signature)",
3902
+ measuredOn: "2026-10-05",
3903
+ evidence: SANDBOX_HARNESS_MATRIX_EVIDENCE
3904
+ }
3905
+ ];
3906
+ /**
3907
+ * Whether a harness can run a model, and why not. A bare id resolves its provider through
3908
+ * {@link resolveModelProvider}; an id whose provider cannot be resolved (a sentinel like `default`)
3909
+ * is left to the harness, because its provider only the serving harness knows. A vendor-locked
3910
+ * harness refuses every other provider; a router-backed harness refuses only the measured
3911
+ * {@link harnessModelExclusions}.
3912
+ */
3913
+ function harnessModelSupport(harness, modelId, options = {}) {
3914
+ const trimmed = modelId.trim();
3915
+ const provider = resolveModelProvider(trimmed);
3916
+ const model = provider !== null && modelProvider(trimmed) === null ? `${provider}/${trimmed}` : trimmed;
3917
+ if (provider === null) return {
3918
+ supported: true,
3919
+ model,
3920
+ provider
3921
+ };
3922
+ const allowedProviders = harnessProviders(harness);
3923
+ if (allowedProviders && !allowedProviders.includes(provider)) return {
3924
+ supported: false,
3925
+ model,
3926
+ provider,
3927
+ allowedProviders,
3928
+ message: `Harness ${harness} runs only ${allowedProviders.join(" or ")} models, not ${model} (provider ${provider}). Choose a model whose id starts with ${allowedProviders.map((p) => `${p}/`).join(" or ")}, or a harness that runs ${provider} models, such as opencode.`
3929
+ };
3930
+ const reasoning = options.reasoningEffort !== void 0 && options.reasoningEffort !== null && options.reasoningEffort !== "none";
3931
+ const exclusion = harnessModelExclusions.find((entry) => entry.harness === harness && entry.models.test(model) && (!entry.onlyWithReasoningEffort || reasoning));
3932
+ if (exclusion) return {
3933
+ supported: false,
3934
+ model,
3935
+ provider,
3936
+ exclusion,
3937
+ message: `Harness ${harness} cannot run ${model}` + (exclusion.onlyWithReasoningEffort ? " with a reasoning effort" : "") + `: ${exclusion.reason} (measured ${exclusion.measuredOn}, ${exclusion.evidence}). ` + (exclusion.onlyWithReasoningEffort ? "Remove model.reasoningEffort, or choose another harness or model." : "Choose another harness or model.")
3938
+ };
3939
+ return {
3940
+ supported: true,
3941
+ model,
3942
+ provider
3943
+ };
3944
+ }
3945
+ new Intl.Collator(void 0, {
3946
+ numeric: true,
3947
+ sensitivity: "base"
3948
+ });
3949
+ /**
3950
+ * The explicit reasoning-effort set a harness's runtime accepts when it ISN'T a plain `none…ceiling`
3951
+ * slice — measured against the pinned CLI binaries, NOT inferred from the canonical ladder:
3952
+ * - codex: `model_reasoning_effort` accepts `none|minimal|low|medium|high|xhigh|max`, plus `ultra`
3953
+ * which the API's own enumeration omits but accepts end-to-end; canonical `ultracode` maps to
3954
+ * native `ultra`. Per-model catalog data narrows this list.
3955
+ * - claude-code: `--effort` accepts `low|medium|high|xhigh|max`; canonical `ultracode` maps to
3956
+ * native `max`. It cannot express `none` or `minimal`, and an unsupported value is warned about
3957
+ * and silently replaced with the default rather than rejected — so the set must not overstate.
3958
+ * - pi: `--thinking` accepts `off|minimal|low|medium|high|xhigh|max` (pi 1.4.0
3959
+ * `cli/args.js`); canonical `none` maps to `off` and `ultracode` to `max`.
3960
+ * - prime: the prime fork of the pi line accepts the same `--thinking` set
3961
+ * (`off|minimal|low|medium|high|xhigh|max`); canonical `none` maps to `off` and `ultracode` to
3962
+ * `max`.
3963
+ * - openclaw: `--thinking` accepts `off|minimal|low|medium|high|xhigh|max` (and `adaptive`, which
3964
+ * defers the choice rather than naming a rung); canonical `none` maps to `off` and `ultracode`
3965
+ * to `max`.
3966
+ * - kimi-code: `--thinking` is binary. Canonical `none` emits `--no-thinking`; any non-none level
3967
+ * emits `--thinking`, represented here by `high`.
3968
+ */
3969
+ const harnessReasoningEffortsOverride = {
3970
+ "claude-code": [
3971
+ "low",
3972
+ "medium",
3973
+ "high",
3974
+ "xhigh",
3975
+ "ultracode"
3976
+ ],
3977
+ "kimi-code": ["none", "high"]
3978
+ };
3979
+ /**
3980
+ * The ceiling for harnesses whose set IS a plain `none…ceiling` slice. Only the no-thinking runners
3981
+ * need an entry (`cli-base` has no agent; `nanoclaw` sends no thinking flag). Harnesses with a
3982
+ * provider-clamped or non-contiguous set live in {@link harnessReasoningEffortsOverride}; router /
3983
+ * model-driven harnesses (opencode, gemini, …) have no entry → default to the full ladder, narrowed
3984
+ * by the model's own capability.
3985
+ */
3986
+ const harnessReasoningCeiling = {
3987
+ "cli-base": "none",
3988
+ nanoclaw: "none"
3989
+ };
3990
+ /** The reasoning efforts a harness can express, independent of model — its explicit override set, or
3991
+ * `none` up to its ceiling (default `ultracode` for router/model-driven harnesses). */
3992
+ function harnessReasoningEfforts(harness) {
3993
+ const override = harnessReasoningEffortsOverride[harness];
3994
+ if (override) return override;
3995
+ const ceiling = harnessReasoningCeiling[harness] ?? "ultracode";
3996
+ return reasoningLadder.slice(0, reasoningLadder.indexOf(ceiling) + 1);
3997
+ }
3998
+ /**
3999
+ * Harnesses whose runner DROPS a per-turn selector — grounded in the cli-bridge adapter audit, NOT a
4000
+ * guess. Most harnesses honor both selectors, so only the exceptions are listed; a harness absent from
4001
+ * a set honors that selector.
4002
+ *
4003
+ * - model dropped: `amp` (own agent picks the model), `openclaw` (dispatcher routes by its own
4004
+ * config), `nanoclaw` (socket-bridge runner is config/env-driven).
4005
+ * - effort dropped: `amp`, `factory-droids`, `hermes`, `nanoclaw`, and `acp` (no thinking flag is
4006
+ * plumbed to the underlying CLI — the runner reads no `reasoningEffort`).
4007
+ *
4008
+ * This is distinct from {@link reasoningEffortsFor} (which levels a harness can EXPRESS): a picker uses
4009
+ * these to trim or mark harnesses up front, so a user's model/effort choice is never silently ignored.
4010
+ */
4011
+ const harnessIgnoresModel = new Set([
4012
+ "amp",
4013
+ "openclaw",
4014
+ "nanoclaw"
4015
+ ]);
4016
+ const harnessIgnoresEffort = new Set([
4017
+ "amp",
4018
+ "factory-droids",
4019
+ "hermes",
4020
+ "nanoclaw",
4021
+ "acp"
4022
+ ]);
4023
+ /** Whether the harness's runner honors a per-turn MODEL override (vs. picking the model itself). */
4024
+ function harnessHonorsModel(harness) {
4025
+ return !harnessIgnoresModel.has(harness);
4026
+ }
4027
+ /** Whether the harness's runner honors a reasoning-EFFORT override (vs. dropping it). */
4028
+ function harnessHonorsEffort(harness) {
4029
+ return !harnessIgnoresEffort.has(harness);
4030
+ }
4031
+ /**
4032
+ * The system-prompt intents a harness's own controls can execute, measured by reading the request
4033
+ * each installed CLI sends — NOT taken from its help text:
4034
+ *
4035
+ * - claude-code 2.1.222 and pi 0.83.0 own both. `--system-prompt` drops the built-in prompt from
4036
+ * the request (27,673 B → the caller's bytes on claude-code, 2,582 B → the caller's on pi);
4037
+ * `--append-system-prompt` leaves it in place and adds the caller's text after it.
4038
+ * - codex 0.146.0 owns replacement only: the `model_instructions_file` config key becomes the
4039
+ * request's entire instructions text. It has no additive control — its AGENTS.md lands in a
4040
+ * developer/user message, not the system channel.
4041
+ * - gemini 0.26.0 owns replacement only: `.gemini/system.md` under `GEMINI_SYSTEM_MD=1` replaces
4042
+ * the base prompt. Its one additive path is GEMINI.md memory, which IS the `instructions`
4043
+ * surface, so an addition lowered there would be byte-indistinguishable from `instructions`.
4044
+ * - opencode 1.17.18 owns addition only THROUGH A WORKSPACE: config-declared `instructions[]`
4045
+ * files compose into the same single `role: "system"` message as its built-in prompt, which
4046
+ * stays in place. Its replacement control (`agent.<name>.prompt`) binds to one agent chosen at
4047
+ * launch, which a workspace plan cannot guarantee — but an executor that selects that agent
4048
+ * can, so `replace: false` here is the plan-forwarding answer, not opencode's ceiling.
4049
+ *
4050
+ * Every other harness owns NEITHER, including the ones whose prompt path is a `role: "system"` chat
4051
+ * message: that message is flattened into the user turn before the CLI sees it, so it is not a
4052
+ * system-prompt channel at all — honoring an intent through it would put the caller's text in
4053
+ * ordinary user content while the harness's own prompt ran unchanged. A harness with no entry
4054
+ * refuses both, so one added later cannot inherit a capability by omission.
4055
+ */
4056
+ const harnessSystemPromptControls = {
4057
+ "claude-code": {
4058
+ replace: true,
4059
+ append: true
4060
+ },
4061
+ pi: {
4062
+ replace: true,
4063
+ append: true
4064
+ },
4065
+ prime: {
4066
+ replace: true,
4067
+ append: true
4068
+ },
4069
+ codex: {
4070
+ replace: true,
4071
+ append: false
4072
+ },
4073
+ gemini: {
4074
+ replace: true,
4075
+ append: false
4076
+ },
4077
+ opencode: {
4078
+ replace: false,
4079
+ append: true
4080
+ }
4081
+ };
4082
+ const noSystemPromptControls = {
4083
+ replace: false,
4084
+ append: false
4085
+ };
4086
+ /**
4087
+ * Which system-prompt intents a harness honors THROUGH A WORKSPACE — the value an adapter that
4088
+ * lowers a profile to files, env vars, and CLI flags and then hands the result to a launcher it
4089
+ * does not own should declare as {@link AgentProfileCapabilities.systemPrompt}. That is the shape
4090
+ * of every caller today (the cli-bridge and tangle providers both forward a plan), which is why
4091
+ * this answer depends on the harness alone.
4092
+ *
4093
+ * It is NOT the whole truth for an adapter that starts the harness itself, because one control in
4094
+ * the table above lives outside any workspace: opencode's `agent.<name>.prompt` really does replace
4095
+ * its built-in prompt, but it binds to the single agent whoever starts the server selects. A plan
4096
+ * cannot name that agent, so `opencode` reads `replace: false` here — while an adapter that writes
4097
+ * opencode's server config AND picks the primary agent (`sdk-provider-opencode`) does honor
4098
+ * replacement, and declares `replace: true` for itself. The capability is a property of the
4099
+ * (harness, executor) pair; this function answers it for the plan-forwarding executor.
4100
+ *
4101
+ * Do not widen the table to close that gap: a harness-keyed `true` would promise the intent to
4102
+ * every plan-forwarding caller, and those callers cannot deliver it. An executor that owns a
4103
+ * launcher control states so where it binds it — `materializeProfile`'s `binds` option in
4104
+ * `@tangle-network/agent-profile-materialize`, which turns the plan's refusal into a binding that
4105
+ * executor must then apply.
4106
+ *
4107
+ * Pass `undefined` when the harness is not known at declaration time: the answer is then
4108
+ * `{ replace: false, append: false }`, because an adapter that cannot name its harness cannot
4109
+ * promise either intent, and `false` means "refuse" rather than "silently substitute the other".
4110
+ * An adapter that forwards a profile to some other layer must still declare what that layer's
4111
+ * harness really does — being able to put the field on the wire is not the same as honoring it.
4112
+ */
4113
+ function harnessSystemPromptIntents(harness) {
4114
+ if (!harness) return noSystemPromptControls;
4115
+ return harnessSystemPromptControls[harness] ?? noSystemPromptControls;
4116
+ }
4117
+ //#endregion
4118
+ //#region ../../../node_modules/.pnpm/@tangle-network+agent-interface@5.10.11/node_modules/@tangle-network/agent-interface/dist/sandbox-size.js
4119
+ /**
4120
+ * Portable sandbox size vocabulary.
4121
+ *
4122
+ * A size preset is a provider-neutral NAME for a compute tier (cpu / memory /
4123
+ * disk). This module owns only the vocabulary — the names and their smallest→
4124
+ * largest ordering — so the lowest shared layer can reference a size without
4125
+ * depending on the sandbox SDK (`Capability.recommendedSize` lives here, and
4126
+ * agent-interface must not depend on `@tangle-network/sandbox`).
4127
+ *
4128
+ * The concrete cpu/memory/disk numbers for each preset are the sandbox SDK's
4129
+ * single source of truth (`@tangle-network/sandbox` → `SANDBOX_SIZE_PRESETS`),
4130
+ * which imports these names. Mirrors how this package owns the `ReasoningEffort`
4131
+ * vocabulary while backends own its native mapping.
4132
+ */
4133
+ /** Compute tiers, ordered smallest → largest. */
4134
+ const SANDBOX_SIZE_PRESET_NAMES = [
4135
+ "nano",
4136
+ "small",
4137
+ "medium",
4138
+ "large"
4139
+ ];
4140
+ //#endregion
4141
+ //#region ../../../node_modules/.pnpm/@tangle-network+agent-interface@5.10.11/node_modules/@tangle-network/agent-interface/dist/profile-schema.js
4142
+ const profileOpaqueValueSchema = z.unknown().transform((value, context) => {
4143
+ if (value === void 0 || isBoundedJsonMaterial(value, {
4144
+ dataPropertiesOnly: true,
4145
+ content: true
4146
+ })) return structuredClone(value);
4147
+ try {
4148
+ assertAgentProfileValue(value, []);
4149
+ } catch (error) {
4150
+ if (!(error instanceof AgentProfileValueError)) throw error;
4151
+ context.addIssue({
4152
+ code: "custom",
4153
+ path: [...error.path],
4154
+ message: error.message
4155
+ });
4156
+ return z.NEVER;
4157
+ }
4158
+ context.addIssue({
4159
+ code: "custom",
4160
+ message: "profile metadata exceeds contract bounds or is not portable JSON"
4161
+ });
4162
+ return z.NEVER;
4163
+ });
4164
+ const agentProfilePermissionValueSchema = z.enum([
4165
+ "allow",
4166
+ "deny",
4167
+ "ask"
4168
+ ]);
4169
+ const agentProfilePermissionSchema = z.union([agentProfilePermissionValueSchema, ownPropertyRecordSchema(agentProfilePermissionValueSchema)]);
4170
+ const agentProfileResourceRefSchema = z.union([z.strictObject({
4171
+ kind: z.literal("inline"),
4172
+ name: z.string(),
4173
+ content: z.string()
4174
+ }), z.strictObject({
4175
+ kind: z.literal("github"),
4176
+ repository: z.string().optional(),
4177
+ path: z.string(),
4178
+ ref: z.string().optional(),
4179
+ name: z.string().optional()
4180
+ })]);
4181
+ const agentProfileFileMountSchema = z.strictObject({
4182
+ path: z.string(),
4183
+ resource: agentProfileResourceRefSchema,
4184
+ executable: z.boolean().optional()
4185
+ });
4186
+ const agentProfileResourcesSchema = z.strictObject({
4187
+ knowledge: agentProfileKnowledgeRefsSchema.optional(),
4188
+ files: z.array(agentProfileFileMountSchema).max(CONTRACT_MAX_ARRAY_LENGTH).optional(),
4189
+ tools: z.array(agentProfileResourceRefSchema).max(CONTRACT_MAX_ARRAY_LENGTH).optional(),
4190
+ skills: z.array(agentProfileResourceRefSchema).max(CONTRACT_MAX_ARRAY_LENGTH).optional(),
4191
+ agents: z.array(agentProfileResourceRefSchema).max(CONTRACT_MAX_ARRAY_LENGTH).optional(),
4192
+ commands: z.array(agentProfileResourceRefSchema).max(CONTRACT_MAX_ARRAY_LENGTH).optional(),
4193
+ instructions: z.union([z.string(), agentProfileResourceRefSchema]).optional(),
4194
+ failOnError: z.boolean().optional()
4195
+ });
4196
+ const reasoningEffortSchema = z.enum(REASONING_EFFORTS);
4197
+ /**
4198
+ * Enforce the token ceilings that live together: each single ceiling must not
4199
+ * exceed the total. It fails loud on a violation and never clamps a value.
4200
+ * `reasoningEffort` is a separate quality dial and is not a bound here.
4201
+ */
4202
+ function enforceModelTokenBounds(hints, context) {
4203
+ const { maxVisibleOutputTokens, maxReasoningTokens, maxTotalOutputTokens } = hints;
4204
+ if (maxTotalOutputTokens === void 0) return;
4205
+ if (maxVisibleOutputTokens !== void 0 && maxVisibleOutputTokens > maxTotalOutputTokens) context.addIssue({
4206
+ code: "custom",
4207
+ path: ["maxVisibleOutputTokens"],
4208
+ message: "maxVisibleOutputTokens must not exceed maxTotalOutputTokens"
4209
+ });
4210
+ if (maxReasoningTokens !== void 0 && maxReasoningTokens > maxTotalOutputTokens) context.addIssue({
4211
+ code: "custom",
4212
+ path: ["maxReasoningTokens"],
4213
+ message: "maxReasoningTokens must not exceed maxTotalOutputTokens"
4214
+ });
4215
+ }
4216
+ const agentProfileModelHintsSchema = z.strictObject({
4217
+ default: z.string().optional(),
4218
+ small: z.string().optional(),
4219
+ provider: z.string().optional(),
4220
+ reasoningEffort: reasoningEffortSchema.optional(),
4221
+ maxVisibleOutputTokens: z.number().int().positive().optional(),
4222
+ maxReasoningTokens: z.number().int().positive().optional(),
4223
+ maxTotalOutputTokens: z.number().int().positive().optional(),
4224
+ metadata: ownPropertyRecordSchema(profileOpaqueValueSchema).optional()
4225
+ }).superRefine(enforceModelTokenBounds);
4226
+ /** Ordered account selection policy, without credentials or ambient model defaults. */
4227
+ const agentProfileSeatSchema = z.strictObject({
4228
+ harness: harnessTypeSchema,
4229
+ provider: z.string().regex(/^[a-z][a-z0-9-]*$/),
4230
+ model: z.string().min(1).refine((value) => value.trim() === value, "model must be canonical"),
4231
+ reasoningEffort: reasoningEffortSchema.optional(),
4232
+ selector: z.union([z.strictObject({ kind: z.literal("all-eligible") }), z.strictObject({
4233
+ kind: z.literal("seat"),
4234
+ id: z.string().min(1).refine((value) => value.trim() === value, "seat id must be canonical")
4235
+ })]),
4236
+ tools: ownPropertyRecordSchema(z.boolean()).optional(),
4237
+ permissions: ownPropertyRecordSchema(agentProfilePermissionSchema).optional()
4238
+ });
4239
+ /**
4240
+ * Replacement and addition are separate, independently optional fields, and the
4241
+ * pair is admitted on purpose: the effective prompt is `systemPrompt` followed
4242
+ * by `appendSystemPrompt`. No cross-field refinement rejects the combination,
4243
+ * because {@link mergeAgentProfiles} can produce it from two valid profiles.
4244
+ */
4245
+ const agentProfilePromptSchema = z.strictObject({
4246
+ systemPrompt: z.string().optional(),
4247
+ appendSystemPrompt: z.string().optional(),
4248
+ instructions: z.array(z.string()).max(CONTRACT_MAX_ARRAY_LENGTH).optional()
4249
+ });
4250
+ const controlCharacterPattern = /[\u0000-\u001f\u007f]/;
4251
+ const secretCapableNamePattern = /(?:^|[_-])(?:api[_-]?key|access[_-]?key|private[_-]?key|token|secret|password|credentials?|authorization|cookie|database[_-]?url|dsn|pat)(?:[_-]|$)/i;
4252
+ /** Return true when a public config name denotes credential material. */
4253
+ function isCredentialBearingProfileConfigName(name) {
4254
+ return secretCapableNamePattern.test(name);
4255
+ }
4256
+ const publicProfileConfigStringSchema = z.string().refine((value) => isWellFormedUnicode(value) && !controlCharacterPattern.test(value) && !looksLikeCredential(value), "public profile config cannot carry credential-like material");
4257
+ const agentProfilePublicConfigValueSchema = z.strictObject({
4258
+ kind: z.literal("public"),
4259
+ value: publicProfileConfigStringSchema
4260
+ });
4261
+ const agentProfileSecretRefSchema = agentCandidateSecretRefSchema;
4262
+ const agentProfileConfigValueSchema = z.discriminatedUnion("kind", [agentProfilePublicConfigValueSchema, agentProfileSecretRefSchema]);
4263
+ function profileConfigRecordSchema(keySchema) {
4264
+ return ownPropertyRecordSchema(agentProfileConfigValueSchema).superRefine((record, context) => {
4265
+ for (const [name, value] of Object.entries(record)) {
4266
+ if (!keySchema.safeParse(name).success) context.addIssue({
4267
+ code: "custom",
4268
+ path: [name],
4269
+ message: "profile config key is invalid for this field"
4270
+ });
4271
+ if (value.kind === "public" && isCredentialBearingProfileConfigName(name)) context.addIssue({
4272
+ code: "custom",
4273
+ path: [name],
4274
+ message: "credential-bearing config names require a secret-ref"
4275
+ });
4276
+ }
4277
+ });
4278
+ }
4279
+ const agentProfileEnvironmentSchema = profileConfigRecordSchema(environmentNameSchema);
4280
+ const agentProfileHeaderSchema = profileConfigRecordSchema(headerNameSchema);
4281
+ const agentSubagentProfileSchema = z.strictObject({
4282
+ description: z.string().optional(),
4283
+ prompt: z.string().optional(),
4284
+ model: z.string().optional(),
4285
+ tools: ownPropertyRecordSchema(z.boolean()).optional(),
4286
+ permissions: ownPropertyRecordSchema(agentProfilePermissionSchema).optional(),
4287
+ maxSteps: z.number().optional(),
4288
+ metadata: ownPropertyRecordSchema(profileOpaqueValueSchema).optional()
4289
+ });
4290
+ const agentProfileHookCommandSchema = z.strictObject({
4291
+ command: z.string(),
4292
+ timeoutMs: z.number().positive().optional(),
4293
+ blocking: z.boolean().optional(),
4294
+ matcher: z.string().optional(),
4295
+ env: agentProfileEnvironmentSchema.optional()
4296
+ });
4297
+ const agentProfileModeSchema = z.strictObject({
4298
+ description: z.string().optional(),
4299
+ model: z.string().optional(),
4300
+ prompt: z.string().optional(),
4301
+ tools: ownPropertyRecordSchema(z.boolean()).optional(),
4302
+ permissions: ownPropertyRecordSchema(agentProfilePermissionSchema).optional(),
4303
+ metadata: ownPropertyRecordSchema(profileOpaqueValueSchema).optional()
4304
+ });
4305
+ const agentProfileConfidentialSchema = z.strictObject({
4306
+ tee: z.string().optional(),
4307
+ attestationNonce: z.string().optional(),
4308
+ sealed: z.boolean().optional(),
4309
+ attestationRefresh: z.boolean().optional()
4310
+ });
4311
+ const nonBlankMcpValueSchema = z.string().refine((value) => value.trim().length > 0, "value cannot be blank");
4312
+ const remoteMcpUrlSchema = nonBlankMcpValueSchema.refine((value) => {
4313
+ try {
4314
+ const url = new URL(value);
4315
+ return url.protocol === "http:" || url.protocol === "https:";
4316
+ } catch {
4317
+ return false;
4318
+ }
4319
+ }, "remote MCP url must be an absolute HTTP(S) URL").refine((value) => !looksLikeCredential(value), "remote MCP url cannot contain credentials or credential-named query parameters");
4320
+ const agentProfileLocalMcpServerSchema = z.strictObject({
4321
+ transport: z.literal("stdio").optional(),
4322
+ command: nonBlankMcpValueSchema.refine(isSafeExecutable, "local MCP command must be a canonical public executable"),
4323
+ args: z.array(agentProfileConfigValueSchema).max(CONTRACT_MAX_ARRAY_LENGTH).optional(),
4324
+ env: agentProfileEnvironmentSchema.optional(),
4325
+ cwd: z.string().refine((value) => isSafeRelativePath(value, true), "local MCP cwd must be a canonical workspace-relative path").optional(),
4326
+ url: z.undefined().optional(),
4327
+ headers: z.undefined().optional(),
4328
+ enabled: z.literal(true).optional(),
4329
+ metadata: ownPropertyRecordSchema(profileOpaqueValueSchema).optional()
4330
+ });
4331
+ const agentProfileRemoteMcpServerSchema = z.strictObject({
4332
+ transport: z.enum(["sse", "http"]).optional(),
4333
+ command: z.undefined().optional(),
4334
+ args: z.undefined().optional(),
4335
+ env: z.undefined().optional(),
4336
+ cwd: z.undefined().optional(),
4337
+ url: remoteMcpUrlSchema,
4338
+ headers: agentProfileHeaderSchema.optional(),
4339
+ enabled: z.literal(true).optional(),
4340
+ metadata: ownPropertyRecordSchema(profileOpaqueValueSchema).optional()
4341
+ });
4342
+ const agentProfileDisabledMcpServerSchema = z.strictObject({
4343
+ enabled: z.literal(false),
4344
+ transport: z.undefined().optional(),
4345
+ command: z.undefined().optional(),
4346
+ args: z.undefined().optional(),
4347
+ env: z.undefined().optional(),
4348
+ cwd: z.undefined().optional(),
4349
+ url: z.undefined().optional(),
4350
+ headers: z.undefined().optional(),
4351
+ metadata: ownPropertyRecordSchema(profileOpaqueValueSchema).optional()
4352
+ });
4353
+ const agentProfileMcpServerSchema = z.union([
4354
+ agentProfileLocalMcpServerSchema,
4355
+ agentProfileRemoteMcpServerSchema,
4356
+ agentProfileDisabledMcpServerSchema
4357
+ ]);
4358
+ const agentProfileConnectionSchema = z.strictObject({
4359
+ connectionId: z.string().min(1),
4360
+ capabilities: z.array(z.string().min(1)).max(CONTRACT_MAX_ARRAY_LENGTH).min(1),
4361
+ alias: z.string().min(1).optional()
4362
+ });
4363
+ const removeListSchema = z.union([z.literal(true), z.array(z.string().min(1)).max(CONTRACT_MAX_ARRAY_LENGTH)]);
4364
+ const agentProfilePromptRemovalSchema = z.strictObject({
4365
+ systemPrompt: z.literal(true).optional(),
4366
+ appendSystemPrompt: z.literal(true).optional(),
4367
+ instructions: removeListSchema.optional()
4368
+ });
4369
+ const agentProfileResourceRemovalSchema = z.strictObject({
4370
+ knowledge: removeListSchema.optional(),
4371
+ files: removeListSchema.optional(),
4372
+ tools: removeListSchema.optional(),
4373
+ skills: removeListSchema.optional(),
4374
+ agents: removeListSchema.optional(),
4375
+ commands: removeListSchema.optional(),
4376
+ instructions: z.literal(true).optional(),
4377
+ failOnError: z.literal(true).optional()
4378
+ });
4379
+ const agentProfileDiffRemovalSchema = z.strictObject({
4380
+ identity: z.literal(true).optional(),
4381
+ tags: removeListSchema.optional(),
4382
+ prompt: z.union([z.literal(true), agentProfilePromptRemovalSchema]).optional(),
4383
+ model: removeListSchema.optional(),
4384
+ harness: z.literal(true).optional(),
4385
+ seats: z.literal(true).optional(),
4386
+ proxySecrets: z.literal(true).optional(),
4387
+ permissions: removeListSchema.optional(),
4388
+ tools: removeListSchema.optional(),
4389
+ mcp: removeListSchema.optional(),
4390
+ connections: removeListSchema.optional(),
4391
+ subagents: removeListSchema.optional(),
4392
+ resources: z.union([z.literal(true), agentProfileResourceRemovalSchema]).optional(),
4393
+ hooks: removeListSchema.optional(),
4394
+ modes: removeListSchema.optional(),
4395
+ confidential: z.literal(true).optional(),
4396
+ metadata: removeListSchema.optional(),
4397
+ extensions: removeListSchema.optional()
4398
+ });
4399
+ const trainingIdentitySchema = z.string().min(1).max(500).refine((value) => value.trim() === value && isWellFormedUnicode(value) && !controlCharacterPattern.test(value) && !looksLikeCredential(value), "training identity must be canonical public text");
4400
+ const agentTrainingTaskSchema = z.strictObject({
4401
+ benchmark: trainingIdentitySchema,
4402
+ task: trainingIdentitySchema,
4403
+ contentDigest: sha256DigestSchema
4404
+ });
4405
+ /** The same order is used by dataset ingestion, receipt admission and holdout checks. */
4406
+ function agentTrainingTaskKey(task) {
4407
+ return JSON.stringify([
4408
+ task.benchmark,
4409
+ task.task,
4410
+ task.contentDigest
4411
+ ]);
4412
+ }
4413
+ const agentTrainingDatasetIdentitySchema = z.strictObject({
4414
+ digest: sha256DigestSchema,
4415
+ taskSetDigest: sha256DigestSchema,
4416
+ tasks: z.array(agentTrainingTaskSchema).min(1).max(1e4)
4417
+ }).superRefine((dataset, context) => {
4418
+ const keys = dataset.tasks.map(agentTrainingTaskKey);
4419
+ if (keys.some((key, index) => index > 0 && key <= keys[index - 1])) context.addIssue({
4420
+ code: "custom",
4421
+ path: ["tasks"],
4422
+ message: "training tasks must be sorted and unique"
4423
+ });
4424
+ if (canonicalCandidateDigest(dataset.tasks) !== dataset.taskSetDigest) context.addIssue({
4425
+ code: "custom",
4426
+ path: ["taskSetDigest"],
4427
+ message: "training task inventory digest mismatch"
4428
+ });
4429
+ });
4430
+ const agentTrainingParametersSchema = ownPropertyRecordSchema(z.union([
4431
+ z.string().max(2048).pipe(publicProfileConfigStringSchema),
4432
+ z.number().finite(),
4433
+ z.boolean(),
4434
+ z.null()
4435
+ ]), { maxEntries: 100 }).superRefine((parameters, context) => {
4436
+ for (const name of Object.keys(parameters)) if (!trainingIdentitySchema.safeParse(name).success || isCredentialBearingProfileConfigName(name)) context.addIssue({
4437
+ code: "custom",
4438
+ path: [name],
4439
+ message: "training parameter name must be public and non-credential"
4440
+ });
4441
+ });
4442
+ const agentTrainingReceiptSchema = z.strictObject({
4443
+ version: z.literal(1),
4444
+ dataset: agentTrainingDatasetIdentitySchema,
4445
+ parentProfileDigest: sha256DigestSchema,
4446
+ parentReceiptDigest: sha256DigestSchema.nullable(),
4447
+ executionRef: sha256DigestSchema,
4448
+ trainer: z.strictObject({
4449
+ mode: z.enum(["command", "managed"]),
4450
+ id: trainingIdentitySchema,
4451
+ revision: sha256DigestSchema,
4452
+ parameters: agentTrainingParametersSchema
4453
+ }),
4454
+ checkpoint: z.strictObject({
4455
+ artifactDigest: sha256DigestSchema,
4456
+ artifactBytes: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
4457
+ routerModelId: trainingIdentitySchema,
4458
+ servingDigest: sha256DigestSchema
4459
+ })
4460
+ }).superRefine((receipt, context) => {
4461
+ if (receipt.checkpoint.routerModelId !== trainedModelIdForArtifact(receipt.checkpoint.artifactDigest)) context.addIssue({
4462
+ code: "custom",
4463
+ path: ["checkpoint", "routerModelId"],
4464
+ message: "trained Router model must be artifact-addressed"
4465
+ });
4466
+ });
4467
+ const agentProfileTrainingSchema = z.strictObject({
4468
+ receipt: agentTrainingReceiptSchema,
4469
+ ancestors: z.array(agentTrainingReceiptSchema).max(8)
4470
+ }).superRefine((training, context) => {
4471
+ const chain = [training.receipt, ...training.ancestors];
4472
+ const digests = chain.map(canonicalCandidateDigest);
4473
+ if (new Set(digests).size !== digests.length) context.addIssue({
4474
+ code: "custom",
4475
+ message: "training receipt ancestry must not repeat"
4476
+ });
4477
+ for (let index = 0; index < chain.length; index++) if (chain[index].parentReceiptDigest !== (digests[index + 1] ?? null)) context.addIssue({
4478
+ code: "custom",
4479
+ message: "training receipt ancestry is incomplete or has been altered"
4480
+ });
4481
+ });
4482
+ const agentProfileMetadataSchema = ownPropertyRecordSchema(z.unknown(), { prepareValue: (key, value) => {
4483
+ if (key === "training") return value;
4484
+ if (value === void 0 || isBoundedJsonMaterial(value, {
4485
+ dataPropertiesOnly: true,
4486
+ content: true
4487
+ })) return structuredClone(value);
4488
+ assertAgentProfileValue(value, [key]);
4489
+ return z.NEVER;
4490
+ } }).superRefine((metadata, context) => {
4491
+ if (!Object.hasOwn(metadata, "training")) return;
4492
+ const result = agentProfileTrainingSchema.safeParse(metadata.training);
4493
+ if (result.success) metadata.training = result.data;
4494
+ else {
4495
+ delete metadata.training;
4496
+ for (const issue of result.error.issues) context.addIssue({
4497
+ code: "custom",
4498
+ path: ["training", ...issue.path],
4499
+ message: issue.message,
4500
+ continue: false
4501
+ });
4502
+ }
4503
+ });
4504
+ /**
4505
+ * The complete provider-neutral agent profile schema — the runtime validator for
4506
+ * the canonical {@link AgentProfile} TS contract. Kept structurally in lock-step
4507
+ * with that interface by the compile-time guard at the bottom of this file.
4508
+ */
4509
+ const agentProfileSchema = z.strictObject({
4510
+ name: z.string().optional(),
4511
+ description: z.string().optional(),
4512
+ version: z.string().optional(),
4513
+ tags: z.array(z.string()).max(CONTRACT_MAX_ARRAY_LENGTH).optional(),
4514
+ prompt: agentProfilePromptSchema.optional(),
4515
+ model: agentProfileModelHintsSchema.optional(),
4516
+ harness: harnessTypeSchema.optional(),
4517
+ seats: z.array(agentProfileSeatSchema).max(CONTRACT_MAX_ARRAY_LENGTH).nonempty().optional(),
4518
+ proxySecrets: ProxySecretsSchema.optional(),
4519
+ permissions: ownPropertyRecordSchema(agentProfilePermissionSchema).optional(),
4520
+ tools: ownPropertyRecordSchema(z.boolean()).optional(),
4521
+ mcp: ownPropertyRecordSchema(agentProfileMcpServerSchema).optional(),
4522
+ connections: z.array(agentProfileConnectionSchema).max(CONTRACT_MAX_ARRAY_LENGTH).optional(),
4523
+ subagents: ownPropertyRecordSchema(agentSubagentProfileSchema).optional(),
4524
+ resources: agentProfileResourcesSchema.optional(),
4525
+ hooks: ownPropertyRecordSchema(z.array(agentProfileHookCommandSchema).max(CONTRACT_MAX_ARRAY_LENGTH)).optional(),
4526
+ modes: ownPropertyRecordSchema(agentProfileModeSchema).optional(),
4527
+ confidential: agentProfileConfidentialSchema.optional(),
4528
+ metadata: agentProfileMetadataSchema.optional(),
4529
+ extensions: ownPropertyRecordSchema(z.union([ownPropertyRecordSchema(profileOpaqueValueSchema), z.undefined()])).optional()
4530
+ }).superRefine((profile, context) => {
4531
+ validateNestedRecordKeys(profile, context, [], /* @__PURE__ */ new Set());
4532
+ if (profile.seats?.length) {
4533
+ const first = profile.seats[0];
4534
+ if (first.harness !== profile.harness || first.provider !== profile.model?.provider || first.model !== profile.model?.default) context.addIssue({
4535
+ code: "custom",
4536
+ path: ["seats", 0],
4537
+ message: "first seat must match profile harness, model.provider, and model.default"
4538
+ });
4539
+ if (first.reasoningEffort !== void 0 && first.reasoningEffort !== profile.model?.reasoningEffort) context.addIssue({
4540
+ code: "custom",
4541
+ path: [
4542
+ "seats",
4543
+ 0,
4544
+ "reasoningEffort"
4545
+ ],
4546
+ message: "first seat reasoningEffort must match profile model.reasoningEffort"
4547
+ });
4548
+ if (first.tools !== void 0 && canonicalAgentProfileJson(first.tools) !== canonicalAgentProfileJson(profile.tools)) context.addIssue({
4549
+ code: "custom",
4550
+ path: [
4551
+ "seats",
4552
+ 0,
4553
+ "tools"
4554
+ ],
4555
+ message: "first seat tools must match profile tools"
4556
+ });
4557
+ if (first.permissions !== void 0 && canonicalAgentProfileJson(first.permissions) !== canonicalAgentProfileJson(profile.permissions)) context.addIssue({
4558
+ code: "custom",
4559
+ path: [
4560
+ "seats",
4561
+ 0,
4562
+ "permissions"
4563
+ ],
4564
+ message: "first seat permissions must match profile permissions"
4565
+ });
4566
+ for (const [index, seat] of profile.seats.entries()) {
4567
+ if (resolveModelProvider(seat.model) !== seat.provider) context.addIssue({
4568
+ code: "custom",
4569
+ path: [
4570
+ "seats",
4571
+ index,
4572
+ "provider"
4573
+ ],
4574
+ message: "seat provider must match the model provider"
4575
+ });
4576
+ if (!harnessHonorsModel(seat.harness)) context.addIssue({
4577
+ code: "custom",
4578
+ path: [
4579
+ "seats",
4580
+ index,
4581
+ "harness"
4582
+ ],
4583
+ message: "seat harness does not honor an exact model choice"
4584
+ });
4585
+ const effort = seat.reasoningEffort ?? profile.model?.reasoningEffort;
4586
+ const support = harnessModelSupport(seat.harness, seat.model, { reasoningEffort: effort });
4587
+ if (!support.supported) context.addIssue({
4588
+ code: "custom",
4589
+ path: [
4590
+ "seats",
4591
+ index,
4592
+ "model"
4593
+ ],
4594
+ message: support.message
4595
+ });
4596
+ if (effort !== void 0 && (!harnessHonorsEffort(seat.harness) || !harnessReasoningEfforts(seat.harness).includes(effort))) context.addIssue({
4597
+ code: "custom",
4598
+ path: [
4599
+ "seats",
4600
+ index,
4601
+ "reasoningEffort"
4602
+ ],
4603
+ message: "seat harness cannot honor the stage reasoning effort"
4604
+ });
4605
+ const prompt = harnessSystemPromptIntents(seat.harness);
4606
+ if (profile.prompt?.systemPrompt !== void 0 && !prompt.replace) context.addIssue({
4607
+ code: "custom",
4608
+ path: [
4609
+ "seats",
4610
+ index,
4611
+ "harness"
4612
+ ],
4613
+ message: "seat harness cannot replace the system prompt"
4614
+ });
4615
+ if (profile.prompt?.appendSystemPrompt !== void 0 && !prompt.append) context.addIssue({
4616
+ code: "custom",
4617
+ path: [
4618
+ "seats",
4619
+ index,
4620
+ "harness"
4621
+ ],
4622
+ message: "seat harness cannot append the system prompt"
4623
+ });
4624
+ }
4625
+ }
4626
+ const training = agentProfileTrainingSchema.safeParse(profile.metadata?.training);
4627
+ if (profile.model?.default?.startsWith("tangle-trained/") && !training.success) context.addIssue({
4628
+ code: "custom",
4629
+ path: ["metadata", "training"],
4630
+ message: "trained model requires a checkpoint receipt"
4631
+ });
4632
+ if ([
4633
+ profile.model?.small,
4634
+ ...Object.values(profile.subagents ?? {}).map((agent) => agent.model),
4635
+ ...Object.values(profile.modes ?? {}).map((mode) => mode.model)
4636
+ ].some((model) => model?.startsWith("tangle-trained/") && (!training.success || model !== training.data.receipt.checkpoint.routerModelId))) context.addIssue({
4637
+ code: "custom",
4638
+ message: "trained auxiliary models require the same receipted checkpoint"
4639
+ });
4640
+ if (training.success && profile.model?.default !== training.data.receipt.checkpoint.routerModelId) context.addIssue({
4641
+ code: "custom",
4642
+ path: ["model", "default"],
4643
+ message: "trained profile model must equal the receipt's Router model"
4644
+ });
4645
+ });
4646
+ const encodedRecordKeyPattern = "^u(?:[0-9a-f]{4})*$";
4647
+ function isEncodedRecordKeyPropertyNames(value) {
4648
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
4649
+ const propertyNames = value;
4650
+ return propertyNames.type === "string" && propertyNames.pattern === encodedRecordKeyPattern;
4651
+ }
4652
+ function removeModelInputSchemaArtifacts(value) {
4653
+ if (Array.isArray(value)) return value.map(removeModelInputSchemaArtifacts);
4654
+ if (value === null || typeof value !== "object") return value;
4655
+ const result = {};
4656
+ for (const [key, entry] of Object.entries(value)) {
4657
+ if (key === "$schema") continue;
4658
+ if (key === "propertyNames" && isEncodedRecordKeyPropertyNames(entry)) continue;
4659
+ result[key] = removeModelInputSchemaArtifacts(entry);
4660
+ }
4661
+ return result;
4662
+ }
4663
+ removeModelInputSchemaArtifacts(z.toJSONSchema(agentProfileSchema, {
4664
+ target: "draft-2020-12",
4665
+ io: "input",
4666
+ unrepresentable: "any"
4667
+ }));
4668
+ function validateNestedRecordKeys(value, context, path, seen) {
4669
+ if (value === null || typeof value !== "object" || seen.has(value)) return;
4670
+ seen.add(value);
4671
+ for (const [key, entry] of Object.entries(value)) {
4672
+ if (!isWellFormedUnicode(key)) context.addIssue({
4673
+ code: "custom",
4674
+ path: [...path, key],
4675
+ message: "record keys must contain valid Unicode"
4676
+ });
4677
+ validateNestedRecordKeys(entry, context, [...path, key], seen);
4678
+ }
4679
+ }
4680
+ z.strictObject({
4681
+ kind: z.literal("agent-profile-diff"),
4682
+ id: z.string().min(1).optional(),
4683
+ title: z.string().min(1).optional(),
4684
+ description: z.string().optional(),
4685
+ rationale: z.string().optional(),
4686
+ source: z.strictObject({
4687
+ kind: z.enum([
4688
+ "trace",
4689
+ "frontier-author",
4690
+ "human",
4691
+ "optimizer",
4692
+ "compound"
4693
+ ]),
4694
+ artifacts: z.array(z.string().min(1)).max(CONTRACT_MAX_ARRAY_LENGTH).optional(),
4695
+ notes: z.array(z.string()).max(CONTRACT_MAX_ARRAY_LENGTH).optional()
4696
+ }).optional(),
4697
+ set: agentProfileSchema.optional(),
4698
+ remove: agentProfileDiffRemovalSchema.optional(),
4699
+ metadata: ownPropertyRecordSchema(profileOpaqueValueSchema).optional()
4700
+ });
4701
+ z.strictObject({
4702
+ id: z.string().min(1),
4703
+ definition: agentProfileSchema,
4704
+ recommendedSize: z.enum(SANDBOX_SIZE_PRESET_NAMES).optional()
4705
+ });
4706
+ //#endregion
4707
+ //#region ../../../node_modules/.pnpm/@tangle-network+agent-interface@5.10.11/node_modules/@tangle-network/agent-interface/dist/runtime-attachments.js
4708
+ const AgentRuntimeAttachmentsSchema = boundedJsonSchema.pipe(z.strictObject({ mcp: agentProfileSchema.shape.mcp.unwrap().superRefine((servers, context) => {
4709
+ for (const alias of Object.keys(servers)) {
4710
+ const result = boundedIdentifierSchema.safeParse(alias);
4711
+ if (!result.success) for (const issue of result.error.issues) context.addIssue({
4712
+ ...issue,
4713
+ path: [alias, ...issue.path]
4714
+ });
4715
+ }
4716
+ }) }));
4717
+ //#endregion
3222
4718
  //#region ../../../packages/agent-profile-materialize/dist/index.js
3223
4719
  const compareStrings = (a, b) => a < b ? -1 : a > b ? 1 : 0;
3224
4720
  constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (typeof constants.O_NOFOLLOW === "number" ? constants.O_NOFOLLOW : 0);
4721
+ function normalizeWorkspaceRelativePath(pathValue) {
4722
+ if (typeof pathValue !== "string" || !pathValue || hasControlCharacter$1(pathValue)) throw new Error("Workspace file path must be non-empty and contain no control characters");
4723
+ if (isAbsolute(pathValue) || win32.isAbsolute(pathValue) || /^[A-Za-z]:/.test(pathValue)) throw new Error(`Workspace file path must be relative: ${pathValue}`);
4724
+ const segments = pathValue.replace(/\\/g, "/").split("/");
4725
+ if (segments.some((segment) => !segment || segment === "." || segment === ".." || segment === ".git" || segment === ".sidecar")) throw new Error(`Workspace file path must be canonical: ${pathValue}`);
4726
+ return segments.join("/");
4727
+ }
4728
+ function hasControlCharacter$1(value) {
4729
+ for (let index = 0; index < value.length; index++) {
4730
+ const code = value.charCodeAt(index);
4731
+ if (code < 32 || code === 127) return true;
4732
+ }
4733
+ return false;
4734
+ }
4735
+ function validateFileMode(mode) {
4736
+ const normalized = mode ?? 420;
4737
+ if (!Number.isInteger(normalized) || normalized < 0 || normalized > 511) throw new Error(`Workspace file mode must be between 0o000 and 0o777: ${mode}`);
4738
+ return normalized;
4739
+ }
4740
+ const MATERIALIZER_HARNESS_SET = new Set([
4741
+ "claude-code",
4742
+ "nanoclaw",
4743
+ "codex",
4744
+ "opencode",
4745
+ "kimi-code",
4746
+ "pi",
4747
+ "prime",
4748
+ "gemini",
4749
+ "hermes",
4750
+ "openclaw"
4751
+ ]);
4752
+ function isMaterializerHarness(harness) {
4753
+ return MATERIALIZER_HARNESS_SET.has(harness);
4754
+ }
4755
+ function assertMaterializerHarness(harness) {
4756
+ if (!isMaterializerHarness(harness)) throw new Error(`Unsupported profile materialization harness "${harness}"`);
4757
+ }
3225
4758
  const CODEX_SYSTEM_PROMPT_FILE = ".codex/system-prompt.md";
3226
4759
  const OPENCODE_APPEND_SYSTEM_PROMPT_FILE = ".opencode/agent-system-prompt.md";
3227
4760
  const OPENCODE_CONFIG_FILE = "opencode.json";
4761
+ const OPENCODE_CONFIG_SCHEMA = "https://opencode.ai/config.json";
4762
+ const OPENCODE_PRIMARY_AGENT_PREFIX = "tangle-profile-";
4763
+ const CLAUDE_SETTINGS_PATH = ".tangle/claude-settings.json";
4764
+ /** Whether the shared materializer may place its context file in the harness agent directory. */
4765
+ function harnessAutoLoadsAgentContextFile(harness) {
4766
+ assertMaterializerHarness(harness);
4767
+ return harness === "pi";
4768
+ }
4769
+ /**
4770
+ * Why a harness refuses a system-prompt REPLACEMENT.
4771
+ *
4772
+ * The reason names the control that does exist, so the refusal is actionable
4773
+ * without a capability-matrix lookup — a bare "unsupported" sends the caller
4774
+ * looking for a flag that was never there.
4775
+ */
4776
+ function systemPromptRefusal(harness) {
4777
+ switch (harness) {
4778
+ case "opencode": return "opencode: the only system-prompt replacement is per-agent (`agent.<name>.prompt`), which binds to the agent selected at launch and a workspace plan cannot guarantee; an executor that applies the plan's \"--agent\" flag to its own spawn declares binds: [\"systemPrompt\"], and one that composes opencode's config itself declares binds: [\"opencode.agent-prompt\"]";
4779
+ default: return `${harness}: no verified exact system-prompt replacement control`;
4780
+ }
4781
+ }
4782
+ /**
4783
+ * Why a harness refuses an ADDITION to the system prompt.
4784
+ *
4785
+ * gemini puts its context file in the system-prompt position, so the temptation
4786
+ * is to lower an addition there. That is refused because GEMINI.md is the ONE
4787
+ * file it auto-loads: an addition written there is byte-identical to the same
4788
+ * text under `prompt.instructions`, and no consumer could tell which intent the
4789
+ * caller expressed. opencode is not refused for the same situation, because it
4790
+ * loads exactly the files its config names and can therefore carry the two
4791
+ * intents in separate, separately-ordered files.
4792
+ */
4793
+ function appendSystemPromptRefusal(harness) {
4794
+ switch (harness) {
4795
+ case "gemini": return "gemini: the only additive system-prompt channel is GEMINI.md memory, the single context file it auto-loads, which `prompt.instructions` already materializes — use it instead";
4796
+ case "codex": return "codex: no verified additive system-prompt control — its AGENTS.md lands in a developer/user message, not the system channel";
4797
+ default: return `${harness}: no verified additive system-prompt control`;
4798
+ }
4799
+ }
3228
4800
  /** Project context file each harness actually reads from cwd. NEVER a constant. */
3229
4801
  const CONTEXT_FILE = {
3230
4802
  "claude-code": "CLAUDE.md",
@@ -3273,22 +4845,764 @@ const CONTEXT_FILE_PATHS = new Set(Object.values(CONTEXT_FILE));
3273
4845
  * invented, already owned by the name alone.
3274
4846
  */
3275
4847
  const MATERIALIZER_CONTEXT_PATHS = new Set([...CONTEXT_FILE_PATHS].filter((path) => !MATERIALIZER_RESERVED_PATHS.has(path)));
3276
- new Set([
4848
+ /**
4849
+ * The paths whose generated content is wholly this package's output, per
4850
+ * {@link PlanFile.ownership}: the reserved names, the context files, and
4851
+ * `opencode.json`, which carries only the registrations this package generates
4852
+ * from the profile.
4853
+ *
4854
+ * `opencode.json` and every context file is a documented name a user repository
4855
+ * can carry, so the name alone proves nothing and a profile resource may still
4856
+ * mount one. An existing file there is replaced only when
4857
+ * {@link materializerReplacement} recognizes its bytes as this package's own
4858
+ * earlier output.
4859
+ *
4860
+ * Deliberately absent: `.gemini/system.md`, the file `prompt.systemPrompt`
4861
+ * lowers to. The line a marker would have to add is the reason. A REPLACEMENT
4862
+ * is the caller's exact bytes and this package may add none of its own, so that
4863
+ * path keeps refusing. A context file carries `prompt.instructions`, which this
4864
+ * package already composes — it joins the blocks and appends the final newline
4865
+ * — so one more composed line is inside the same authority.
4866
+ *
4867
+ * That line, not "which channel the harness reads it on", is what separates the
4868
+ * two. `GEMINI.md` is owned even though gemini lowers its context file into the
4869
+ * system-prompt position as an ADDITION ({@link appendSystemPromptRefusal}),
4870
+ * because the intent it carries is still instructions this package composed.
4871
+ */
4872
+ const MATERIALIZER_OWNED_PATHS = new Set([
3277
4873
  ...MATERIALIZER_RESERVED_PATHS,
3278
4874
  ...MATERIALIZER_CONTEXT_PATHS,
3279
4875
  OPENCODE_CONFIG_FILE
3280
4876
  ]);
4877
+ const MATERIALIZER_SUBAGENT_PATH = /^(?:(?:\.claude|\.opencode|\.gemini)\/agents\/[a-z0-9][a-z0-9_-]*\.md|\.codex\/agents\/[a-z0-9][a-z0-9_-]*\.toml)$/u;
3281
4878
  /** The one provenance token every generated-file marker carries. */
3282
4879
  const MATERIALIZER_MARKER = "tangle-agent-profile-materialize: generated";
3283
- `${MATERIALIZER_MARKER}`;
4880
+ const MATERIALIZER_SUBAGENT_MARKER = `# ${MATERIALIZER_MARKER}`;
3284
4881
  const MATERIALIZER_CONTEXT_MARKER_NOTE = "do not edit; the next profile materialization replaces this file";
4882
+ function materializerSubagentMarkerPrefix(relPath) {
4883
+ return relPath.endsWith(".toml") ? `${MATERIALIZER_SUBAGENT_MARKER}\n` : `---\n${MATERIALIZER_SUBAGENT_MARKER}\n`;
4884
+ }
4885
+ /** Mark one generated native agent file without changing its harness meaning. */
4886
+ function markMaterializerSubagent(relPath, content) {
4887
+ if (!MATERIALIZER_SUBAGENT_PATH.test(relPath)) throw new Error(`Not a native agent path: ${relPath}`);
4888
+ if (relPath.endsWith(".toml")) return `${materializerSubagentMarkerPrefix(relPath)}${content}`;
4889
+ if (!content.startsWith("---\n")) throw new Error(`Native Markdown agent has no frontmatter: ${relPath}`);
4890
+ return `${materializerSubagentMarkerPrefix(relPath)}${content.slice(4)}`;
4891
+ }
4892
+ /** The marker line a generated context file whose body is `body` carries. */
4893
+ function materializerContextMarker(body) {
4894
+ return `<!-- ${MATERIALIZER_MARKER} sha256:${createHash("sha256").update(body, "utf8").digest("hex")}; ${MATERIALIZER_CONTEXT_MARKER_NOTE} -->`;
4895
+ }
4896
+ /**
4897
+ * Mark one generated context file so the NEXT materialization can prove this
4898
+ * package wrote the bytes it is about to replace.
4899
+ *
4900
+ * The marker is an HTML comment on line 1. CommonMark closes an HTML block at
4901
+ * the line holding `-->`, so every instruction below it parses exactly as it
4902
+ * did without the line, and the line itself states no instruction. It is one
4903
+ * more line this package composes into a file it already composes: it goes on
4904
+ * a context file, which carries `prompt.instructions`, and NEVER on a
4905
+ * system-prompt REPLACEMENT, whose bytes are the caller's exact text
4906
+ * (`.gemini/system.md`; `.codex/system-prompt.md` is a reserved name this
4907
+ * package invented and needs no marker to be owned).
4908
+ *
4909
+ * It carries the digest of the generated body below it, which the subagent
4910
+ * marker does not need. `CLAUDE.md` is claude-code's own memory file and the
4911
+ * agent appends to it mid-session, so a bare marker would still sit on line 1
4912
+ * of a file the agent has since rewritten. The digest tells which leading bytes
4913
+ * are still this package's own: the next materialization replaces exactly
4914
+ * those and keeps what the agent appended below them
4915
+ * ({@link generatedContextAppendix}). The marker's wording is part of every
4916
+ * marker already written into live workspaces, so it stays as it is.
4917
+ *
4918
+ * A reserved context path — opencode's invented instruction file — is returned
4919
+ * unchanged: its NAME already proves the provenance, and nothing else may mount
4920
+ * there.
4921
+ */
4922
+ function markMaterializerContextFile(relPath, content) {
4923
+ if (!CONTEXT_FILE_PATHS.has(relPath)) throw new Error(`Not a harness context file: ${relPath}`);
4924
+ if (!MATERIALIZER_CONTEXT_PATHS.has(relPath)) return content;
4925
+ return `${materializerContextMarker(content)}\n${content}`;
4926
+ }
3285
4927
  `${MATERIALIZER_MARKER}`;
3286
4928
  `${MATERIALIZER_CONTEXT_MARKER_NOTE}`;
4929
+ /**
4930
+ * Whether a generated file occupies a path that the profile materializer owns.
4931
+ *
4932
+ * Generated native agent files and generated context files come from the active
4933
+ * profile.
4934
+ * The active profile must replace the prior profile version at the same path.
4935
+ * Otherwise, a profile update stops every resumed session before launch.
4936
+ * Explicit resources at these paths stay shared.
4937
+ * The plan builder applies ownership only when the source is `generated`.
4938
+ * An output marker proves ownership before replacement.
4939
+ */
4940
+ function isMaterializerOwnedPath(relPath) {
4941
+ return MATERIALIZER_OWNED_PATHS.has(relPath) || MATERIALIZER_SUBAGENT_PATH.test(relPath);
4942
+ }
4943
+ /**
4944
+ * cwd-relative native skill dir per harness, or null if the harness has no
4945
+ * cwd skill primitive (skills live in a user/global dir the workspace plan
4946
+ * cannot reach). Public so consumers composing a profile can (a) render the
4947
+ * exact path the platform will mount a skill at into their prompts instead
4948
+ * of hardcoding `~/.claude/skills/...`, and (b) branch on skill support
4949
+ * ahead of materialization instead of catching the materialize-time throw.
4950
+ */
4951
+ const HARNESS_SKILL_DIRS = {
4952
+ "claude-code": ".claude/skills",
4953
+ nanoclaw: ".claude/skills",
4954
+ codex: ".codex/skills",
4955
+ opencode: ".opencode/skills",
4956
+ "kimi-code": ".kimi/skills",
4957
+ pi: ".pi/skills",
4958
+ prime: ".prime/agent/skills",
4959
+ gemini: ".gemini/skills",
4960
+ hermes: null,
4961
+ openclaw: "skills"
4962
+ };
4963
+ function mergeJsonFiles(files) {
4964
+ const byPath = /* @__PURE__ */ new Map();
4965
+ for (const f of files) {
4966
+ const identity = `${normalizePlanFileRoot(f.root)}\0${f.relPath}`;
4967
+ const prev = byPath.get(identity);
4968
+ if (!prev) {
4969
+ byPath.set(identity, f);
4970
+ continue;
4971
+ }
4972
+ if (f.relPath.endsWith(".json")) try {
4973
+ const next = JSON.parse(f.content);
4974
+ const merged = {
4975
+ ...JSON.parse(prev.content),
4976
+ ...next
4977
+ };
4978
+ const replacedRoots = new Set(Object.keys(next));
4979
+ const secretSlots = [...(prev.secretSlots ?? []).filter((slot) => typeof slot.path[0] === "string" && !replacedRoots.has(slot.path[0])), ...f.secretSlots ?? []];
4980
+ const { secretSlots: _previousSecretSlots, ...previousFile } = prev;
4981
+ byPath.set(identity, {
4982
+ ...previousFile,
4983
+ content: JSON.stringify(merged, null, 2),
4984
+ ...secretSlots.length > 0 ? { mode: 384 } : {},
4985
+ ...secretSlots.length === 0 ? {} : { secretSlots }
4986
+ });
4987
+ continue;
4988
+ } catch {}
4989
+ byPath.set(identity, f);
4990
+ }
4991
+ return [...byPath.values()];
4992
+ }
4993
+ function normalizePlanFileRoot(root) {
4994
+ if (root === void 0 || root === "workspace") return "workspace";
4995
+ if (root === "agent") return root;
4996
+ throw new Error(`Unsupported workspace plan file root: ${String(root)}`);
4997
+ }
4998
+ const sha256 = (value) => createHash("sha256").update(value, "utf8").digest("hex");
4999
+ const tomlStr = (s) => JSON.stringify(s);
5000
+ function isProfilePublicConfigValue(value) {
5001
+ return typeof value === "object" && value !== null && !Array.isArray(value) && value.kind === "public" && typeof value.value === "string";
5002
+ }
5003
+ function isProfileSecretRef(value) {
5004
+ return typeof value === "object" && value !== null && !Array.isArray(value) && value.kind === "secret-ref" && typeof value.key === "string";
5005
+ }
5006
+ function workspacePlanConfigValue(value) {
5007
+ return isProfilePublicConfigValue(value) ? value.value : { ...value };
5008
+ }
5009
+ function serializeWorkspacePlanJson(value) {
5010
+ const secretSlots = [];
5011
+ const lower = (current, path, arrayEntry = false) => {
5012
+ if (isProfilePublicConfigValue(current)) return current.value;
5013
+ if (isProfileSecretRef(current)) {
5014
+ secretSlots.push({
5015
+ path: [...path],
5016
+ ref: { ...current }
5017
+ });
5018
+ return null;
5019
+ }
5020
+ if (Array.isArray(current)) return current.map((entry, index) => lower(entry, [...path, index], true));
5021
+ if (current && typeof current === "object") {
5022
+ const output = Object.create(null);
5023
+ for (const [key, entry] of Object.entries(current)) {
5024
+ const lowered = lower(entry, [...path, key]);
5025
+ if (lowered !== void 0) Object.defineProperty(output, key, {
5026
+ value: lowered,
5027
+ enumerable: true,
5028
+ configurable: true,
5029
+ writable: true
5030
+ });
5031
+ }
5032
+ return output;
5033
+ }
5034
+ return current === void 0 && arrayEntry ? null : current;
5035
+ };
5036
+ const content = JSON.stringify(lower(value, []), null, 2);
5037
+ if (content === void 0) throw new Error("Generated profile JSON must have a serializable root");
5038
+ return {
5039
+ content,
5040
+ ...secretSlots.length === 0 ? {} : { secretSlots }
5041
+ };
5042
+ }
5043
+ function workspacePlanArgumentSegments(value) {
5044
+ return typeof value === "string" ? [value] : [...value.segments];
5045
+ }
5046
+ function concatWorkspacePlanArguments(...values) {
5047
+ const segments = values.flatMap(workspacePlanArgumentSegments);
5048
+ if (segments.every((segment) => typeof segment === "string")) return segments.join("");
5049
+ return {
5050
+ kind: "workspace-plan-argument-template",
5051
+ segments
5052
+ };
5053
+ }
5054
+ function joinWorkspacePlanArguments(values, separator) {
5055
+ if (values.length === 0) return "";
5056
+ const joined = [];
5057
+ for (const [index, value] of values.entries()) {
5058
+ if (index > 0) joined.push(separator);
5059
+ joined.push(value);
5060
+ }
5061
+ return concatWorkspacePlanArguments(...joined);
5062
+ }
5063
+ function tomlProfileConfigValue(value) {
5064
+ if (isProfilePublicConfigValue(value)) return tomlStr(value.value);
5065
+ return {
5066
+ kind: "workspace-plan-argument-template",
5067
+ segments: [{
5068
+ kind: "secret",
5069
+ ref: { ...value },
5070
+ encoding: "json-string"
5071
+ }]
5072
+ };
5073
+ }
5074
+ const ERROR_CATALOG = {
5075
+ VALIDATION_ERROR: "400 final | The request is malformed or a field is invalid. | Fix the field the message names and send the request again.",
5076
+ INVALID_REQUEST: "400 final | The request is malformed or a field is invalid. | Fix the field the message names and send the request again.",
5077
+ INVALID_TEXT_PART: "400 final | A text part is missing its text or is not base64-encoded UTF-8. | Base64-encode every text part, then send the request again.",
5078
+ UNAUTHORIZED: "401 final | The credential is missing, invalid or expired. | Sign in again or send a valid API key.",
5079
+ PAYMENT_REQUIRED: "402 final | The account has no balance, credit or plan for this request. | Add credit or a paid seat at https://id.tangle.tools/app/billing, then retry.",
5080
+ FORBIDDEN: "403 final | The caller is authenticated but not allowed to do this. | Use a credential with the role or scope the message names.",
5081
+ FEATURE_DISABLED: "403 final | This capability is switched off for this deployment or account. | Ask the operator to enable it.",
5082
+ NOT_FOUND: "404 final | The resource does not exist or this account cannot see it. | Check the id and the account or team that owns it.",
5083
+ SIDECAR_NOT_FOUND: "404 final | The sandbox runtime does not exist or this account cannot see it. | Check the sandbox id, or create the sandbox again.",
5084
+ CONFLICT: "409 final | The request conflicts with an existing resource or an earlier request. | Read the existing resource, or use a new name or idempotency key.",
5085
+ STALE_STATE: "409 final | The caller's view of the resource is stale. | Read the resource again and repeat the request against its current state.",
5086
+ INVALID_STATE: "409 final | The resource is in the wrong state for this operation. | Bring it to the state the message names, then retry.",
5087
+ IN_PROGRESS: "409 retry | Another operation holds this resource. | Wait for that operation to finish, then retry.",
5088
+ EGRESS_PROXY_RECOVERY_REQUIRED: "409 final | The egress proxy lost the credentials it serves. | Recreate the sandbox to rematerialize its egress credentials.",
5089
+ EGRESS_PROXY_SECRETS_UNAVAILABLE: "409 final | The egress proxy rebuild found no value for secrets the box still references. | Send the missing secrets the response names in one retry, or recreate the sandbox.",
5090
+ EGRESS_IN_PLACE_RELOAD_UNAVAILABLE: "409 final | The egress proxy cannot be re-keyed without a restart. | Re-key once no agent turn is streaming, allowing a proxy restart.",
5091
+ EXPIRED: "410 final | The token, decision or grant has expired. | Request a new one.",
5092
+ PAYLOAD_TOO_LARGE: "413 final | The body or artifact is over its size limit. | Send a smaller body, or split it.",
5093
+ NOT_CONNECTED: "424 final | A required integration connection is missing. | Connect the integration the message names, then retry.",
5094
+ QUOTA_EXCEEDED: "429 final | A plan or concurrency quota is reached. | Stop or delete resources, or raise the quota.",
5095
+ RATE_LIMITED: "429 retry | Too many requests in the current window. | Wait for the Retry-After interval, then retry.",
5096
+ RATE_LIMIT_EXCEEDED: "429 retry | Too many requests in the current window. | Wait for the Retry-After interval, then retry.",
5097
+ INTERNAL_ERROR: "500 final | The server failed for a reason it did not classify. | Report the request id; the request itself did not cause it.",
5098
+ OPERATION_FAILED: "500 final | A server-side operation failed. | Report the request id with the operation the message names.",
5099
+ CONFIGURATION_ERROR: "500 final | The deployment is missing configuration or has an invalid value. | The operator sets the configuration key the message names.",
5100
+ AGENT_EXECUTION_FAILED: "500 final | The agent run failed inside the sandbox. | Read the cause in the message; fix the prompt, model or credential it names.",
5101
+ BACKEND_START_FAILED: "500 final | The agent backend cannot start, and a retry fails the same way. | Fix the configuration, credential or session the cause names.",
5102
+ MESSAGE_RETRIEVAL_FAILED: "500 final | Message storage cannot serve this read. | Report the request id; the stored session needs repair.",
5103
+ UNSUPPORTED: "501 final | This operation is not supported for this runtime, harness or driver. | Choose a runtime or option that supports it.",
5104
+ UPSTREAM_ERROR: "502 retry | An upstream service failed or answered outside its contract. | Retry with backoff; report the request id if it persists.",
5105
+ UNAVAILABLE: "503 retry | A dependency or capacity is temporarily unavailable. | Retry after the Retry-After interval.",
5106
+ NOT_READY: "503 retry | The target is starting, restarting, recovering or draining. | Retry after the Retry-After interval.",
5107
+ BACKEND_UNAVAILABLE: "503 retry | The agent backend did not answer. | Retry after the Retry-After interval.",
5108
+ MESSAGE_RETRIEVAL_UNAVAILABLE: "503 retry | Message storage did not answer. | Retry after the Retry-After interval.",
5109
+ TIMEOUT: "504 retry | The operation exceeded its deadline. | Retry; if it repeats, raise the timeout or split the work.",
5110
+ KV_VALUE_TOO_LARGE: "413 final | A workflow KV value is over the per-value size cap. | Store a smaller value, or put the data in an artifact and keep its id in KV.",
5111
+ KV_KEY_LIMIT: "409 final | The workflow has reached its KV key cap. | Delete keys the workflow no longer reads, then write again.",
5112
+ KV_VERSION_CONFLICT: "409 final | Another writer changed the KV key since it was read. | Read the key again and retry the compare-and-swap against its current version.",
5113
+ PRECONDITION_FAILED: "412 final | The stored version no longer matches the request's precondition. | Read the current version or etag and send it with the request.",
5114
+ UNPROCESSABLE: "422 final | The input has nothing usable for this operation. | Record the history the message names, then ask again.",
5115
+ BASE_IMAGE_NOT_FOUND: "400 final | The requested image does not exist. | Check the image name and tag, then create again.",
5116
+ BASE_IMAGE_MISSING_BEFORE_CREATE: "400 final | The requested image does not exist; the host proved it before creating anything. | Check the image name and tag, then create again.",
5117
+ UNSUPPORTED_EGRESS_POLICY: "400 final | This runtime cannot enforce the requested egress policy. | Choose a policy the runtime supports, or another runtime.",
5118
+ UNSUPPORTED_FOR_RUNTIME: "400 final | The requested runtime cannot honour a create input. | Remove the input the message names, or choose another runtime.",
5119
+ ROOT_USER_FORBIDDEN: "403 final | The sandbox may not run as root. | Run the workload as a non-root user.",
5120
+ EGRESS_DOMAIN_NOT_ALLOWED: "403 final | The sandbox egress allowlist does not include this host. | Add the host to egressPolicy.allowDomains with box.egress.update.",
5121
+ EGRESS_REQUEST_REFUSED: "403 final | The sandbox egress policy refused this request. | Read box.egress.denials() for the rule that refused it.",
5122
+ NOT_MANAGED: "404 final | This host does not manage the named container. | Check the sandbox id; the platform resolves its host again on retry.",
5123
+ SNAPSHOT_NOT_FOUND: "404 final | The snapshot does not exist or this account cannot see it. | List the sandbox snapshots and use an id from that list.",
5124
+ BRANCH_PARENT_NOT_RUNNING: "409 final | The branch parent is not running. | Resume the parent sandbox, then branch again.",
5125
+ CONTAINER_RESERVATION_CONFLICT: "409 retry | Another lifecycle operation holds this sandbox. | Wait for that operation to finish, then retry.",
5126
+ CONTAINER_NETWORK_MISSING: "409 final | The stopped sandbox lost its network, so it cannot start in place; its files remain. | Resume the sandbox so the platform recreates it.",
5127
+ EGRESS_DISABLED: "409 final | Egress is not enabled on this host. | Place the sandbox on a host with egress enabled.",
5128
+ NATIVE_CAPTURE_UNAVAILABLE: "409 final | The host cannot prove the native capture image this create requires. | Retry on another host, or create without native capture.",
5129
+ NETWORK_ISOLATION_REQUIRED: "409 final | The create requires its own network, and the host did not place one. | Retry on a host that supports network isolation.",
5130
+ SESSION_CLAIM_MISMATCH: "409 final | The request names a session other than the one bound to this container. | Use the session id the container was created for.",
5131
+ SNAPSHOT_NOT_SYNCED: "409 retry | The snapshot has not finished uploading. | Retry after the upload completes.",
5132
+ WARM_CLAIM_REMOVED: "409 final | Another lifecycle operation removed the claimed warm sandbox. | Create the sandbox again.",
5133
+ WORKSPACE_STORAGE_MISSING: "409 final | The stopped sandbox storage is gone or replaced, so the host refused to start it. | Restore the sandbox from a snapshot.",
5134
+ RESTORE_QUOTA_EXCEEDED: "413 final | The snapshot is larger than the workspace quota. | Create with a larger disk, or restore a smaller snapshot.",
5135
+ GIT_CLONE_REFUSED: "422 final | The repository refused the clone credential, or the credential cannot see it. | Fix the git credential or repository URL, then create again.",
5136
+ BRANCH_FAILED: "500 final | The live branch of a running sandbox failed. | Report the request id; branch from a snapshot instead.",
5137
+ CONTAINER_START_FAILED: "500 retry | The host started the sandbox and its runtime failed. | Retry; if it repeats, recreate the sandbox from a snapshot.",
5138
+ GIT_CLONE_FAILED: "500 retry | Cloning the repository failed. | Retry; if it repeats, check that the repository URL is reachable.",
5139
+ GIT_CLONE_TIMEOUT: "500 retry | Cloning the repository exceeded its deadline. | Retry, or clone a smaller repository.",
5140
+ HOST_CLEANUP_UNCONFIRMED: "500 retry | The host cannot prove it removed what a failed create made. | Retry; the platform reconciles the earlier attempt first.",
5141
+ HOST_RESERVATION_COMMIT_FAILED: "500 retry | The host could not record the create after cleaning it up. | Retry the create.",
5142
+ MISSING_SIDECAR_AUTH_TOKEN: "500 final | The sandbox has no runtime auth token, so its host cannot route to it. | Recreate the sandbox.",
5143
+ SNAPSHOT_RESTORE_FAILED: "500 final | Restoring the snapshot into the sandbox failed; no empty workspace was served. | Report the request id, or restore another snapshot.",
5144
+ VM_START_FAILED: "500 retry | The microVM failed to start. | Retry; if it repeats, recreate the sandbox.",
5145
+ SIDECAR_UPSTREAM_UNAVAILABLE: "502 retry | The host could not reach the sandbox runtime. | Retry; the request may have reached the sandbox.",
5146
+ BRANCH_UFFD_UNAVAILABLE: "503 retry | The parent host cannot fork live memory now. | Retry, or branch from a snapshot.",
5147
+ CAPACITY_EXHAUSTED: "503 retry | No host has room for this sandbox now. | Retry after the Retry-After interval.",
5148
+ COMPLIANCE_CAPACITY_UNAVAILABLE: "503 retry | No verified compliance-scope host can take this sandbox now. | Retry after the Retry-After interval.",
5149
+ FIRECRACKER_IMAGE_UNAVAILABLE: "503 final | No host carries the requested Firecracker image. | Choose an image the Firecracker hosts carry, or the Docker runtime.",
5150
+ HOST_UNAVAILABLE: "503 retry | The host did not answer; the sandbox and its files remain. | Retry after the Retry-After interval.",
5151
+ HOST_PRESSURE: "503 retry | The host was too busy to create the sandbox and created nothing. | Retry after the Retry-After interval.",
5152
+ IN_BOX_DOCKER_UNAVAILABLE: "503 retry | Docker inside the sandbox is not available. | Retry, or create the sandbox with in-box Docker enabled.",
5153
+ NO_IP: "503 retry | The sandbox has no network address yet. | Retry after the Retry-After interval.",
5154
+ ROUTE_LOOKUP_FAILED: "503 retry | The host could not look up the sandbox route. | Retry after the Retry-After interval.",
5155
+ SNAPSHOT_STORAGE_UNAVAILABLE: "503 retry | Snapshot storage did not answer. | Retry after the Retry-After interval.",
5156
+ THIN_POOL_HEADROOM: "503 final | The sandbox host cannot grow this workspace. | Recreate the sandbox from a snapshot so it lands on another host.",
5157
+ WARM_RECONNECT_MISS: "503 retry | The warm restore path is unavailable. | Retry; the platform restores through the cold path.",
5158
+ WORKSPACE_IMAGE_BUILDER_BUSY: "503 retry | The workspace image builder is busy. | Retry after the Retry-After interval.",
5159
+ WORKSPACE_IMAGE_BUILDER_UNAVAILABLE: "503 retry | The workspace image builder is unavailable. | Retry after the Retry-After interval.",
5160
+ SIDECAR_HEALTH_TIMEOUT: "504 retry | The sandbox runtime did not become ready within its boot attempts. | Retry; if it repeats, recreate the sandbox.",
5161
+ rate_limit_error: "429 retry | The model provider rate-limited this turn. | Wait for the provider's window, then send the turn again.",
5162
+ provider_quota_exhausted: "429 final | The harness subscription quota is spent until its resetAt. | Wait until resetAt, or send the turn with another credential.",
5163
+ native_api_error: "502 final | The harness's model API refused the turn; the message carries its answer. | Fix what the provider's answer names, then send the turn again.",
5164
+ empty_visible_output: "502 retry | The turn ended without visible output from the model. | Send the turn again; if it repeats, change the model or the prompt.",
5165
+ session_rehydration_failed: "409 final | The session's stored transcript cannot be replayed into a new harness session. | Start a new session; this one cannot resume.",
5166
+ SESSION_DIED: "500 final | The harness session process died during the turn; the message says why. | Send the turn again in a new session.",
5167
+ MEMORY_LIMIT_KILLED: "500 final | The harness ran out of memory and was killed. | Give the sandbox more memory or split the work, then send the turn again.",
5168
+ PROCESS_OUTPUT_GAP: "410 final | A process log reader fell behind the spool, so output was evicted before it was read. | Read faster or redirect output to a file; missedBytes says how much.",
5169
+ SESSION_CREDENTIAL_NOT_RETAINED: "409 final | A restored session's model credential is not kept in session storage. | Send the model credential with the turn.",
5170
+ interaction_kind_unsupported: "400 final | The turn asks for an interaction kind this harness cannot originate. | Drop the interaction toggle or choose a harness that supports it.",
5171
+ invalid_attachment: "400 final | An attachment has no url or path, or content the harness cannot take. | Fix the attachment the message names, then send the turn again.",
5172
+ PROFILE_UNSUPPORTED: "422 final | The profile asks for controls its harness cannot run, so no box is worth starting. | Remove the controls the message names, or choose a harness that runs them.",
5173
+ PROFILE_NOT_CACHED: "409 final | The turn names a profile by hash that this runtime does not hold. | Send the full profile object instead of its hash.",
5174
+ MODEL_CALL_LIMIT_REACHED: "400 final | The bounded turn needed more model calls than it allowed. | Raise the turn's model-call limit or split the task.",
5175
+ MODEL_CALL_LIMIT_UNSUPPORTED: "400 final | This harness's model calls cannot be counted, so a call limit cannot hold. | Drop the limit or choose a harness that supports it.",
5176
+ TOOL_DISABLED_TURN_UNSUPPORTED: "400 final | This harness cannot run a turn with its tools disabled. | Allow tools, or choose a harness that supports tool-free turns.",
5177
+ EXECUTION_TTL_EXPIRED: "504 final | The execution ran past its time limit and was stopped. | Raise ttlMs up to the deployment ceiling, or split the work.",
5178
+ EXECUTION_TTL_EXCEEDS_LIMIT: "400 final | The requested execution time limit is above this deployment's ceiling. | Send a ttlMs at or below the ceiling the message names.",
5179
+ MESSAGE_ADMISSION_EXPIRED: "409 final | The message's admission deadline passed before the harness was invoked. | Dispatch the message again with a new deadline.",
5180
+ BACKEND_HARNESS_CONFLICT: "400 final | Running the turn would run a harness other than the one the caller named. | Name one harness for the session and its turns.",
5181
+ HARNESS_MODEL_UNSUPPORTED: "400 final | The named harness cannot run the named model. | Choose a model the harness supports, or another harness.",
5182
+ HARNESS_RUNTIME_UNAVAILABLE: "503 retry | The harness's local daemon exited before it could serve the session. | Retry after the Retry-After interval; the message carries the daemon's reason.",
5183
+ GPU_PROVIDER_NOT_CONFIGURED: "503 final | No GPU provider is configured for this deployment. | Create the sandbox without a GPU, or ask the operator to configure a provider.",
5184
+ COMPLIANCE_NOT_ENTITLED: "403 final | The account is not entitled to the requested compliance placement. | Enable the compliance plan for the account, or create without it.",
5185
+ COMPLIANCE_CELL_UNAVAILABLE: "503 final | No cell serves the requested compliance placement. | Choose another region or compliance mode, or ask the operator.",
5186
+ NETWORK_ERROR: "503 retry | The request did not reach the platform, or its answer was lost. | Check connectivity, then retry; a keyed create joins its earlier attempt.",
5187
+ EXECUTION_INTERRUPTED: "503 retry | The sandbox runtime restarted during the run, before the run produced a terminal event; the run cannot resume. | Run the turn again.",
5188
+ STREAM_INTERRUPTED: "503 retry | The execution's stream ended without its terminal event; its outcome is unknown. | Rejoin with its executionId and lastEventId, or read the session status.",
5189
+ PUBLIC_PROFILE_PIN_REFUSED: "400 final | The runtime refused the pinned public profile revision this turn named. | Send the turn with the revision and digest the profile has now.",
5190
+ model_credential_refused: "403 final | The account owner refused the model credential for this seat. | Reconnect or replace that seat's credential, or choose another seat.",
5191
+ TEMPLATE_PUBLICATION_WAIT_INTERRUPTED: "504 retry | The SDK stopped waiting for a template publication; the job keeps running. | Resume the wait with resumeJobId instead of publishing again."
5192
+ };
5193
+ function catalogEntry(code) {
5194
+ const [head = "", cause = "", nextStep = ""] = ERROR_CATALOG[code].split(" | ");
5195
+ return {
5196
+ code,
5197
+ status: Number(head.slice(0, 3)),
5198
+ retryable: head.endsWith("retry"),
5199
+ cause,
5200
+ nextStep,
5201
+ docs: `https://sandbox.tangle.tools/docs/errors#${code.toLowerCase()}`
5202
+ };
5203
+ }
5204
+ /**
5205
+ * The one error class. The catalog gives the status, retryability and next
5206
+ * step; the message names this occurrence's cause.
5207
+ */
5208
+ var CatalogError = class extends Error {
5209
+ code;
5210
+ details;
5211
+ statusCode;
5212
+ retryable;
5213
+ nextStep;
5214
+ constructor(code, message, details) {
5215
+ super(message);
5216
+ this.code = code;
5217
+ this.details = details;
5218
+ const entry = catalogEntry(code);
5219
+ this.statusCode = entry.status;
5220
+ this.retryable = entry.retryable;
5221
+ this.nextStep = entry.nextStep;
5222
+ this.name = this.constructor.name;
5223
+ }
5224
+ /** The `{ success: false, error }` response envelope. */
5225
+ toJSON() {
5226
+ return {
5227
+ success: false,
5228
+ error: {
5229
+ code: this.code,
5230
+ message: this.message,
5231
+ details: this.details
5232
+ }
5233
+ };
5234
+ }
5235
+ };
5236
+ function formatUnsupported(unsupported) {
5237
+ return `Unable to materialize ${unsupported.length} profile resource(s):\n${unsupported.map(({ dimension, reason }) => `- ${dimension}: ${reason}`).join("\n")}`;
5238
+ }
5239
+ /** A profile asks for controls its harness cannot run: the caller's fault, 422, never worth a retry. */
5240
+ var ProfileUnsupportedError = class extends CatalogError {
5241
+ owner = "caller";
5242
+ status = 422;
5243
+ constructor(unsupported) {
5244
+ super("PROFILE_UNSUPPORTED", formatUnsupported(unsupported), { unsupported });
5245
+ this.unsupported = unsupported;
5246
+ }
5247
+ };
5248
+ /** Fail when a profile asks for controls the chosen harness cannot execute. */
5249
+ function assertWorkspacePlanSupported(plan) {
5250
+ if (plan.unsupported.length > 0) throw new ProfileUnsupportedError(plan.unsupported);
5251
+ }
5252
+ /**
5253
+ * Enforce supportability under the profile's failOnError policy.
5254
+ * Strict mode throws; best-effort mode returns visible warnings.
5255
+ */
5256
+ function enforceWorkspacePlanSupport(plan, failOnError) {
5257
+ if (failOnError !== false) {
5258
+ assertWorkspacePlanSupported(plan);
5259
+ return [];
5260
+ }
5261
+ return plan.unsupported.map(({ dimension, reason }) => `${dimension}: ${reason}`);
5262
+ }
5263
+ function createProfilePlanBuilder(harness) {
5264
+ const plan = {
5265
+ harness,
5266
+ files: [],
5267
+ env: {},
5268
+ flags: [],
5269
+ unsupported: [],
5270
+ requires: []
5271
+ };
5272
+ const pushPlanFile = (relPath, serialized, source, mode, root = "workspace") => {
5273
+ const normalizedPath = normalizeWorkspaceRelativePath(relPath);
5274
+ const content = typeof serialized === "string" ? serialized : serialized.content;
5275
+ if (harness === "opencode" && OPENCODE_CONFIG.test(normalizedPath) && SUBSTITUTION.test(content)) throw new Error(`Profile value ${normalizedPath}:${substituted(parseLoosely(content))} holds an OpenCode {env:} or {file:} substitution; use a secret-ref`);
5276
+ const secretSlots = typeof serialized === "string" ? void 0 : serialized.secretSlots;
5277
+ const fileMode = mode ?? (secretSlots !== void 0 && secretSlots.length > 0 ? 384 : void 0);
5278
+ plan.files.push({
5279
+ relPath: normalizedPath,
5280
+ content,
5281
+ source,
5282
+ ...root === "workspace" ? {} : { root },
5283
+ ...source === "generated" && isMaterializerOwnedPath(normalizedPath) ? { ownership: "materializer" } : {},
5284
+ ...fileMode === void 0 ? {} : { mode: validateFileMode(fileMode) },
5285
+ ...secretSlots === void 0 ? {} : { secretSlots: secretSlots.map((slot) => ({
5286
+ path: [...slot.path],
5287
+ ref: { ...slot.ref }
5288
+ })) }
5289
+ });
5290
+ };
5291
+ const add = (relPath, content, mode) => pushPlanFile(relPath, content, "generated", mode);
5292
+ const addAtRoot = (root, relPath, content, mode) => pushPlanFile(relPath, content, "generated", mode, root);
5293
+ const unsupported = (dimension, reason) => plan.unsupported.push({
5294
+ dimension,
5295
+ reason
5296
+ });
5297
+ const explicitResourcePaths = /* @__PURE__ */ new Map();
5298
+ const addExplicitResource = (dimension, relPath, content, mode) => {
5299
+ const normalizedPath = normalizeWorkspaceRelativePath(relPath);
5300
+ const previousDimension = explicitResourcePaths.get(normalizedPath);
5301
+ if (previousDimension) throw new Error(`Duplicate profile resource path: ${normalizedPath} (${previousDimension}, ${dimension})`);
5302
+ if (MATERIALIZER_RESERVED_PATHS.has(normalizedPath)) throw new Error(`Profile resource path is reserved by the materializer: ${normalizedPath} (${dimension}). This package writes that path itself and replaces it on re-application, so a mount there cannot survive; choose another path.`);
5303
+ explicitResourcePaths.set(normalizedPath, dimension);
5304
+ pushPlanFile(normalizedPath, content, "user", mode);
5305
+ };
5306
+ return {
5307
+ plan,
5308
+ add,
5309
+ addAtRoot,
5310
+ addExplicitResource,
5311
+ unsupported,
5312
+ finalize(failOnError) {
5313
+ for (const [relPath, dimension] of explicitResourcePaths) if (plan.files.filter((file) => (file.root ?? "workspace") === "workspace" && file.relPath === relPath).length > 1) throw new Error(`Profile ${dimension} resource conflicts with generated harness file: ${relPath}`);
5314
+ plan.files = mergeJsonFiles(plan.files).sort((a, b) => compareStrings(`${a.root ?? "workspace"}\0${a.relPath}`, `${b.root ?? "workspace"}\0${b.relPath}`));
5315
+ if (failOnError && plan.unsupported.length) throw new ProfileUnsupportedError(plan.unsupported);
5316
+ return plan;
5317
+ }
5318
+ };
5319
+ }
5320
+ /**
5321
+ * OpenCode expands `{env:NAME}` and `{file:path}` across its config text, so a
5322
+ * profile string there could send a native env var or readable file to a
5323
+ * server the profile names (#10257). Every profile value reaches an OpenCode
5324
+ * config here, before the materializer adds its own references.
5325
+ */
5326
+ const OPENCODE_CONFIG = /(?:^|\/)opencode\.jsonc?$/u;
5327
+ const SUBSTITUTION = /\{(?:env|file):/u;
5328
+ /** A config that does not parse (JSONC comments) is still refused; it reports the raw text. */
5329
+ function parseLoosely(text) {
5330
+ try {
5331
+ return JSON.parse(text);
5332
+ } catch {
5333
+ return text;
5334
+ }
5335
+ }
5336
+ /** The path of the first key or string OpenCode would substitute. */
5337
+ function substituted(value, at = "") {
5338
+ if (typeof value === "string") return SUBSTITUTION.test(value) ? at : void 0;
5339
+ if (value === null || typeof value !== "object") return void 0;
5340
+ for (const [key, entry] of Object.entries(value)) {
5341
+ const path = at ? `${at}.${key}` : key;
5342
+ const found = SUBSTITUTION.test(key) ? path : substituted(entry, path);
5343
+ if (found) return found;
5344
+ }
5345
+ }
5346
+ function setPlanEnvironment(plan, name, value) {
5347
+ const normalized = typeof value === "string" ? value : workspacePlanConfigValue(value);
5348
+ const previous = plan.env[name];
5349
+ if (previous !== void 0 && JSON.stringify(previous) !== JSON.stringify(normalized)) throw new Error(`profile environment values disagree for ${name}`);
5350
+ plan.env[name] = normalized;
5351
+ }
5352
+ function materializeHooks(h, hooks, add, unsupported, plan) {
5353
+ switch (h) {
5354
+ case "claude-code":
5355
+ add(CLAUDE_SETTINGS_PATH, settingsHooks(h, hooks, add, unsupported, plan));
5356
+ registerClaudeSettings(plan);
5357
+ break;
5358
+ case "nanoclaw":
5359
+ unsupported("hooks", "nanoclaw's chat bridge does not expose Claude Code hook settings to the spawned agent");
5360
+ break;
5361
+ case "gemini":
5362
+ add(".gemini/settings.json", settingsHooks(h, hooks, add, unsupported, plan));
5363
+ break;
5364
+ case "codex":
5365
+ for (const [event, cmds] of Object.entries(hooks).sort(([left], [right]) => compareStrings(left, right))) {
5366
+ if (!hookEventSupported("codex", event)) {
5367
+ unsupported("hooks", `codex: unsupported hook event "${event}"`);
5368
+ continue;
5369
+ }
5370
+ if (cmds.some((command) => command.blocking === false)) {
5371
+ unsupported("hooks", `codex: hook event "${event}" cannot execute asynchronous commands`);
5372
+ continue;
5373
+ }
5374
+ const entries = cmds.map((command) => {
5375
+ const handler = [
5376
+ `type = ${tomlStr("command")}`,
5377
+ `command = ${tomlStr(materializedHookCommand(event, command, add, plan))}`,
5378
+ ...command.timeoutMs ? [`timeout = ${timeoutSeconds(command.timeoutMs)}`] : []
5379
+ ];
5380
+ return `{ matcher = ${tomlStr(command.matcher ?? "*")}, hooks = [{ ${handler.join(", ")} }] }`;
5381
+ });
5382
+ plan.flags.push("-c", `hooks.${event}=[${entries.join(", ")}]`);
5383
+ }
5384
+ break;
5385
+ case "opencode":
5386
+ unsupported("hooks", "opencode hooks require executable JS/TS plugins; command hooks cannot be translated exactly");
5387
+ break;
5388
+ case "kimi-code":
5389
+ unsupported("hooks", "kimi hooks are [[hooks]] in the config TOML loaded via --config-file, not cwd — pass --config-file");
5390
+ break;
5391
+ case "pi":
5392
+ unsupported("hooks", "pi hooks are TS extensions (.pi/extensions/*.ts) — build an extension");
5393
+ break;
5394
+ case "prime":
5395
+ unsupported("hooks", "prime hooks are TS extensions (fork core/extensions), not command hooks — build an extension");
5396
+ break;
5397
+ case "hermes":
5398
+ unsupported("hooks", "hermes project plugins do not expose an exact command-hook mapping");
5399
+ break;
5400
+ case "openclaw":
5401
+ unsupported("hooks", "openclaw hooks are DISABLED by default — enable in ~/.openclaw/openclaw.json; cwd hooks/ alone is a no-op");
5402
+ break;
5403
+ }
5404
+ }
5405
+ /** Settings `hooks{}`: event → [{matcher, hooks: [{type: "command", …}]}]. */
5406
+ function settingsHooks(h, hooks, add, unsupported, plan) {
5407
+ const settings = {};
5408
+ for (const [event, cmds] of Object.entries(hooks)) {
5409
+ if (!hookEventSupported(h, event)) {
5410
+ unsupported("hooks", `${h}: unsupported hook event "${event}"`);
5411
+ continue;
5412
+ }
5413
+ if (h === "gemini" && cmds.some((c) => c.blocking === false)) unsupported("hooks", `gemini: hook event "${event}" does not support non-blocking commands`);
5414
+ settings[event] = cmds.map((c) => ({
5415
+ matcher: c.matcher ?? "*",
5416
+ hooks: [{
5417
+ type: "command",
5418
+ command: materializedHookCommand(event, c, add, plan),
5419
+ ...c.timeoutMs ? { timeout: h === "gemini" ? c.timeoutMs : timeoutSeconds(c.timeoutMs) } : {},
5420
+ ...h === "claude-code" && c.blocking === false ? { async: true } : {}
5421
+ }]
5422
+ }));
5423
+ }
5424
+ return serializeWorkspacePlanJson({ hooks: settings });
5425
+ }
5426
+ function registerClaudeSettings(plan) {
5427
+ if (!plan.flags.some((flag, at) => flag === "--settings" && plan.flags[at + 1] === ".tangle/claude-settings.json")) plan.flags.push("--settings", CLAUDE_SETTINGS_PATH);
5428
+ }
5429
+ const CLAUDE_HOOK_EVENTS = new Set([
5430
+ "ConfigChange",
5431
+ "CwdChanged",
5432
+ "Elicitation",
5433
+ "ElicitationResult",
5434
+ "FileChanged",
5435
+ "InstructionsLoaded",
5436
+ "MessageDisplay",
5437
+ "Notification",
5438
+ "PermissionDenied",
5439
+ "PermissionRequest",
5440
+ "PostCompact",
5441
+ "PostToolBatch",
5442
+ "PostToolUse",
5443
+ "PostToolUseFailure",
5444
+ "PreCompact",
5445
+ "PreToolUse",
5446
+ "SessionEnd",
5447
+ "SessionStart",
5448
+ "Setup",
5449
+ "Stop",
5450
+ "StopFailure",
5451
+ "SubagentStart",
5452
+ "SubagentStop",
5453
+ "TaskCompleted",
5454
+ "TaskCreated",
5455
+ "TeammateIdle",
5456
+ "UserPromptExpansion",
5457
+ "UserPromptSubmit",
5458
+ "WorktreeCreate",
5459
+ "WorktreeRemove"
5460
+ ]);
5461
+ const CODEX_HOOK_EVENTS = new Set([
5462
+ "PermissionRequest",
5463
+ "PostCompact",
5464
+ "PostToolUse",
5465
+ "PreCompact",
5466
+ "PreToolUse",
5467
+ "SessionStart",
5468
+ "Stop",
5469
+ "SubagentStart",
5470
+ "SubagentStop",
5471
+ "UserPromptSubmit"
5472
+ ]);
5473
+ const GEMINI_HOOK_EVENTS = new Set([
5474
+ "AfterAgent",
5475
+ "AfterModel",
5476
+ "AfterTool",
5477
+ "BeforeAgent",
5478
+ "BeforeModel",
5479
+ "BeforeTool",
5480
+ "BeforeToolSelection",
5481
+ "Notification",
5482
+ "PreCompress",
5483
+ "SessionEnd",
5484
+ "SessionStart"
5485
+ ]);
5486
+ function hookEventSupported(harness, event) {
5487
+ switch (harness) {
5488
+ case "claude-code": return CLAUDE_HOOK_EVENTS.has(event);
5489
+ case "codex": return CODEX_HOOK_EVENTS.has(event);
5490
+ case "gemini": return GEMINI_HOOK_EVENTS.has(event);
5491
+ default: return false;
5492
+ }
5493
+ }
5494
+ function timeoutSeconds(timeoutMs) {
5495
+ return Math.max(1, Math.ceil(timeoutMs / 1e3));
5496
+ }
5497
+ function materializedHookCommand(event, command, add, plan) {
5498
+ if (!command.env || Object.keys(command.env).length === 0) return command.command;
5499
+ const wrapperId = canonicalCandidateDigest({
5500
+ event,
5501
+ command: command.command,
5502
+ env: Object.fromEntries(Object.entries(command.env).sort(([left], [right]) => compareStrings(left, right)))
5503
+ }).slice(7);
5504
+ const path = `.tangle/profile-hooks/${wrapperId}.mjs`;
5505
+ const envSources = Object.fromEntries(Object.entries(command.env).sort(([left], [right]) => compareStrings(left, right)).map(([name, value]) => {
5506
+ const sourceName = `TANGLE_PROFILE_HOOK_${sha256(`${wrapperId}\0${name}`).slice(0, 24).toUpperCase()}`;
5507
+ setPlanEnvironment(plan, sourceName, value);
5508
+ return [name, sourceName];
5509
+ }));
5510
+ add(path, hookWrapperSource("/bin/sh", ["-c", command.command], {}, envSources));
5511
+ return `node ${path}`;
5512
+ }
5513
+ function hookWrapperSource(executable, args, extraEnv, envSources) {
5514
+ if (envSources !== void 0 && Object.keys(extraEnv).length > 0) throw new Error("Hook wrapper cannot mix inline environment values and sources");
5515
+ return [
5516
+ "import { spawnSync } from \"node:child_process\"",
5517
+ `const executable = ${JSON.stringify(executable)}`,
5518
+ `const args = ${JSON.stringify(args)}`,
5519
+ ...envSources === void 0 ? [`const extraEnv = ${JSON.stringify(extraEnv)}`] : [
5520
+ `const envSources = ${JSON.stringify(envSources)}`,
5521
+ "const extraEnv = {}",
5522
+ "for (const [name, source] of Object.entries(envSources)) {",
5523
+ " const value = process.env[source]",
5524
+ " if (value === undefined) {",
5525
+ " console.error(\"missing materialized hook environment \" + source)",
5526
+ " process.exit(127)",
5527
+ " }",
5528
+ " extraEnv[name] = value",
5529
+ "}"
5530
+ ],
5531
+ "const result = spawnSync(executable, args, {",
5532
+ " stdio: \"inherit\",",
5533
+ " env: { ...process.env, ...extraEnv },",
5534
+ " shell: false,",
5535
+ "})",
5536
+ "if (result.error) {",
5537
+ " console.error(result.error.message)",
5538
+ " process.exit(127)",
5539
+ "}",
5540
+ "if (result.signal) {",
5541
+ " console.error(\"hook terminated by \" + result.signal)",
5542
+ " process.exit(1)",
5543
+ "}",
5544
+ "process.exit(result.status ?? 1)",
5545
+ ""
5546
+ ].join("\n");
5547
+ }
3287
5548
  new TextDecoder("utf-8", {
3288
5549
  fatal: true,
3289
5550
  ignoreBOM: true
3290
5551
  });
3291
- Object.values({
5552
+ /**
5553
+ * The {@link BINDABLE_LAUNCH_CONTROLS} the plan HANDS OVER rather than executes,
5554
+ * because only the harness's own configuration reaches them: opencode's
5555
+ * `agent.<name>.prompt`, whose text arrives in
5556
+ * {@link WorkspacePlan.systemPromptBinding}.
5557
+ */
5558
+ const EXECUTOR_SYSTEM_PROMPT_BINDINGS = ["opencode.agent-prompt"];
5559
+ /** The only dimensions `skip` honors; any other is a loud rejection, never a silent no-op. */
5560
+ const SKIPPABLE_DIMENSIONS = ["mcp", "extensions"];
5561
+ const SKIPPABLE_DIMENSION_SET = new Set(SKIPPABLE_DIMENSIONS);
5562
+ function isSkippableDimension(value) {
5563
+ return SKIPPABLE_DIMENSION_SET.has(value);
5564
+ }
5565
+ /** Reject a dimension `materializeProfile` would not actually skip, rather than ignoring it. */
5566
+ function assertSkippableDimensions(skip) {
5567
+ if (!skip) return [];
5568
+ const unsupportedSkips = skip.filter((dimension) => !isSkippableDimension(dimension));
5569
+ if (unsupportedSkips.length > 0) throw new Error(`materializeProfile: cannot skip ${unsupportedSkips.join(", ")}. Skippable dimensions are: ${SKIPPABLE_DIMENSIONS.join(", ")}.`);
5570
+ return skip;
5571
+ }
5572
+ /**
5573
+ * Launcher controls an executor declares it OWNS via `binds`. Opencode's prompt
5574
+ * replacement binds to the one agent the process starter selects, so an
5575
+ * undeclared plan refuses it. `systemPrompt`: the executor applies plan flags
5576
+ * to its own spawn, so the plan writes a primary agent and selects it with
5577
+ * `--agent`. `opencode.agent-prompt`: the executor composes opencode's config,
5578
+ * so the plan hands the text over. The two are mutually exclusive.
5579
+ * `codex.developer-instructions`: instructions ride codex's additive channel.
5580
+ */
5581
+ const BINDABLE_LAUNCH_CONTROLS = [
5582
+ "systemPrompt",
5583
+ "codex.developer-instructions",
5584
+ ...EXECUTOR_SYSTEM_PROMPT_BINDINGS
5585
+ ];
5586
+ const BINDABLE_LAUNCH_CONTROL_SET = new Set(BINDABLE_LAUNCH_CONTROLS);
5587
+ /** Reject a binding declaration this materializer has no lowering for, rather than ignoring it. */
5588
+ function assertBindableLaunchControls(binds) {
5589
+ if (!binds) return /* @__PURE__ */ new Set();
5590
+ const unknown = binds.filter((control) => !BINDABLE_LAUNCH_CONTROL_SET.has(control));
5591
+ if (unknown.length > 0) throw new Error(`materializeProfile: cannot bind ${unknown.join(", ")}. Bindable launch controls are: ${BINDABLE_LAUNCH_CONTROLS.join(", ")}.`);
5592
+ const declared = new Set(binds);
5593
+ const handedOver = [...EXECUTOR_SYSTEM_PROMPT_BINDINGS].filter((control) => declared.has(control));
5594
+ if (declared.has("systemPrompt") && handedOver.length > 0) throw new Error(`materializeProfile: cannot bind systemPrompt together with ${handedOver.join(", ")}. The first says the plan's launch flags reach the spawn; the second says the caller composes the harness config itself and reads neither.`);
5595
+ return declared;
5596
+ }
5597
+ function normalizedControlName(name) {
5598
+ return name.replace(/[^a-zA-Z0-9_]/g, "").toLowerCase();
5599
+ }
5600
+ function nativeWebToolKind(name) {
5601
+ const posture = resolveNativeWebTools({ [name]: true });
5602
+ if (posture.search === true && posture.fetch === void 0) return "search";
5603
+ if (posture.fetch === true && posture.search === void 0) return "fetch";
5604
+ }
5605
+ const CLAUDE_TOOL_NAMES = {
3292
5606
  agent: "Agent",
3293
5607
  askuserquestion: "AskUserQuestion",
3294
5608
  bash: "Bash",
@@ -3304,7 +5618,679 @@ Object.values({
3304
5618
  webfetch: "WebFetch",
3305
5619
  websearch: "WebSearch",
3306
5620
  write: "Write"
3307
- }).sort();
5621
+ };
5622
+ /** Tool IDs accepted by Claude Code. */
5623
+ const CLAUDE_CODE_NATIVE_TOOL_IDS = Object.values(CLAUDE_TOOL_NAMES).sort();
5624
+ /** Permission IDs accepted by Claude Code (same as tool IDs). */
5625
+ const CLAUDE_CODE_NATIVE_PERMISSION_IDS = CLAUDE_CODE_NATIVE_TOOL_IDS;
5626
+ function claudeToolName(name) {
5627
+ const web = nativeWebToolKind(name);
5628
+ if (web === "search") return "WebSearch";
5629
+ if (web === "fetch") return "WebFetch";
5630
+ return CLAUDE_TOOL_NAMES[normalizedControlName(name)];
5631
+ }
5632
+ /** Tool IDs reported by the OpenCode binary shipped in the Sandbox image. */
5633
+ const OPENCODE_NATIVE_TOOL_IDS = [
5634
+ "apply_patch",
5635
+ "bash",
5636
+ "codesearch",
5637
+ "edit",
5638
+ "glob",
5639
+ "grep",
5640
+ "question",
5641
+ "read",
5642
+ "skill",
5643
+ "task",
5644
+ "todowrite",
5645
+ "webfetch",
5646
+ "websearch",
5647
+ "write"
5648
+ ];
5649
+ const OPENCODE_NATIVE_TOOL_ID_SET = new Set(OPENCODE_NATIVE_TOOL_IDS);
5650
+ /** Permission IDs accepted by OpenCode (tools except read, plus special permissions). */
5651
+ const OPENCODE_NATIVE_PERMISSION_IDS = [
5652
+ "apply_patch",
5653
+ "bash",
5654
+ "codesearch",
5655
+ "doom_loop",
5656
+ "edit",
5657
+ "external_directory",
5658
+ "glob",
5659
+ "grep",
5660
+ "mcp",
5661
+ "question",
5662
+ "skill",
5663
+ "task",
5664
+ "todowrite",
5665
+ "webfetch",
5666
+ "websearch",
5667
+ "write"
5668
+ ];
5669
+ /** Resolve portable and legacy profile names to current OpenCode tool IDs. */
5670
+ function openCodeNativeToolId(name) {
5671
+ const web = nativeWebToolKind(name);
5672
+ if (web === "search") return "websearch";
5673
+ if (web === "fetch") return "webfetch";
5674
+ const normalized = normalizedControlName(name);
5675
+ if (normalized === "patch") return "apply_patch";
5676
+ return OPENCODE_NATIVE_TOOL_ID_SET.has(normalized) ? normalized : void 0;
5677
+ }
5678
+ function openCodeToolName(name) {
5679
+ return openCodeNativeToolId(name);
5680
+ }
5681
+ function openCodePermissionName(name) {
5682
+ if (name.includes("*") || name.includes("?")) return void 0;
5683
+ const normalized = normalizedControlName(name);
5684
+ if (["write", "edit"].includes(normalized)) return "edit";
5685
+ const web = nativeWebToolKind(name);
5686
+ if (web === "search") return "websearch";
5687
+ if (web === "fetch") return "webfetch";
5688
+ if ([
5689
+ "bash",
5690
+ "mcp",
5691
+ "doom_loop",
5692
+ "external_directory"
5693
+ ].includes(normalized)) return normalized;
5694
+ return normalized !== "read" && OPENCODE_NATIVE_TOOL_ID_SET.has(normalized) ? normalized : void 0;
5695
+ }
5696
+ /** OpenCode 1.x registers MCP tools as sanitized server + "_" + tool.
5697
+ * Accept exact tools and a server-wide rule only for this profile's servers.
5698
+ * A generic permission spelling must never become a grant to an undeclared MCP.
5699
+ */
5700
+ function openCodeDeclaredMcpPermissionName(name, aliases) {
5701
+ const servers = aliases.map((alias) => ({
5702
+ alias,
5703
+ native: alias.replace(/[^a-zA-Z0-9_-]/g, "_")
5704
+ }));
5705
+ const matches = servers.filter(({ native }) => name.startsWith(`${native}_`));
5706
+ const match = matches[0];
5707
+ if (!match) return void 0;
5708
+ const { native } = match;
5709
+ const tool = name.slice(native.length + 1);
5710
+ if (tool !== "*" && !/^[a-zA-Z0-9_-]+$/.test(tool)) return void 0;
5711
+ if (matches.length !== 1 || servers.some((server) => server !== matches[0] && (server.native.startsWith(`${native}_`) || native.startsWith(`${server.native}_`)))) throw new Error(`opencode: ambiguous declared MCP permission "${name}"`);
5712
+ if (tool !== "*" && openCodePermissionName(name) !== void 0) throw new Error(`opencode: permission "${name}" names both a native and MCP tool`);
5713
+ return name;
5714
+ }
5715
+ const PI_EXECUTION_CONTROL_EXTENSION_PATH = ".tangle/pi-execution-controls.ts";
5716
+ /**
5717
+ * Translate only portable spellings whose Pi equivalent differs.
5718
+ *
5719
+ * Every other exact name is resolved against Pi's live registry, keeping
5720
+ * extension and MCP tools profile-configurable without a static catalog.
5721
+ */
5722
+ function piToolId(name) {
5723
+ const trimmed = name.trim();
5724
+ if (trimmed.length === 0) return void 0;
5725
+ const portableName = trimmed.toLowerCase();
5726
+ if (portableName === "shell") return "bash";
5727
+ if (portableName === "glob") return "find";
5728
+ return trimmed;
5729
+ }
5730
+ /**
5731
+ * Map tool switches to native ids; spellings of one tool keep its explicit off.
5732
+ *
5733
+ * Products compose profiles in layers: a shared allowlist, then a product
5734
+ * constraint that disables a native tool under its own spelling. Physim adds
5735
+ * `webfetch: false` over an allowlist holding `web_fetch: true`. Off is the
5736
+ * only value that honours every layer, so it wins regardless of entry order.
5737
+ */
5738
+ function mapSupportedBooleanEntries(entries, mapName, onUnsupported) {
5739
+ return mapControlEntries(entries, mapName, onUnsupported, (left, right) => left && right);
5740
+ }
5741
+ function permissionAllowsEverything(policy) {
5742
+ return typeof policy === "string" ? policy === "allow" : Object.values(policy).every((value) => value === "allow");
5743
+ }
5744
+ function mapSupportedPermissionEntries(entries, mapName, onUnsupported, label) {
5745
+ return mapControlEntries(entries, mapName, onUnsupported, (left, right, nativeName) => mergePermissionPolicies(left, right, `${label} "${nativeName}"`));
5746
+ }
5747
+ function mapControlEntries(entries, mapName, onUnsupported, merge) {
5748
+ const mapped = /* @__PURE__ */ new Map();
5749
+ for (const [name, value] of entries) {
5750
+ const nativeName = mapName(name);
5751
+ if (!nativeName) {
5752
+ onUnsupported(name);
5753
+ continue;
5754
+ }
5755
+ const previous = mapped.get(nativeName);
5756
+ mapped.set(nativeName, previous === void 0 ? value : merge(previous, value, nativeName));
5757
+ }
5758
+ return [...mapped.entries()].sort(([left], [right]) => compareStrings(left, right));
5759
+ }
5760
+ const PERMISSION_RESTRICTION = {
5761
+ allow: 0,
5762
+ ask: 1,
5763
+ deny: 2
5764
+ };
5765
+ function stricterDecision(left, right) {
5766
+ return PERMISSION_RESTRICTION[right] > PERMISSION_RESTRICTION[left] ? right : left;
5767
+ }
5768
+ /**
5769
+ * Merge policies whose names resolve to one native tool; the stricter
5770
+ * decision wins, as an explicit off does for tool switches.
5771
+ *
5772
+ * Pattern rules merge only when both spellings list the same patterns in the
5773
+ * same order. OpenCode applies the last matching pattern, so any other pair
5774
+ * has no merge at least as strict as each spelling: `{"*": "deny"}` beside
5775
+ * `{"https://x/*": "allow"}` would allow x. Those pairs stay contradictions
5776
+ * that `executionControlConflict` reports at admission.
5777
+ */
5778
+ function mergePermissionPolicies(left, right, label) {
5779
+ if (typeof left === "string" && typeof right === "string") return stricterDecision(left, right);
5780
+ if (typeof left === "string" || typeof right === "string") throw new Error(`${label} aliases mix a whole-tool decision with pattern rules`);
5781
+ const patterns = Object.keys(left);
5782
+ const rightPatterns = Object.keys(right);
5783
+ if (patterns.length !== rightPatterns.length || rightPatterns.some((pattern, index) => pattern !== patterns[index])) throw new Error(`${label} aliases set different pattern rules`);
5784
+ return Object.fromEntries(Object.entries(left).map(([pattern, decision]) => [pattern, stricterDecision(decision, right[pattern] ?? decision)]));
5785
+ }
5786
+ function claudePermissionRules(entries) {
5787
+ const rules = {
5788
+ allow: [],
5789
+ ask: [],
5790
+ deny: []
5791
+ };
5792
+ for (const [tool, policy] of entries) {
5793
+ if (typeof policy === "string") {
5794
+ rules[policy].push(tool);
5795
+ continue;
5796
+ }
5797
+ for (const [specifier, decision] of Object.entries(policy).sort(([left], [right]) => compareStrings(left, right))) rules[decision].push(specifier === "*" ? tool : `${tool}(${specifier})`);
5798
+ }
5799
+ rules.allow.sort(compareStrings);
5800
+ rules.ask.sort(compareStrings);
5801
+ rules.deny.sort(compareStrings);
5802
+ return rules;
5803
+ }
5804
+ /**
5805
+ * Give each Claude rule one decision. A tool switch and a permission can name
5806
+ * the same rule; the stricter decision wins, as deny already beats allow
5807
+ * inside Claude Code.
5808
+ */
5809
+ function sealClaudePermissionRules(rules) {
5810
+ const owner = /* @__PURE__ */ new Map();
5811
+ for (const decision of [
5812
+ "allow",
5813
+ "ask",
5814
+ "deny"
5815
+ ]) for (const rule of rules[decision]) {
5816
+ const previous = owner.get(rule);
5817
+ owner.set(rule, previous === void 0 ? decision : stricterDecision(previous, decision));
5818
+ }
5819
+ const sealed = {
5820
+ allow: [],
5821
+ ask: [],
5822
+ deny: []
5823
+ };
5824
+ for (const [rule, decision] of owner) sealed[decision].push(rule);
5825
+ sealed.allow.sort(compareStrings);
5826
+ sealed.ask.sort(compareStrings);
5827
+ sealed.deny.sort(compareStrings);
5828
+ return sealed;
5829
+ }
5830
+ function materializeExecutionControls(h, tools, permissions, modes, plan, add, unsupported, mcpAliases = []) {
5831
+ const toolEntries = Object.entries(tools ?? {}).sort(([left], [right]) => compareStrings(left, right));
5832
+ const permissionEntries = Object.entries(permissions ?? {}).sort(([left], [right]) => compareStrings(left, right));
5833
+ switch (h) {
5834
+ case "claude-code":
5835
+ materializeClaudeControls(toolEntries, permissionEntries, plan, add, unsupported);
5836
+ break;
5837
+ case "opencode":
5838
+ materializeOpenCodeControls(toolEntries, permissionEntries, add, unsupported, mcpAliases);
5839
+ break;
5840
+ case "codex":
5841
+ materializeCodexControls(toolEntries, permissionEntries, plan, unsupported);
5842
+ break;
5843
+ case "pi":
5844
+ materializePiControls(toolEntries, permissionEntries, plan, add, unsupported);
5845
+ break;
5846
+ default:
5847
+ if (toolEntries.length > 0) unsupported("tools", `${h}: no verified primary-process tool availability mapping`);
5848
+ if (permissionEntries.length > 0) unsupported("permissions", `${h}: no verified primary-process permission policy mapping`);
5849
+ }
5850
+ if (modes && Object.keys(modes).length > 0) unsupported("modes", `${h}: resolve one named AgentProfile mode before materialization`);
5851
+ }
5852
+ function materializeClaudeControls(toolEntries, permissionEntries, plan, add, unsupported) {
5853
+ if (toolEntries.length > 0 || permissionEntries.length > 0) {
5854
+ const nativeTools = mapSupportedBooleanEntries(toolEntries, claudeToolName, (name) => unsupported("tools", `claude-code: no verified native tool mapping for "${name}". Accepted: ${CLAUDE_CODE_NATIVE_TOOL_IDS.join(", ")}`));
5855
+ const rules = claudePermissionRules(mapSupportedPermissionEntries(permissionEntries, claudeToolName, (name) => unsupported("permissions", `claude-code: no verified native permission mapping for "${name}". Accepted: ${CLAUDE_CODE_NATIVE_PERMISSION_IDS.join(", ")}`), "claude-code permission"));
5856
+ for (const [tool, enabled] of nativeTools) rules[enabled ? "allow" : "deny"].push(tool);
5857
+ add(CLAUDE_SETTINGS_PATH, serializeWorkspacePlanJson({ permissions: sealClaudePermissionRules(rules) }));
5858
+ registerClaudeSettings(plan);
5859
+ }
5860
+ }
5861
+ function materializeOpenCodeControls(toolEntries, permissionEntries, add, unsupported, mcpAliases) {
5862
+ const enforceableTools = toolEntries.filter(([name, enabled]) => {
5863
+ if (normalizedControlName(name) !== "lsp" || !enabled) return true;
5864
+ unsupported("tools", "opencode: the LSP tool is disabled by the runtime and cannot be enabled exactly");
5865
+ return false;
5866
+ });
5867
+ const enforceablePermissions = permissionEntries.filter(([name, policy]) => {
5868
+ if (normalizedControlName(name) !== "read") return true;
5869
+ if (!permissionAllowsEverything(policy)) unsupported("permissions", "opencode: read access cannot be denied or approval-gated");
5870
+ return false;
5871
+ });
5872
+ const nativeTools = mapSupportedBooleanEntries(enforceableTools, openCodeToolName, (name) => unsupported("tools", `opencode: no verified native tool mapping for "${name}". Accepted: ${OPENCODE_NATIVE_TOOL_IDS.join(", ")}`));
5873
+ const nativePermissions = mapSupportedPermissionEntries(enforceablePermissions, (name) => openCodeDeclaredMcpPermissionName(name, mcpAliases) ?? openCodePermissionName(name), (name) => unsupported("permissions", `opencode: no verified native permission mapping for "${name}". Accepted: ${OPENCODE_NATIVE_PERMISSION_IDS.join(", ")}`), "opencode permission");
5874
+ if (enforceableTools.length > 0 || permissionEntries.length > 0) add(OPENCODE_CONFIG_FILE, serializeWorkspacePlanJson({
5875
+ $schema: OPENCODE_CONFIG_SCHEMA,
5876
+ ...nativeTools.length > 0 ? { tools: Object.fromEntries(nativeTools) } : {},
5877
+ ...nativePermissions.length > 0 ? { permission: Object.fromEntries(nativePermissions) } : {}
5878
+ }));
5879
+ }
5880
+ function materializeCodexControls(toolEntries, permissionEntries, plan, unsupported) {
5881
+ const searchEntries = [];
5882
+ const fetchEntries = [];
5883
+ for (const [name, enabled] of toolEntries) {
5884
+ const posture = resolveNativeWebTools({ [name]: enabled });
5885
+ if (posture.search === enabled && posture.fetch === void 0) {
5886
+ searchEntries.push([name, enabled]);
5887
+ continue;
5888
+ }
5889
+ if (posture.fetch === enabled && posture.search === void 0) {
5890
+ fetchEntries.push([name, enabled]);
5891
+ continue;
5892
+ }
5893
+ unsupported("tools", `codex: no verified primary-process tool mapping for "${name}"`);
5894
+ }
5895
+ if (mapSupportedBooleanEntries(fetchEntries, () => "web_fetch", () => void 0)[0]?.[1]) for (const [name] of fetchEntries) unsupported("tools", `codex: native web fetch is unavailable for "${name}"`);
5896
+ const nativeSearch = mapSupportedBooleanEntries(searchEntries, () => "web_search", () => void 0);
5897
+ if (nativeSearch[0]) plan.flags.push("-c", `tools.web_search=${nativeSearch[0][1]}`);
5898
+ if (permissionEntries.length > 0) unsupported("permissions", "codex: no verified primary-process permission policy mapping");
5899
+ }
5900
+ function materializePiControls(toolEntries, permissionEntries, plan, add, unsupported) {
5901
+ const nativeTools = mapSupportedBooleanEntries(toolEntries, piToolId, (name) => unsupported("tools", `pi: tool name "${name}" is empty after trimming`));
5902
+ const nativePermissions = mapSupportedPermissionEntries(permissionEntries, piToolId, (name) => unsupported("permissions", `pi: permission name "${name}" is empty after trimming`), "pi permission");
5903
+ const enabled = new Set(nativeTools.filter(([, value]) => value).map(([name]) => name).sort(compareStrings));
5904
+ const excluded = new Set(nativeTools.filter(([, value]) => !value).map(([name]) => name).sort(compareStrings));
5905
+ for (const [name, policy] of nativePermissions) {
5906
+ if (typeof policy !== "string") {
5907
+ unsupported("permissions", `pi: conditional permission policy for "${name}" has no verified headless mapping`);
5908
+ continue;
5909
+ }
5910
+ if (policy === "ask") {
5911
+ unsupported("permissions", `pi: permission policy "ask" for "${name}" requires an interactive decision surface`);
5912
+ continue;
5913
+ }
5914
+ if (policy === "allow") continue;
5915
+ enabled.delete(name);
5916
+ excluded.add(name);
5917
+ }
5918
+ if (enabled.size > 0 || excluded.size > 0) {
5919
+ add(PI_EXECUTION_CONTROL_EXTENSION_PATH, piExecutionControlExtensionSource([...enabled], [...excluded]));
5920
+ plan.flags.push("--extension", PI_EXECUTION_CONTROL_EXTENSION_PATH);
5921
+ }
5922
+ if (excluded.size > 0) plan.flags.push("--exclude-tools", [...excluded].sort(compareStrings).join(","));
5923
+ }
5924
+ function piExecutionControlExtensionSource(enabledTools, excludedTools) {
5925
+ return [
5926
+ "import { writeSync } from \"node:fs\";",
5927
+ `const enabledTools = Object.freeze(${JSON.stringify(enabledTools)});`,
5928
+ `const excludedTools = Object.freeze(${JSON.stringify(excludedTools)});`,
5929
+ "",
5930
+ "function failProfile(message) {",
5931
+ " try {",
5932
+ " writeSync(2, \"Pi profile execution controls failed: \" + message + \"\\n\");",
5933
+ " } finally {",
5934
+ " process.exit(78);",
5935
+ " }",
5936
+ "}",
5937
+ "",
5938
+ "function resolveTool(reference, available, required) {",
5939
+ " if (available.includes(reference)) return reference;",
5940
+ " const folded = reference.toLowerCase();",
5941
+ " const matches = available.filter((name) => name.toLowerCase() === folded);",
5942
+ " if (matches.length === 1) return matches[0];",
5943
+ " if (matches.length > 1) {",
5944
+ " failProfile('tool \"' + reference + '\" is ambiguous: ' + matches.join(\", \"));",
5945
+ " }",
5946
+ " if (required) {",
5947
+ " failProfile('requested tool \"' + reference + '\" is unavailable');",
5948
+ " }",
5949
+ " return undefined;",
5950
+ "}",
5951
+ "",
5952
+ "function applyControls(pi) {",
5953
+ " const available = pi.getAllTools().map((tool) => tool.name);",
5954
+ " for (const reference of excludedTools) {",
5955
+ " const remaining = resolveTool(reference, available, false);",
5956
+ " if (remaining !== undefined) {",
5957
+ " failProfile(",
5958
+ " 'excluded tool \"' + reference + '\" remains available as \"' + remaining +",
5959
+ " '\"; pass its exact registered Pi name',",
5960
+ " );",
5961
+ " }",
5962
+ " }",
5963
+ " const enabled = enabledTools.map((name) =>",
5964
+ " resolveTool(name, available, true),",
5965
+ " );",
5966
+ " const active = new Set(pi.getActiveTools());",
5967
+ " for (const name of enabled) active.add(name);",
5968
+ " pi.setActiveTools([...active]);",
5969
+ "}",
5970
+ "",
5971
+ "export default function applyProfileExecutionControls(pi) {",
5972
+ " pi.on(\"before_agent_start\", () => applyControls(pi));",
5973
+ " pi.on(\"turn_start\", () => applyControls(pi));",
5974
+ "}",
5975
+ ""
5976
+ ].join("\n");
5977
+ }
5978
+ /**
5979
+ * The header a harness sends to a remote MCP server whose tool-call timeout it
5980
+ * raised, carrying the timeout it applied in milliseconds. A server may hold a
5981
+ * call for nearly that long. A server that does not see the header must assume
5982
+ * the harness default, 60 s for Claude Code, Codex and OpenCode.
5983
+ */
5984
+ const MCP_TOOL_TIMEOUT_HEADER = "X-Mcp-Tool-Timeout-Ms";
5985
+ const MIN_MCP_TOOL_TIMEOUT_MS = 1e3;
5986
+ const MAX_MCP_TOOL_TIMEOUT_MS = 36e5;
5987
+ /**
5988
+ * The tool-call timeout a profile asks the harness to give one MCP server,
5989
+ * from `metadata.toolTimeoutMs`. Profile metadata is open in every published
5990
+ * schema, so a profile carrying it validates against older consumers, which
5991
+ * ignore it. A malformed value is reported, never guessed.
5992
+ */
5993
+ function mcpToolTimeoutMs(server, name, h, unsupported) {
5994
+ const value = server.metadata?.toolTimeoutMs;
5995
+ if (value === void 0) return void 0;
5996
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < MIN_MCP_TOOL_TIMEOUT_MS || value > MAX_MCP_TOOL_TIMEOUT_MS) {
5997
+ unsupported("mcp", `${h}: MCP server "${name}" metadata.toolTimeoutMs must be an integer from ${MIN_MCP_TOOL_TIMEOUT_MS} to ${MAX_MCP_TOOL_TIMEOUT_MS}`);
5998
+ return;
5999
+ }
6000
+ return value;
6001
+ }
6002
+ function mcpToolTimeouts(mcp, h, unsupported) {
6003
+ const timeouts = /* @__PURE__ */ new Map();
6004
+ for (const [name, server] of Object.entries(mcp)) {
6005
+ const value = mcpToolTimeoutMs(server, name, h, unsupported);
6006
+ if (value !== void 0) timeouts.set(name, value);
6007
+ }
6008
+ return timeouts;
6009
+ }
6010
+ function withAppliedToolTimeout(headers, appliedTimeoutMs) {
6011
+ if (appliedTimeoutMs === void 0) return headers;
6012
+ return {
6013
+ ...headers,
6014
+ [MCP_TOOL_TIMEOUT_HEADER]: {
6015
+ kind: "public",
6016
+ value: String(appliedTimeoutMs)
6017
+ }
6018
+ };
6019
+ }
6020
+ const carriesAuthorization = (headers) => Object.keys(headers ?? {}).some((header) => header.toLowerCase() === "authorization");
6021
+ /**
6022
+ * Lower canonical MCP definitions to OpenCode's native startup configuration.
6023
+ * `toolTimeouts` holds the validated `metadata.toolTimeoutMs` of each server
6024
+ * that declared one; without it OpenCode applies the MCP SDK's 60 s default to
6025
+ * every tool call.
6026
+ */
6027
+ function openCodeMcpConfig(mcp, toolTimeouts = /* @__PURE__ */ new Map()) {
6028
+ const out = {};
6029
+ for (const [name, s] of Object.entries(mcp)) {
6030
+ if (s.enabled === false) continue;
6031
+ const timeout = toolTimeouts.get(name);
6032
+ if (s.url) {
6033
+ if (s.transport === "sse") throw new Error(`OpenCode MCP server "${name}" uses unsupported SSE transport`);
6034
+ const headers = withAppliedToolTimeout(s.headers, timeout);
6035
+ out[name] = {
6036
+ type: "remote",
6037
+ url: s.url,
6038
+ enabled: true,
6039
+ ...headers ? { headers } : {},
6040
+ ...timeout !== void 0 ? { timeout } : {},
6041
+ ...carriesAuthorization(s.headers) ? { oauth: false } : {}
6042
+ };
6043
+ continue;
6044
+ }
6045
+ if (!s.command) throw new Error(`OpenCode MCP server "${name}" must define either url or command`);
6046
+ if (s.cwd !== void 0) throw new Error(`OpenCode MCP server "${name}" does not support a cwd field`);
6047
+ out[name] = {
6048
+ type: "local",
6049
+ command: [s.command, ...s.args ?? []],
6050
+ enabled: true,
6051
+ ...s.env ? { environment: s.env } : {},
6052
+ ...timeout !== void 0 ? { timeout } : {}
6053
+ };
6054
+ }
6055
+ return out;
6056
+ }
6057
+ function materializeMcp(h, mcp, plan, add, unsupported) {
6058
+ switch (h) {
6059
+ case "claude-code":
6060
+ materializeClaudeMcp(h, mcp, plan, add, unsupported);
6061
+ break;
6062
+ case "nanoclaw":
6063
+ unsupported("mcp", "nanoclaw MCP must be injected through options.mcpServers by its SDK adapter");
6064
+ break;
6065
+ case "codex":
6066
+ materializeCodexMcp(h, mcp, plan, unsupported);
6067
+ break;
6068
+ case "opencode":
6069
+ add(OPENCODE_CONFIG_FILE, serializeWorkspacePlanJson({
6070
+ $schema: OPENCODE_CONFIG_SCHEMA,
6071
+ mcp: openCodeMcpConfig(mcp, mcpToolTimeouts(mcp, h, unsupported))
6072
+ }));
6073
+ break;
6074
+ case "gemini":
6075
+ materializeGeminiMcp(mcp, add);
6076
+ break;
6077
+ case "kimi-code":
6078
+ add(".kimi-code/mcp.json", serializeWorkspacePlanJson({ mcpServers: Object.fromEntries(Object.entries(mcp).map(([name, server]) => [name, piMcpServer(server)])) }));
6079
+ break;
6080
+ case "pi":
6081
+ materializePiMcp(mcp, plan, add);
6082
+ break;
6083
+ case "prime":
6084
+ unsupported("mcp", "prime: settings.json mcpServers never becomes model-visible (fork mcp-manager.ts:62-124 registers OAuth providers only and skips stdio servers) — model-visible MCP is exactly the fork's built-in catalog skills");
6085
+ break;
6086
+ case "hermes":
6087
+ unsupported("mcp", "hermes MCP is global config.yaml (mcp_servers), no cwd discovery — write to the hermes global config or pass a config flag");
6088
+ break;
6089
+ case "openclaw":
6090
+ unsupported("mcp", "openclaw MCP is central ~/.openclaw/openclaw.json (mcp.servers), no cwd discovery");
6091
+ break;
6092
+ }
6093
+ }
6094
+ function materializeClaudeMcp(h, mcp, plan, add, unsupported) {
6095
+ const timeouts = mcpToolTimeouts(mcp, h, unsupported);
6096
+ const toolTimeoutMs = timeouts.size > 0 ? Math.max(...timeouts.values()) : void 0;
6097
+ if (toolTimeoutMs !== void 0) setPlanEnvironment(plan, "MCP_TOOL_TIMEOUT", String(toolTimeoutMs));
6098
+ const servers = {};
6099
+ for (const [name, server] of Object.entries(mcp)) {
6100
+ if (server.url) {
6101
+ const headers = withAppliedToolTimeout(server.headers, timeouts.has(name) ? toolTimeoutMs : void 0);
6102
+ servers[name] = {
6103
+ type: server.transport ?? "http",
6104
+ url: server.url,
6105
+ ...headers ? { headers } : {}
6106
+ };
6107
+ continue;
6108
+ }
6109
+ if (server.cwd !== void 0) unsupported("mcp", `${h}: local MCP server "${name}" does not support a cwd field`);
6110
+ servers[name] = {
6111
+ type: "stdio",
6112
+ command: server.command,
6113
+ ...server.args ? { args: server.args } : {},
6114
+ ...server.env ? { env: server.env } : {}
6115
+ };
6116
+ }
6117
+ const relPath = ".tangle/claude-mcp.json";
6118
+ add(relPath, serializeWorkspacePlanJson({ mcpServers: servers }));
6119
+ plan.flags.push("--mcp-config", relPath, "--strict-mcp-config");
6120
+ }
6121
+ function materializeCodexMcp(h, mcp, plan, unsupported) {
6122
+ const timeouts = mcpToolTimeouts(mcp, h, unsupported);
6123
+ const servers = [];
6124
+ for (const [name, server] of Object.entries(mcp).sort(([left], [right]) => compareStrings(left, right))) {
6125
+ if (server.url && server.transport === "sse") {
6126
+ unsupported("mcp", `codex: remote MCP server "${name}" uses unsupported SSE transport`);
6127
+ continue;
6128
+ }
6129
+ servers.push(concatWorkspacePlanArguments(`${tomlStr(name)} = `, codexMcpServerToml(name, server, plan, timeouts.get(name))));
6130
+ }
6131
+ if (servers.length > 0) plan.flags.push("-c", concatWorkspacePlanArguments("mcp_servers={ ", joinWorkspacePlanArguments(servers, ", "), " }"));
6132
+ }
6133
+ function materializeGeminiMcp(mcp, add) {
6134
+ const servers = {};
6135
+ for (const [name, server] of Object.entries(mcp)) servers[name] = server.url ? {
6136
+ [server.transport === "sse" ? "url" : "httpUrl"]: server.url,
6137
+ ...server.headers ? { headers: server.headers } : {}
6138
+ } : piMcpServer(server);
6139
+ add(".gemini/settings.json", serializeWorkspacePlanJson({ mcpServers: servers }));
6140
+ }
6141
+ function materializePiMcp(mcp, plan, add) {
6142
+ add(".pi/mcp.json", serializeWorkspacePlanJson({ mcpServers: Object.fromEntries(Object.entries(mcp).map(([name, server]) => [name, {
6143
+ ...piMcpServer(server),
6144
+ directTools: true
6145
+ }])) }));
6146
+ plan.requires?.push({
6147
+ kind: "harness-extension",
6148
+ dimension: "mcp",
6149
+ id: "npm:pi-mcp-adapter",
6150
+ reason: "pi has no built-in MCP; without this extension the servers in .pi/mcp.json are never read and the agent starts with none of their tools",
6151
+ remedy: "pi install npm:pi-mcp-adapter"
6152
+ });
6153
+ }
6154
+ function tomlInlineStringTable(values) {
6155
+ return `{ ${Object.entries(values).sort(([left], [right]) => compareStrings(left, right)).map(([key, value]) => `${tomlStr(key)} = ${tomlStr(value)}`).join(", ")} }`;
6156
+ }
6157
+ function codexMcpServerToml(name, server, plan, toolTimeoutMs) {
6158
+ const fields = [];
6159
+ const appliedTimeoutMs = toolTimeoutMs === void 0 ? void 0 : Math.ceil(toolTimeoutMs / 1e3) * 1e3;
6160
+ if (appliedTimeoutMs !== void 0) fields.push(`tool_timeout_sec = ${appliedTimeoutMs / 1e3}`);
6161
+ if (server.url) {
6162
+ fields.push(`url = ${tomlStr(server.url)}`);
6163
+ const headers = withAppliedToolTimeout(server.headers, appliedTimeoutMs);
6164
+ if (headers && Object.keys(headers).length > 0) {
6165
+ const envHeaders = {};
6166
+ for (const [header, value] of Object.entries(headers).sort(([left], [right]) => compareStrings(left, right))) {
6167
+ const envName = `TANGLE_MCP_HEADER_${sha256(`${name}\0${header}`).slice(0, 24).toUpperCase()}`;
6168
+ setPlanEnvironment(plan, envName, value);
6169
+ envHeaders[header] = envName;
6170
+ }
6171
+ fields.push(`env_http_headers = ${tomlInlineStringTable(envHeaders)}`);
6172
+ }
6173
+ } else {
6174
+ if (!server.command) throw new Error(`Codex MCP server "${name}" must define url or command`);
6175
+ fields.push(`command = ${tomlStr(server.command)}`);
6176
+ if (server.args?.length) fields.push(concatWorkspacePlanArguments("args = [", joinWorkspacePlanArguments(server.args.map(tomlProfileConfigValue), ", "), "]"));
6177
+ if (server.cwd) fields.push(`cwd = ${tomlStr(server.cwd)}`);
6178
+ if (server.env && Object.keys(server.env).length > 0) {
6179
+ const envNames = Object.keys(server.env).sort(compareStrings);
6180
+ for (const envName of envNames) setPlanEnvironment(plan, envName, server.env[envName]);
6181
+ fields.push(`env_vars = [${envNames.map(tomlStr).join(", ")}]`);
6182
+ }
6183
+ }
6184
+ return concatWorkspacePlanArguments("{ ", joinWorkspacePlanArguments(fields, ", "), " }");
6185
+ }
6186
+ /**
6187
+ * Lower one canonical MCP server to the `{mcpServers: {...}}` entry Kimi and
6188
+ * `pi-mcp-adapter` both read (gemini shares its local form). The pi caller adds
6189
+ * `directTools`, a tool-surfacing policy rather than a property of the server.
6190
+ */
6191
+ function piMcpServer(server) {
6192
+ if (server.url) return {
6193
+ url: server.url,
6194
+ transport: server.transport ?? "http",
6195
+ ...server.headers ? { headers: server.headers } : {}
6196
+ };
6197
+ return {
6198
+ command: server.command,
6199
+ ...server.args ? { args: server.args } : {},
6200
+ ...server.env ? { env: server.env } : {},
6201
+ ...server.cwd ? { cwd: server.cwd } : {}
6202
+ };
6203
+ }
6204
+ function lowerProfilePrompt(profile, harness, binds, instructionsRoot, builder) {
6205
+ const { plan, add, addAtRoot, unsupported } = builder;
6206
+ if (profile.prompt?.systemPrompt?.trim()) if (harness === "claude-code" || harness === "pi" || harness === "prime") plan.systemPrompt = profile.prompt.systemPrompt;
6207
+ else if (harness === "codex") {
6208
+ add(CODEX_SYSTEM_PROMPT_FILE, profile.prompt.systemPrompt);
6209
+ plan.flags.push("-c", `model_instructions_file=${CODEX_SYSTEM_PROMPT_FILE}`);
6210
+ } else if (harness === "gemini") {
6211
+ add(".gemini/system.md", profile.prompt.systemPrompt);
6212
+ plan.env.GEMINI_SYSTEM_MD = "1";
6213
+ } else if (harness === "opencode") {
6214
+ const systemPrompt = profile.prompt.systemPrompt;
6215
+ if (binds.has("opencode.agent-prompt")) plan.systemPromptBinding = {
6216
+ intent: "replace",
6217
+ control: "opencode.agent-prompt",
6218
+ systemPrompt
6219
+ };
6220
+ else if (binds.has("systemPrompt")) {
6221
+ const primaryAgentName = `${OPENCODE_PRIMARY_AGENT_PREFIX}${sha256(systemPrompt).slice(0, 16)}`;
6222
+ const primaryAgentPath = `.opencode/agents/${primaryAgentName}.md`;
6223
+ if (profile.subagents?.[primaryAgentName] !== void 0) throw new Error(`opencode: subagent name "${primaryAgentName}" is reserved for the profile primary agent`);
6224
+ plan.systemPrompt = systemPrompt;
6225
+ add(primaryAgentPath, markMaterializerSubagent(primaryAgentPath, [
6226
+ "---",
6227
+ "mode: primary",
6228
+ "---",
6229
+ systemPrompt,
6230
+ ""
6231
+ ].join("\n")));
6232
+ plan.flags.push("--agent", primaryAgentName);
6233
+ } else unsupported("systemPrompt", systemPromptRefusal(harness));
6234
+ } else unsupported("systemPrompt", systemPromptRefusal(harness));
6235
+ const openCodeInstructionFiles = [];
6236
+ const openCodeConfigUnreachable = harness === "opencode" && binds.has("opencode.agent-prompt");
6237
+ if (profile.prompt?.appendSystemPrompt !== void 0) {
6238
+ const appendSystemPrompt = profile.prompt.appendSystemPrompt;
6239
+ if (appendSystemPrompt.trim().length === 0) throw new Error("prompt.appendSystemPrompt must be non-empty text");
6240
+ if (openCodeConfigUnreachable) unsupported("appendSystemPrompt", "opencode: the launcher that binds opencode.agent-prompt composes opencode's config itself and loads no workspace opencode.json, so an addition registered there would never reach the model; compose it into the launcher's own instructions[]");
6241
+ else if (harness === "opencode") {
6242
+ add(OPENCODE_APPEND_SYSTEM_PROMPT_FILE, appendSystemPrompt.endsWith("\n") ? appendSystemPrompt : `${appendSystemPrompt}\n`);
6243
+ openCodeInstructionFiles.push(OPENCODE_APPEND_SYSTEM_PROMPT_FILE);
6244
+ } else if (harness === "claude-code" || harness === "pi" || harness === "prime") plan.appendSystemPrompt = appendSystemPrompt;
6245
+ else unsupported("appendSystemPrompt", appendSystemPromptRefusal(harness));
6246
+ }
6247
+ const instructions = [...profile.prompt?.instructions ?? []];
6248
+ const resourceInstructions = profile.resources?.instructions;
6249
+ if (typeof resourceInstructions === "string") instructions.push(resourceInstructions);
6250
+ else if (resourceInstructions && resourceInstructions.kind === "inline") instructions.push(resourceInstructions.content);
6251
+ else if (resourceInstructions) unsupported("instructions", "instruction ref is not inline (github refs need async pre-resolution)");
6252
+ if (instructions.length) if (harness === "codex" && binds.has("codex.developer-instructions")) plan.appendSystemPrompt = instructions.join("\n\n");
6253
+ else if (openCodeConfigUnreachable) unsupported("instructions", "opencode: the launcher that binds opencode.agent-prompt composes opencode's config itself and loads no workspace opencode.json, so an instruction file registered there would never reach the model; compose it into the launcher's own instructions[]");
6254
+ else {
6255
+ const instructionPath = CONTEXT_FILE[harness];
6256
+ addAtRoot(instructionsRoot, instructionPath, markMaterializerContextFile(instructionPath, `${instructions.join("\n\n")}\n`));
6257
+ if (harness === "opencode") openCodeInstructionFiles.push(instructionPath);
6258
+ }
6259
+ if (openCodeInstructionFiles.length > 0) add(OPENCODE_CONFIG_FILE, serializeWorkspacePlanJson({
6260
+ $schema: OPENCODE_CONFIG_SCHEMA,
6261
+ instructions: openCodeInstructionFiles
6262
+ }));
6263
+ }
6264
+ function activeMcpServers(servers) {
6265
+ return Object.fromEntries(Object.entries(servers ?? {}).filter((entry) => entry[1].enabled !== false));
6266
+ }
6267
+ function materializeCommand(h, name, body, add, unsupported) {
6268
+ switch (h) {
6269
+ case "claude-code":
6270
+ case "nanoclaw":
6271
+ add(`.claude/commands/${name}.md`, body.endsWith("\n") ? body : `${body}\n`);
6272
+ break;
6273
+ case "opencode":
6274
+ add(`.opencode/commands/${name}.md`, body.endsWith("\n") ? body : `${body}\n`);
6275
+ break;
6276
+ case "gemini":
6277
+ add(`.gemini/commands/${name}.toml`, `prompt = ${tomlStr(body)}\n`);
6278
+ break;
6279
+ case "pi":
6280
+ add(`.pi/prompts/${name}.md`, body.endsWith("\n") ? body : `${body}\n`);
6281
+ break;
6282
+ case "prime":
6283
+ add(`.prime/agent/prompts/${name}.md`, body.endsWith("\n") ? body : `${body}\n`);
6284
+ break;
6285
+ case "kimi-code":
6286
+ unsupported("commands", "kimi commands ARE skills (/skill:<name>) — provide as a skill instead");
6287
+ break;
6288
+ case "codex":
6289
+ unsupported("commands", "codex project commands unsupported (~/.codex/prompts is user-global only)");
6290
+ break;
6291
+ default: unsupported("commands", `${h}: no cwd command path`);
6292
+ }
6293
+ }
3308
6294
  function describeUnresolvedRef(r) {
3309
6295
  const name = typeof r.name === "string" ? r.name : void 0;
3310
6296
  const path = typeof r.path === "string" ? r.path : void 0;
@@ -3330,7 +6316,304 @@ function resolveInlineRef(ref) {
3330
6316
  if (r.kind === "inline") throw new Error(`Profile resource ${describeUnresolvedRef(r)} declares kind "inline" but has no string content`);
3331
6317
  return null;
3332
6318
  }
6319
+ const FRONTMATTER_RE = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/;
6320
+ const collapse = (s) => s.replace(/\s+/g, " ").trim();
6321
+ function frontmatterScalar(value) {
6322
+ const trimmed = value.trim();
6323
+ if (trimmed.startsWith("\"") && trimmed.endsWith("\"")) try {
6324
+ const parsed = JSON.parse(trimmed);
6325
+ if (typeof parsed === "string") return parsed;
6326
+ } catch {
6327
+ return trimmed;
6328
+ }
6329
+ if (trimmed.startsWith("'") && trimmed.endsWith("'")) return trimmed.slice(1, -1).replaceAll("''", "'");
6330
+ return trimmed;
6331
+ }
6332
+ function frontmatterValue(frontmatter, field) {
6333
+ const lines = frontmatter.split("\n");
6334
+ const index = lines.findIndex((line) => line.startsWith(`${field}:`));
6335
+ if (index < 0) return void 0;
6336
+ const inline = (lines[index] ?? "").slice(field.length + 1).trim();
6337
+ if (inline && ![
6338
+ ">",
6339
+ "|",
6340
+ ">-",
6341
+ "|-"
6342
+ ].includes(inline)) return frontmatterScalar(inline);
6343
+ const block = [];
6344
+ for (let offset = index + 1; offset < lines.length; offset += 1) {
6345
+ const line = lines[offset] ?? "";
6346
+ if (/^\s+\S/.test(line)) block.push(line.trim());
6347
+ else if (line.trim() !== "") break;
6348
+ }
6349
+ return collapse(block.join(" ")) || void 0;
6350
+ }
6351
+ /** Normalize any skill markdown (VB frontmatter `skill:`/`description:`, or raw) into a
6352
+ * harness SKILL.md with `name:`/`description:` frontmatter the harnesses require. */
6353
+ function normalizeSkillMd(name, raw) {
6354
+ const m = raw.match(FRONTMATTER_RE);
6355
+ const fm = m?.[1] ?? "";
6356
+ const body = (m?.[2] ?? raw).trim();
6357
+ if (fm && frontmatterValue(fm, "name") === name && (frontmatterValue(fm, "description")?.trim().length ?? 0) > 0) return raw;
6358
+ let desc = `Skill ${name}. Use when the task matches its domain.`;
6359
+ const declaredDescription = fm ? frontmatterValue(fm, "description") : void 0;
6360
+ if (declaredDescription) desc = collapse(declaredDescription);
6361
+ return `---\nname: ${name}\ndescription: ${JSON.stringify(desc)}\n---\n\n${body}\n`;
6362
+ }
6363
+ function materializeSubagent(h, name, sa, plan, add, unsupported) {
6364
+ if (!/^[a-z0-9][a-z0-9_-]*$/.test(name)) {
6365
+ unsupported("subagents", `${h}: subagent name "${name}" must use lowercase letters, digits, underscores, or hyphens`);
6366
+ return;
6367
+ }
6368
+ switch (h) {
6369
+ case "claude-code":
6370
+ case "nanoclaw": {
6371
+ const fm = ["---", `name: ${name}`];
6372
+ fm.push(`description: ${JSON.stringify(sa.description ?? name)}`);
6373
+ if (sa.model) fm.push(`model: ${JSON.stringify(sa.model)}`);
6374
+ if (sa.tools) {
6375
+ const tools = Object.entries(sa.tools);
6376
+ const allowed = tools.filter(([, enabled]) => enabled).map(([tool]) => tool);
6377
+ const denied = tools.filter(([, enabled]) => !enabled).map(([tool]) => tool);
6378
+ if (allowed.length > 0) fm.push(`tools: ${JSON.stringify(allowed)}`);
6379
+ if (denied.length > 0) fm.push(`disallowedTools: ${JSON.stringify(denied)}`);
6380
+ }
6381
+ if (sa.maxSteps !== void 0) fm.push(`maxTurns: ${sa.maxSteps}`);
6382
+ reportUnsupportedSubagentFields(h, name, sa, new Set([
6383
+ "description",
6384
+ "prompt",
6385
+ "model",
6386
+ "tools",
6387
+ "maxSteps"
6388
+ ]), unsupported);
6389
+ fm.push("---", "", sa.prompt ?? sa.description ?? name);
6390
+ const relPath = `.claude/agents/${name}.md`;
6391
+ add(relPath, markMaterializerSubagent(relPath, `${fm.join("\n")}\n`));
6392
+ break;
6393
+ }
6394
+ case "opencode": {
6395
+ const fm = [
6396
+ "---",
6397
+ `description: ${JSON.stringify(sa.description ?? name)}`,
6398
+ "mode: subagent"
6399
+ ];
6400
+ if (sa.model) fm.push(`model: ${JSON.stringify(sa.model)}`);
6401
+ if (sa.tools) fm.push(`tools: ${JSON.stringify(sa.tools)}`);
6402
+ if (sa.permissions) fm.push(`permission: ${JSON.stringify(sa.permissions)}`);
6403
+ if (sa.maxSteps !== void 0) fm.push(`steps: ${sa.maxSteps}`);
6404
+ reportUnsupportedSubagentFields(h, name, sa, new Set([
6405
+ "description",
6406
+ "prompt",
6407
+ "model",
6408
+ "tools",
6409
+ "permissions",
6410
+ "maxSteps"
6411
+ ]), unsupported);
6412
+ fm.push("---", "", sa.prompt ?? "");
6413
+ const relPath = `.opencode/agents/${name}.md`;
6414
+ add(relPath, markMaterializerSubagent(relPath, `${fm.join("\n")}\n`));
6415
+ break;
6416
+ }
6417
+ case "gemini": {
6418
+ const tools = sa.tools ? Object.entries(sa.tools).filter(([, enabled]) => enabled).map(([tool]) => tool) : void 0;
6419
+ reportUnsupportedSubagentFields(h, name, sa, new Set([
6420
+ "description",
6421
+ "prompt",
6422
+ "model",
6423
+ "tools",
6424
+ "maxSteps"
6425
+ ]), unsupported);
6426
+ const relPath = `.gemini/agents/${name}.md`;
6427
+ add(relPath, markMaterializerSubagent(relPath, [
6428
+ "---",
6429
+ `name: ${name}`,
6430
+ `description: ${JSON.stringify(sa.description ?? name)}`,
6431
+ "kind: local",
6432
+ ...sa.model ? [`model: ${JSON.stringify(sa.model)}`] : [],
6433
+ ...tools ? [`tools: ${JSON.stringify(tools)}`] : [],
6434
+ ...sa.maxSteps !== void 0 ? [`max_turns: ${sa.maxSteps}`] : [],
6435
+ "---",
6436
+ "",
6437
+ sa.prompt ?? "",
6438
+ ""
6439
+ ].join("\n")));
6440
+ break;
6441
+ }
6442
+ case "codex": {
6443
+ const relPath = `.codex/agents/${name}.toml`;
6444
+ const lines = [
6445
+ `name = ${tomlStr(name)}`,
6446
+ `description = ${tomlStr(sa.description ?? name)}`,
6447
+ `developer_instructions = ${tomlStr(sa.prompt ?? sa.description ?? name)}`
6448
+ ];
6449
+ if (sa.model) lines.push(`model = ${tomlStr(sa.model)}`);
6450
+ reportUnsupportedSubagentFields(h, name, sa, new Set([
6451
+ "description",
6452
+ "prompt",
6453
+ "model"
6454
+ ]), unsupported);
6455
+ add(relPath, markMaterializerSubagent(relPath, `${lines.join("\n")}\n`));
6456
+ registerCodexAgent(plan, name, relPath, sa.description ?? name);
6457
+ break;
6458
+ }
6459
+ case "prime":
6460
+ unsupported("subagents", `prime: subagents live in the agent-dir continual-harness store (<agentDir>/harness/harness_state.json), outside any workspace plan — seed "${name}" with seedPrimeProfileSubagents from the executor that owns the agent dir`);
6461
+ break;
6462
+ default: unsupported("subagents", `${h}: subagents have no cwd file (config/flag/global only); "${name}" not mounted`);
6463
+ }
6464
+ }
6465
+ function codexAgentRoleName(resourceName) {
6466
+ const name = resourceName.endsWith(".toml") ? resourceName.slice(0, -5) : resourceName;
6467
+ return /^[a-z0-9][a-z0-9_-]*$/.test(name) ? name : void 0;
6468
+ }
6469
+ function registerCodexAgent(plan, name, configFile, description) {
6470
+ plan.flags.push("-c", `agents.${name}.description=${tomlStr(description)}`, "-c", `agents.${name}.config_file=${tomlStr(configFile)}`);
6471
+ }
6472
+ function reportUnsupportedSubagentFields(harness, name, subagent, supported, unsupported) {
6473
+ for (const field of [
6474
+ "description",
6475
+ "prompt",
6476
+ "model",
6477
+ "tools",
6478
+ "permissions",
6479
+ "maxSteps",
6480
+ "metadata"
6481
+ ]) if (subagent[field] !== void 0 && !supported.has(field)) unsupported("subagents", `${harness}: subagent "${name}" does not support ${field}`);
6482
+ }
6483
+ function lowerProfileResources(profile, harness, builder) {
6484
+ const { plan, addExplicitResource, unsupported } = builder;
6485
+ const fileMountPaths = /* @__PURE__ */ new Set();
6486
+ for (const mount of profile.resources?.files ?? []) {
6487
+ const relPath = normalizeWorkspaceRelativePath(mount.path);
6488
+ if (fileMountPaths.has(relPath)) throw new Error(`Duplicate workspace file mount: ${relPath}`);
6489
+ fileMountPaths.add(relPath);
6490
+ if (mount.executable !== void 0 && typeof mount.executable !== "boolean") throw new Error(`Workspace file executable must be a boolean: ${relPath}`);
6491
+ const resource = resolveInlineRef(mount.resource);
6492
+ if (!resource) {
6493
+ unsupported("files", `file mount "${relPath}" is not inline (github refs need async pre-resolution)`);
6494
+ continue;
6495
+ }
6496
+ addExplicitResource("files", relPath, resource.content, mount.executable ? 493 : 420);
6497
+ }
6498
+ for (const ref of profile.resources?.tools ?? []) {
6499
+ const resource = resolveInlineRef(ref);
6500
+ if (!resource) {
6501
+ unsupported("tools", "tool ref is not inline (github refs need async pre-resolution)");
6502
+ continue;
6503
+ }
6504
+ if (harness !== "opencode") {
6505
+ unsupported("tools", `${harness}: no verified cwd-native file tool path; use MCP or a native extension`);
6506
+ continue;
6507
+ }
6508
+ addExplicitResource("tools", `.opencode/tools/${resource.name}`, resource.content);
6509
+ }
6510
+ for (const ref of profile.resources?.agents ?? []) {
6511
+ const resource = resolveInlineRef(ref);
6512
+ if (!resource) {
6513
+ unsupported("subagents", "agent ref is not inline (github refs need async pre-resolution)");
6514
+ continue;
6515
+ }
6516
+ const directory = agentResourceDirectory(harness);
6517
+ if (!directory) {
6518
+ unsupported("subagents", `${harness}: agent definitions have no verified cwd-native resource path`);
6519
+ continue;
6520
+ }
6521
+ const relPath = `${directory}/${resource.name}`;
6522
+ addExplicitResource("subagents", relPath, resource.content);
6523
+ if (harness === "codex") {
6524
+ const roleName = codexAgentRoleName(resource.name);
6525
+ if (!roleName) unsupported("subagents", `codex: agent resource "${resource.name}" must use a lowercase role name`);
6526
+ else registerCodexAgent(plan, roleName, relPath, roleName);
6527
+ }
6528
+ }
6529
+ }
6530
+ function lowerProfileSkills(profile, harness, builder) {
6531
+ const { addExplicitResource, unsupported } = builder;
6532
+ for (const ref of profile.resources?.skills ?? []) {
6533
+ const resource = resolveInlineRef(ref);
6534
+ if (!resource) {
6535
+ unsupported("skills", "skill ref is not inline (github refs need async pre-resolution)");
6536
+ continue;
6537
+ }
6538
+ const directory = HARNESS_SKILL_DIRS[harness];
6539
+ if (!directory) {
6540
+ unsupported("skills", `${harness}: no cwd skill dir (skills live in a user/global dir); skill "${resource.name}" not mounted`);
6541
+ continue;
6542
+ }
6543
+ addExplicitResource("skills", `${directory}/${resource.name}/SKILL.md`, normalizeSkillMd(resource.name, resource.content));
6544
+ }
6545
+ }
6546
+ function lowerProfileCommands(profile, harness, builder) {
6547
+ const { addExplicitResource, unsupported } = builder;
6548
+ for (const ref of profile.resources?.commands ?? []) {
6549
+ const resource = resolveInlineRef(ref);
6550
+ if (!resource) {
6551
+ unsupported("commands", "command ref is not inline (github needs pre-resolution)");
6552
+ continue;
6553
+ }
6554
+ materializeCommand(harness, resource.name, resource.content, (path, content, mode) => addExplicitResource("commands", path, content, mode), unsupported);
6555
+ }
6556
+ }
6557
+ function agentResourceDirectory(harness) {
6558
+ switch (harness) {
6559
+ case "claude-code":
6560
+ case "nanoclaw": return ".claude/agents";
6561
+ case "codex": return ".codex/agents";
6562
+ case "opencode": return ".opencode/agents";
6563
+ case "gemini": return ".gemini/agents";
6564
+ default: return null;
6565
+ }
6566
+ }
3333
6567
  Object.freeze({ async get() {} });
6568
+ /** What each harness's launch binds and where it reads instructions: its sidecar adapter and every pre-box verdict pass the same. */
6569
+ const HARNESS_LAUNCH_MATERIALIZE_OPTIONS = {
6570
+ codex: { binds: ["codex.developer-instructions"] },
6571
+ opencode: { binds: ["systemPrompt"] },
6572
+ pi: { instructionsRoot: "agent" }
6573
+ };
6574
+ /**
6575
+ * Build a pure workspace plan for one canonical harness.
6576
+ * The caller applies files, environment, and flags at its process boundary.
6577
+ */
6578
+ function materializeProfile(inputProfile, harness, opts = {}) {
6579
+ assertMaterializerHarness(harness);
6580
+ const profile = agentProfileSchema.parse(inputProfile);
6581
+ const knowledge = profile.resources && Reflect.get(profile.resources, "knowledge");
6582
+ if (Array.isArray(knowledge) && knowledge.length > 0) throw new Error("Knowledge source generations must be owner-authorized and resolved by the execution runtime before materialization");
6583
+ const skip = new Set(assertSkippableDimensions(opts.skip));
6584
+ const binds = assertBindableLaunchControls(opts.binds);
6585
+ const instructionsRoot = opts.instructionsRoot ?? "workspace";
6586
+ if (instructionsRoot !== "workspace" && instructionsRoot !== "agent") throw new Error(`materializeProfile: unsupported instructions root ${String(instructionsRoot)}`);
6587
+ if (instructionsRoot === "agent" && !harnessAutoLoadsAgentContextFile(harness)) throw new Error(`materializeProfile: harness "${harness}" does not load instructions from its agent directory`);
6588
+ const builder = createProfilePlanBuilder(harness);
6589
+ lowerProfileResources(profile, harness, builder);
6590
+ lowerProfilePrompt(profile, harness, binds, instructionsRoot, builder);
6591
+ materializeExecutionControls(harness, profile.tools, profile.permissions, profile.modes, builder.plan, builder.add, builder.unsupported, skip.has("mcp") ? [] : Object.keys(activeMcpServers(profile.mcp)));
6592
+ if ((profile.connections?.length ?? 0) > 0) builder.unsupported("connections", `${harness}: Hub connections must be resolved to authorized MCP servers by the execution runtime`);
6593
+ if (profile.confidential !== void 0) builder.unsupported("confidential", `${harness}: confidential execution requires runtime placement and attestation, not workspace files`);
6594
+ lowerProfileSkills(profile, harness, builder);
6595
+ const attachmentMcp = opts.runtimeAttachments === void 0 ? void 0 : AgentRuntimeAttachmentsSchema.parse(opts.runtimeAttachments).mcp;
6596
+ if (attachmentMcp && skip.has("mcp")) throw new Error("Runtime MCP attachments cannot be skipped");
6597
+ for (const alias of Object.keys(attachmentMcp ?? {})) {
6598
+ if (attachmentMcp?.[alias]?.enabled === false) throw new Error(`Runtime MCP attachment cannot be disabled: ${alias}`);
6599
+ if (Object.hasOwn(profile.mcp ?? {}, alias)) throw new Error(`Runtime MCP attachment alias conflicts with profile: ${alias}`);
6600
+ }
6601
+ const mcp = activeMcpServers({
6602
+ ...profile.mcp,
6603
+ ...attachmentMcp
6604
+ });
6605
+ if (!skip.has("mcp") && Object.keys(mcp).length > 0) {
6606
+ materializeMcp(harness, mcp, builder.plan, builder.add, builder.unsupported);
6607
+ if (attachmentMcp && builder.plan.unsupported.some((entry) => entry.dimension === "mcp")) throw new Error(`${harness} cannot materialize the requested runtime MCP attachments`);
6608
+ }
6609
+ const hooks = profile.hooks ?? {};
6610
+ if (Object.keys(hooks).length > 0) materializeHooks(harness, hooks, builder.add, builder.unsupported, builder.plan);
6611
+ for (const [name, subagent] of Object.entries(profile.subagents ?? {})) materializeSubagent(harness, name, subagent, builder.plan, builder.add, builder.unsupported);
6612
+ const extension = profile.extensions?.[harness];
6613
+ if (!skip.has("extensions") && harness !== "pi" && extension && Object.keys(extension).length > 0) builder.unsupported("extensions", `${harness}: extension namespace "${harness}" requires provider-native handling`);
6614
+ lowerProfileCommands(profile, harness, builder);
6615
+ return builder.finalize(profile.resources?.failOnError);
6616
+ }
3334
6617
  ["apps", "plugins"].flatMap((feature) => ["-c", `features.${feature}=false`]);
3335
6618
  const PROFILE_BUNDLE_SCHEMA = "agent-profile-bundle/v1";
3336
6619
  const PROFILE_BIN_DIR_RE = /(^|\/)(s?bin)\//;
@@ -6614,92 +9897,69 @@ function invalidCapabilities(message) {
6614
9897
  code: "INVALID_CAPABILITY_DOCUMENT"
6615
9898
  });
6616
9899
  }
6617
- function readFlagGroup(record, group, keys) {
6618
- const value = record[group];
6619
- if (value === null || typeof value !== "object" || Array.isArray(value)) invalidCapabilities(`a malformed '${group}' group`);
6620
- const flags = value;
6621
- const out = {};
6622
- for (const key of keys) {
6623
- if (typeof flags[key] !== "boolean") invalidCapabilities(`a non-boolean '${group}.${key}' flag`);
6624
- out[key] = flags[key];
6625
- }
6626
- return out;
9900
+ const asRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
9901
+ /** A flag the document omits or mistypes is unknown, so not proven: false. */
9902
+ function flags(group, keys) {
9903
+ const record = asRecord(group) ?? {};
9904
+ return Object.fromEntries(keys.map((key) => [key, record[key] === true]));
6627
9905
  }
9906
+ /** An optional flag the document omits or mistypes is left out. */
9907
+ const optional = (record, key) => typeof record[key] === "boolean" ? { [key]: record[key] } : {};
6628
9908
  /**
6629
9909
  * Validate the `GET /capabilities` response body into the typed document.
6630
9910
  *
6631
- * Posture, matching the document's own absence-means-unknown convention:
6632
- * - `schema: 1` parses strictly — a v1 document that is missing a declared
6633
- * group or carries a non-boolean flag throws, because a caller acting on
6634
- * a fabricated capability is worse than one that surfaces the defect.
6635
- * - A NEWER schema (integer > 1) returns `null` — "unknown, fail closed".
6636
- * This SDK cannot read the layout, and hard-failing here would break
6637
- * every installed client at exactly the version-skew event capability
6638
- * discovery exists for.
6639
- * - Anything else (non-object, missing or non-numeric `schema`) throws:
6640
- * that is not a capability document at all.
9911
+ * The document is additive: a group or flag this SDK cannot read is unknown
9912
+ * and reads as not supported, never a failure of the whole document (a
9913
+ * sidecar that drops or reshapes one group must not 502 every older client).
9914
+ * A NEWER schema (integer > 1) returns `null`, "unknown, fail closed".
9915
+ * Only a document that is not one throws: a non-object, a missing or
9916
+ * unknown schema, or missing identity fields.
6641
9917
  */
6642
9918
  function parseSandboxRuntimeCapabilities(raw) {
6643
- if (raw === null || typeof raw !== "object" || Array.isArray(raw)) invalidCapabilities("a non-object document");
6644
- const record = raw;
9919
+ const record = asRecord(raw);
9920
+ if (!record) invalidCapabilities("a non-object document");
6645
9921
  if (typeof record.schema === "number" && Number.isInteger(record.schema) && record.schema > 1) return null;
6646
9922
  if (record.schema !== 1) invalidCapabilities(`schema version ${JSON.stringify(record.schema)} — this SDK understands 1`);
6647
9923
  if (typeof record.agentInterface !== "string" || typeof record.sidecarVersion !== "string" || typeof record.image !== "string") invalidCapabilities("a document missing its identity fields");
6648
- if (record.cliAuthReferences !== void 0 && typeof record.cliAuthReferences !== "boolean") invalidCapabilities("a non-boolean 'cliAuthReferences' flag");
6649
- if (record.claudeTokenContinuations !== void 0 && typeof record.claudeTokenContinuations !== "boolean") invalidCapabilities("a non-boolean 'claudeTokenContinuations' flag");
6650
- if (record.codexCredentialContinuations !== void 0 && typeof record.codexCredentialContinuations !== "boolean") invalidCapabilities("a non-boolean 'codexCredentialContinuations' flag");
6651
9924
  const nativeVersion = record.nativeSessionCaptureVersion;
6652
9925
  const nativeHarnesses = record.nativeSessionCaptureHarnesses;
6653
- if (nativeVersion !== void 0 && (typeof nativeVersion !== "number" || !Number.isSafeInteger(nativeVersion) || nativeVersion < 1)) invalidCapabilities("a malformed 'nativeSessionCaptureVersion'");
6654
- if (nativeHarnesses !== void 0 && (!Array.isArray(nativeHarnesses) || nativeHarnesses.some((harness) => typeof harness !== "string") || new Set(nativeHarnesses).size !== nativeHarnesses.length)) invalidCapabilities("malformed 'nativeSessionCaptureHarnesses'");
6655
- const interactionsValue = record.interactions;
6656
- if (interactionsValue === null || typeof interactionsValue !== "object" || Array.isArray(interactionsValue)) invalidCapabilities("a malformed 'interactions' group");
6657
- const interactionsRecord = interactionsValue;
6658
- if ("exactBeforeToolApproval" in interactionsRecord && typeof interactionsRecord.exactBeforeToolApproval !== "boolean") invalidCapabilities("a non-boolean 'interactions.exactBeforeToolApproval' flag");
6659
- if (typeof interactionsRecord.responseDedupe !== "boolean") invalidCapabilities("a missing or non-boolean 'interactions.responseDedupe' flag");
6660
- const interactiveAgentValue = record.interactiveAgent;
6661
- let interactiveAgent;
6662
- if (interactiveAgentValue !== void 0) {
6663
- if (interactiveAgentValue === null || typeof interactiveAgentValue !== "object" || Array.isArray(interactiveAgentValue)) invalidCapabilities("a malformed 'interactiveAgent' group");
6664
- const interactiveAgentRecord = interactiveAgentValue;
6665
- if ("claudeSubscription" in interactiveAgentRecord && typeof interactiveAgentRecord.claudeSubscription !== "boolean") invalidCapabilities("a non-boolean 'interactiveAgent.claudeSubscription' flag");
6666
- interactiveAgent = {
6667
- ...readFlagGroup(record, "interactiveAgent", [
6668
- "start",
6669
- "status",
6670
- "attach",
6671
- "control",
6672
- "reattach",
6673
- "sendPrompt",
6674
- "input",
6675
- "resize",
6676
- "stop"
6677
- ]),
6678
- ...typeof interactiveAgentRecord.claudeSubscription === "boolean" ? { claudeSubscription: interactiveAgentRecord.claudeSubscription } : {}
6679
- };
6680
- }
9926
+ const interactions = asRecord(record.interactions) ?? {};
9927
+ const interactive = asRecord(record.interactiveAgent);
6681
9928
  return {
6682
9929
  schema: 1,
6683
- ...typeof record.cliAuthReferences === "boolean" ? { cliAuthReferences: record.cliAuthReferences } : {},
6684
- ...typeof record.claudeTokenContinuations === "boolean" ? { claudeTokenContinuations: record.claudeTokenContinuations } : {},
6685
- ...typeof record.codexCredentialContinuations === "boolean" ? { codexCredentialContinuations: record.codexCredentialContinuations } : {},
6686
- ...typeof nativeVersion === "number" ? { nativeSessionCaptureVersion: nativeVersion } : {},
6687
- ...Array.isArray(nativeHarnesses) ? { nativeSessionCaptureHarnesses: nativeHarnesses.filter(isBackendType) } : {},
9930
+ ...optional(record, "cliAuthReferences"),
9931
+ ...optional(record, "claudeTokenContinuations"),
9932
+ ...optional(record, "codexCredentialContinuations"),
9933
+ ...typeof nativeVersion === "number" && Number.isSafeInteger(nativeVersion) && nativeVersion >= 1 ? { nativeSessionCaptureVersion: nativeVersion } : {},
9934
+ ...Array.isArray(nativeHarnesses) ? { nativeSessionCaptureHarnesses: [...new Set(nativeHarnesses.filter(isBackendType))] } : {},
6688
9935
  agentInterface: record.agentInterface,
6689
9936
  sidecarVersion: record.sidecarVersion,
6690
9937
  image: record.image,
6691
- dispatch: readFlagGroup(record, "dispatch", ["runControlRef", "executionIdOnAdmission"]),
6692
- cancel: readFlagGroup(record, "cancel", [
9938
+ dispatch: flags(record.dispatch, ["runControlRef", "executionIdOnAdmission"]),
9939
+ cancel: flags(record.cancel, [
6693
9940
  "canonicalRunCancellation",
6694
9941
  "digestBound",
6695
9942
  "idempotent"
6696
9943
  ]),
6697
- runs: readFlagGroup(record, "runs", ["executionScopedStatus", "eventReplay"]),
9944
+ runs: flags(record.runs, ["executionScopedStatus", "eventReplay"]),
6698
9945
  interactions: {
6699
- responseDedupe: interactionsRecord.responseDedupe,
6700
- ...typeof interactionsRecord.exactBeforeToolApproval === "boolean" ? { exactBeforeToolApproval: interactionsRecord.exactBeforeToolApproval } : {}
9946
+ responseDedupe: interactions.responseDedupe === true,
9947
+ ...optional(interactions, "exactBeforeToolApproval")
6701
9948
  },
6702
- ...interactiveAgent === void 0 ? {} : { interactiveAgent }
9949
+ ...interactive ? { interactiveAgent: {
9950
+ ...flags(interactive, [
9951
+ "start",
9952
+ "status",
9953
+ "attach",
9954
+ "control",
9955
+ "reattach",
9956
+ "sendPrompt",
9957
+ "input",
9958
+ "resize",
9959
+ "stop"
9960
+ ]),
9961
+ ...optional(interactive, "claudeSubscription")
9962
+ } } : {}
6703
9963
  };
6704
9964
  }
6705
9965
  //#endregion
@@ -6780,7 +10040,7 @@ var SandboxRuntimeOperations = class extends SandboxLifecycleCapabilities {
6780
10040
  });
6781
10041
  if (!response.ok) throw parseErrorResponse(response.status, await response.text());
6782
10042
  const value = await readResponseJson(response);
6783
- const pending = value && typeof value === "object" && "proxySecretReceipt" in value ? ProxySecretReceiptSchema.safeParse(value.proxySecretReceipt) : void 0;
10043
+ const pending = value && typeof value === "object" && "proxySecretReceipt" in value ? ProxySecretReceiptSchema$1.safeParse(value.proxySecretReceipt) : void 0;
6784
10044
  if (!value || typeof value !== "object" || (pending ? !pending.success || pending.data.status !== "proxy-installed" || pending.data.sandboxId !== this.id || !pending.data.bindings.length || pending.data.bindings.some((binding) => binding.secretRef.key !== cliAuth.secretEnv) || "installed" in value : !("installed" in value) || value.installed !== true) || !("harness" in value) || value.harness !== grant.harness || !("cliAuth" in value)) throw new StateError("Native credential grant receipt is invalid", { currentState: "unconfirmed" });
6785
10045
  const confirmed = cliAuthReferenceSchema.safeParse(value.cliAuth);
6786
10046
  if (!confirmed.success || confirmed.data.account !== cliAuth.account || confirmed.data.secretEnv !== cliAuth.secretEnv || confirmed.data.format !== cliAuth.format) throw new StateError("Native credential grant receipt names another reference", { currentState: "unconfirmed" });
@@ -7298,7 +10558,7 @@ var SandboxProfileCapabilities = class extends SandboxFileWriteCapabilities {
7298
10558
  * back to sending the file-free profile inline).
7299
10559
  */
7300
10560
  async primeProfile(profile, options = {}) {
7301
- const parsed = agentProfileSchema.safeParse(profile);
10561
+ const parsed = agentProfileSchema$1.safeParse(profile);
7302
10562
  if (!parsed.success) throw new ValidationError("Profile priming requires an AgentProfile object");
7303
10563
  if (options.preserveManagedProfile) {
7304
10564
  const snapshot = JSON.parse(JSON.stringify(profile));
@@ -8819,7 +12079,7 @@ var SandboxInteractiveCapabilities = class extends SandboxPromptCapabilities {
8819
12079
  var SandboxSessionEvidenceCapabilities = class extends SandboxInteractiveCapabilities {
8820
12080
  /** @internal — invoked before the sandbox is deleted. */
8821
12081
  async _sessionExportRawEvidence(id, destination, options) {
8822
- const { exportRawEvidenceDirectory } = await import("./raw-evidence-archive-DrgeV9_0.js");
12082
+ const { exportRawEvidenceDirectory } = await import("./raw-evidence-archive-BqN1_X-V.js");
8823
12083
  await this.ensureRunning();
8824
12084
  await this.refresh();
8825
12085
  return exportRawEvidenceDirectory((signal, archiveId, cancel) => this.runtimeFetch(`/agents/sessions/${encodeURIComponent(id)}/raw-evidence/archive?${new URLSearchParams([
@@ -8850,7 +12110,7 @@ var SandboxSessionEvidenceCapabilities = class extends SandboxInteractiveCapabil
8850
12110
  * and the byte and file bounds are verified before the directory appears.
8851
12111
  */
8852
12112
  async exportRawEvidence(destination, options) {
8853
- const { exportRawEvidenceDirectory } = await import("./raw-evidence-archive-DrgeV9_0.js");
12113
+ const { exportRawEvidenceDirectory } = await import("./raw-evidence-archive-BqN1_X-V.js");
8854
12114
  await this.ensureRunning();
8855
12115
  await this.refresh();
8856
12116
  return exportRawEvidenceDirectory((signal, archiveId, cancel) => this.runtimeFetch(`/agents/raw-evidence/archive?${new URLSearchParams({
@@ -10982,7 +14242,7 @@ var SandboxFilesystemOperations = class extends DeclaredFilesystemOperations {
10982
14242
  totalBytes: size,
10983
14243
  percentage: 0
10984
14244
  });
10985
- const { uploadChunkedFromFile } = await import("./chunked-upload-file-D3YxQdAl.js");
14245
+ const { uploadChunkedFromFile } = await import("./chunked-upload-file-FxIlaF8n.js");
10986
14246
  await uploadChunkedFromFile({ fetch: (path, init) => this.host.runtimeFetch(path, init) }, remotePath, localPath, {
10987
14247
  mode: options?.permissions,
10988
14248
  onProgress: options?.onProgress ? (progress) => {
@@ -11890,4 +15150,4 @@ var SandboxInstance = class SandboxInstance extends SandboxEgressCapabilities {
11890
15150
  }
11891
15151
  };
11892
15152
  //#endregion
11893
- export { normalizeSandboxCreateReceipt as A, CAPACITY_ETA_WAIT_MAX_MS as B, SandboxOperationFailedError as C, validateDeferredProfileFileMounts as D, splitInlineProfileSkills as E, normalizeConnection as F, createRetryDelayMs as G, DEFAULT_GPU_CREATE_TIMEOUT_MS as H, normalizeEgressPolicyFields as I, isCapacityShortageCreateError as J, extendableDeadline as K, normalizeProxySecretReceipt as L, readFilesystemIncarnationTuple as M, dateOf as N, isRetryableProfileFileMaterializeFailure as O, parseLifecycleTimes as P, canonicalAgentProfileDigest as Q, normalizeSandboxShape as R, SandboxOperation as S, splitInlineProfileFileMounts as T, DEPLOY_WINDOW_RETRY_MS as U, DEFAULT_CREATE_TIMEOUT_MS as V, awaitCreateResend as W, isRateLimitCreateError as X, isDeployWindowCreateError as Y, isRetryableCreateError as Z, collectAgentFinalMessageText as _, buildTraceExportPayload as a, isToolBearingEvent as b, toOtelJson as c, sandboxLedgerUsd as d, InteractiveSessionHandle as f, applySandboxEventText as g, createInteractiveTerminalSession as h, MAX_EGRESS_DENIALS_LIMIT as i, normalizeStartupDiagnostics as j, normalizeCaptureProof as k, SandboxTaskSession as l, createInteractiveTerminalCapture as m, createSandboxInstanceFromResponse as n, exportTraceBundle as o, InteractiveTerminalFrameLog as p, generateIdempotencyKey as q, WorkspaceImages as r, otelTraceIdForTangleTrace as s, SandboxInstance as t, SandboxSession as u, collectAgentResponseText as v, materializeProfileFileMounts as w, ManagedProcessClient as x, getSandboxEventText as y, CAPACITY_ETA_MARGIN_MS as z };
15153
+ export { isCapacityShortageCreateError as $, ProfileUnsupportedError as A, normalizeConnection as B, SandboxOperationFailedError as C, validateDeferredProfileFileMounts as D, splitInlineProfileSkills as E, normalizeSandboxCreateReceipt as F, CAPACITY_ETA_WAIT_MAX_MS as G, normalizeProxySecretReceipt as H, normalizeStartupDiagnostics as I, DEPLOY_WINDOW_RETRY_MS as J, DEFAULT_CREATE_TIMEOUT_MS as K, readFilesystemIncarnationTuple as L, isMaterializerHarness as M, materializeProfile as N, isRetryableProfileFileMaterializeFailure as O, normalizeCaptureProof as P, generateIdempotencyKey as Q, dateOf as R, SandboxOperation as S, splitInlineProfileFileMounts as T, normalizeSandboxShape as U, normalizeEgressPolicyFields as V, CAPACITY_ETA_MARGIN_MS as W, createRetryDelayMs as X, awaitCreateResend as Y, extendableDeadline as Z, collectAgentFinalMessageText as _, buildTraceExportPayload as a, isToolBearingEvent as b, toOtelJson as c, sandboxLedgerUsd as d, isDeployWindowCreateError as et, InteractiveSessionHandle as f, applySandboxEventText as g, createInteractiveTerminalSession as h, MAX_EGRESS_DENIALS_LIMIT as i, enforceWorkspacePlanSupport as j, HARNESS_LAUNCH_MATERIALIZE_OPTIONS as k, SandboxTaskSession as l, createInteractiveTerminalCapture as m, createSandboxInstanceFromResponse as n, isRetryableCreateError as nt, exportTraceBundle as o, InteractiveTerminalFrameLog as p, DEFAULT_GPU_CREATE_TIMEOUT_MS as q, WorkspaceImages as r, canonicalAgentProfileDigest as rt, otelTraceIdForTangleTrace as s, SandboxInstance as t, isRateLimitCreateError as tt, SandboxSession as u, collectAgentResponseText as v, materializeProfileFileMounts as w, ManagedProcessClient as x, getSandboxEventText as y, parseLifecycleTimes as z };