@shuind/dsh-codex-harness 0.2.21 → 0.2.32-dsh-v0.2.2-rc.1

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 (128) hide show
  1. package/CHANGELOG.md +121 -0
  2. package/README.md +48 -38
  3. package/RELEASE.md +61 -0
  4. package/assets/codex.svg +5 -0
  5. package/cordis.patch.yml +150 -6
  6. package/docs/preset-library.md +39 -23
  7. package/docs/tool-policy-benchmark.json +310 -0
  8. package/docs/tool-policy.md +144 -0
  9. package/lib/client.js +1639 -111
  10. package/lib/compaction.js +17 -2
  11. package/lib/index.js +799 -188
  12. package/lib/installer.js +50 -6
  13. package/lib/preferences.js +111 -0
  14. package/lib/tool-policy.js +2235 -0
  15. package/lib/typert.js +57 -10
  16. package/lib/types/activity.d.ts +1 -1
  17. package/lib/types/activity.js +50 -14
  18. package/lib/types/client/activity.d.ts +33 -9
  19. package/lib/types/client/desktop.d.ts +43 -0
  20. package/lib/types/client/desktop.js +121 -0
  21. package/lib/types/client/entry.d.ts +10 -0
  22. package/lib/types/client/entry.js +12 -0
  23. package/lib/types/client/index.d.ts +109 -19
  24. package/lib/types/client/index.js +21 -40
  25. package/lib/types/client/policy-drafts.d.ts +25 -0
  26. package/lib/types/client/policy-drafts.js +47 -0
  27. package/lib/types/client/preset-copy.d.ts +1 -0
  28. package/lib/types/client/preset-copy.js +2 -0
  29. package/lib/types/client/preset-manager.d.ts +12 -2
  30. package/lib/types/client/preset-manager.js +70 -25
  31. package/lib/types/client/preset-requests.d.ts +12 -0
  32. package/lib/types/client/preset-requests.js +101 -0
  33. package/lib/types/client/session.d.ts +6 -0
  34. package/lib/types/client/session.js +9 -0
  35. package/lib/types/client/tool-policy.d.ts +120 -0
  36. package/lib/types/client/tool-policy.js +394 -0
  37. package/lib/types/compaction.d.ts +3 -3
  38. package/lib/types/compaction.js +6 -2
  39. package/lib/types/desktop-preset.d.ts +20 -0
  40. package/lib/types/desktop-preset.js +39 -0
  41. package/lib/types/exec.d.ts +4 -0
  42. package/lib/types/exec.js +192 -66
  43. package/lib/types/host-settings.d.ts +4 -0
  44. package/lib/types/host-settings.js +13 -0
  45. package/lib/types/index.d.ts +20 -2
  46. package/lib/types/index.js +181 -68
  47. package/lib/types/installer.js +11 -2
  48. package/lib/types/preferences.d.ts +11 -0
  49. package/lib/types/preferences.js +16 -0
  50. package/lib/types/preset-editor-remote.d.ts +2 -0
  51. package/lib/types/preset-editor-remote.js +6 -2
  52. package/lib/types/preset-editor.d.ts +12 -7
  53. package/lib/types/preset-editor.js +43 -13
  54. package/lib/types/preset-prompt-catalog-schema.d.ts +16 -0
  55. package/lib/types/preset-prompt-catalog-schema.js +11 -0
  56. package/lib/types/preset-prompt-catalog.d.ts +21 -0
  57. package/lib/types/preset-prompt-catalog.js +192 -0
  58. package/lib/types/preset-prompt-contract.d.ts +22 -0
  59. package/lib/types/preset-prompt-contract.js +3 -0
  60. package/lib/types/preset-tool-catalog-schema.d.ts +38 -0
  61. package/lib/types/preset-tool-catalog-schema.js +28 -0
  62. package/lib/types/preset-tool-catalog.d.ts +5 -0
  63. package/lib/types/preset-tool-catalog.js +51 -0
  64. package/lib/types/prompt-sections.d.ts +1 -1
  65. package/lib/types/prompt-sections.js +9 -3
  66. package/lib/types/prompt.js +4 -2
  67. package/lib/types/remote.js +23 -8
  68. package/lib/types/settings.d.ts +3 -3
  69. package/lib/types/settings.js +3 -3
  70. package/lib/types/tool-capabilities.d.ts +32 -0
  71. package/lib/types/tool-capabilities.js +42 -0
  72. package/lib/types/tool-policy-contract.d.ts +60 -0
  73. package/lib/types/tool-policy-contract.js +26 -0
  74. package/lib/types/tool-policy.d.ts +171 -0
  75. package/lib/types/tool-policy.js +367 -0
  76. package/lib/types/typert.host.d.ts +2 -2
  77. package/lib/types/typert.host.js +12 -2
  78. package/locale/en.json +6 -0
  79. package/locale/tool-policy/en.json +6 -0
  80. package/locale/tool-policy/zh.json +6 -0
  81. package/locale/zh.json +6 -0
  82. package/package.json +375 -299
  83. package/scripts/benchmark-tool-policy.mjs +186 -0
  84. package/scripts/build-preset.mjs +19 -0
  85. package/scripts/clean-build.mjs +11 -0
  86. package/src/activity-types.ts +7 -0
  87. package/src/activity.ts +158 -0
  88. package/src/client/activity.ts +82 -0
  89. package/src/client/desktop.tsx +162 -0
  90. package/src/client/entry.tsx +16 -0
  91. package/src/client/index.tsx +972 -0
  92. package/src/client/policy-drafts.ts +56 -0
  93. package/src/client/preset-copy.ts +83 -0
  94. package/src/client/preset-manager.tsx +281 -0
  95. package/src/client/preset-requests.ts +113 -0
  96. package/src/client/session.ts +11 -0
  97. package/src/client/tool-policy.tsx +380 -0
  98. package/src/compact-command.ts +112 -0
  99. package/src/compaction.ts +190 -0
  100. package/src/context.ts +15 -0
  101. package/src/desktop-preset.ts +55 -0
  102. package/src/exec.ts +570 -0
  103. package/src/host-settings.ts +17 -0
  104. package/src/index.ts +1097 -0
  105. package/src/installer.ts +172 -0
  106. package/src/invariant.ts +34 -0
  107. package/src/patch.ts +258 -0
  108. package/src/preferences.ts +17 -0
  109. package/src/preset-contract.ts +85 -0
  110. package/src/preset-editor-remote.ts +41 -0
  111. package/src/preset-editor.ts +502 -0
  112. package/src/preset-prompt-catalog-schema.ts +10 -0
  113. package/src/preset-prompt-catalog.ts +191 -0
  114. package/src/preset-prompt-contract.ts +21 -0
  115. package/src/preset-tool-catalog-schema.ts +28 -0
  116. package/src/preset-tool-catalog.ts +51 -0
  117. package/src/prompt-sections.ts +33 -0
  118. package/src/prompt.ts +62 -0
  119. package/src/remote.ts +748 -0
  120. package/src/settings.ts +79 -0
  121. package/src/tool-capabilities.ts +76 -0
  122. package/src/tool-policy-contract.ts +76 -0
  123. package/src/tool-policy.ts +388 -0
  124. package/src/typert.host.ts +119 -0
  125. package/tsconfig.json +29 -0
  126. package/tsdown.config.ts +110 -0
  127. package/lib/types/preset-templates.d.ts +0 -36
  128. package/lib/types/preset-templates.js +0 -12
package/lib/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import z from "@deepseek-ai/schemastery";
2
2
  import { defineTool } from "@deepseek-ai/dsh-tools";
3
+ import { ESCALATION_TARGETS, approveEscalation, escalationHintMarker, sandboxDenialMarker, sandboxPermissionsDescription, validateEscalationArgs } from "@deepseek-ai/dsh-sandbox";
3
4
  import { createHash, randomBytes, randomUUID } from "node:crypto";
4
5
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
6
+ import { HarnessError } from "@deepseek-ai/dsh-llm";
5
7
  import { credentialRef } from "@deepseek-ai/dsh-credentials";
6
8
  import { AsyncLocalStorage } from "node:async_hooks";
7
9
  import { mkdirSync, writeFileSync } from "node:fs";
@@ -11,6 +13,8 @@ import BasicCompactionEngine from "@deepseek-ai/dsh-compaction-basic";
11
13
  import { readFile, realpath, stat, unlink } from "node:fs/promises";
12
14
  import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
13
15
  import { Scalar, YAMLMap, isMap, isScalar, isSeq, parseDocument } from "yaml";
16
+ import { createScope } from "@deepseek-ai/dsh-scope";
17
+ import { PERSONA_PREFIX_SECTION, PERSONA_SUFFIX_SECTION } from "@deepseek-ai/dsh-system-prompt";
14
18
  //#region lib/types/patch.js
15
19
  /** Parser and line-oriented applicator for Codex's `apply_patch` language. */
16
20
  const APPLY_PATCH_DESCRIPTION = "Edits files using Codex patch syntax with Begin/End Patch markers and file update directives. In hunk lines, the first character is the operation marker; repeat a source-leading marker when the source line itself starts with one.";
@@ -269,13 +273,52 @@ function renderExecResult(result) {
269
273
  sections.push("Output:", result.output);
270
274
  return sections.join("\n");
271
275
  }
272
- function sessionCwd$1(exec, workdir) {
273
- const base = exec.agent?.session.header.cwd ?? process.cwd();
274
- if (workdir === void 0) return exec.agent?.session.header.cwd;
275
- return resolve(base, workdir);
276
+ function sessionCwd$1(ctx, exec, workdir) {
277
+ const directories = ctx.get("workingDirectory");
278
+ const cwd = exec.agent === void 0 ? void 0 : directories?.get(exec.agent.session) ?? exec.agent.session.header.cwd;
279
+ return workdir === void 0 ? cwd : resolve(cwd ?? process.cwd(), workdir);
280
+ }
281
+ /** Per-call shell selection belonged to legacy providers, not the current shell seam. */
282
+ function supportsLegacyShellOptions(ctx) {
283
+ const shell = ctx.get("shell");
284
+ if (shell === void 0) throw new Error("exec_command requires ctx.shell");
285
+ return typeof shell.execute !== "function";
286
+ }
287
+ /** Surface infrastructure failures from the current execution handle without reclassifying nonzero exits. */
288
+ async function assertShellCompleted(process, escalationAvailable = false) {
289
+ const result = process.result;
290
+ if (typeof result !== "function") return void 0;
291
+ try {
292
+ return await result.call(process);
293
+ } catch (error) {
294
+ const notes = sandboxNotes(process.sandbox, escalationAvailable);
295
+ if (notes.length === 0) throw error;
296
+ const message = [error instanceof Error ? error.message : String(error), ...notes].join("\n");
297
+ const failure = error instanceof HarnessError ? new HarnessError(message, error.code, { cause: error }) : new Error(message, { cause: error });
298
+ if (error instanceof Error) failure.name = error.name;
299
+ throw failure;
300
+ }
276
301
  }
277
- function readShellOutput(read, maxBytes) {
278
- return limitOutput(read.delta, maxBytes);
302
+ /** Preserve policy/runner facts after bounding command output; never truncate these markers. */
303
+ function sandboxNotes(sandbox, escalationAvailable) {
304
+ if (sandbox?.runnerFailed) return [`[sandbox: the sandbox runner itself failed under ${sandbox.mode} mode — the command did not run; this is a sandbox problem, not a command failure]`];
305
+ if (!sandbox?.denied) return [];
306
+ return [sandboxDenialMarker(sandbox.mode), ...escalationAvailable ? [escalationHintMarker("command")] : []];
307
+ }
308
+ /** Current executors prepare asynchronously; old providers published a handle synchronously. */
309
+ function startShell(ctx, request) {
310
+ const provider = ctx.get("shell");
311
+ if (provider === void 0) throw new Error("exec_command requires ctx.shell");
312
+ const shell = provider;
313
+ const spec = shell.resolve(request);
314
+ if (typeof shell.execute === "function") return shell.execute(spec);
315
+ if (typeof shell.start === "function") return shell.start(spec);
316
+ throw new Error("exec_command: the configured shell has no execution capability");
317
+ }
318
+ function readShellOutput(read, maxBytes, sandbox, escalationAvailable = false) {
319
+ const output = limitOutput(read.delta, maxBytes);
320
+ const notes = sandboxNotes(sandbox, escalationAvailable);
321
+ return notes.length === 0 ? output : `${output}${output.length > 0 && !output.endsWith("\n") ? "\n" : ""}${notes.join("\n")}`;
279
322
  }
280
323
  function terminalResult(result, maxBytes, startedAt) {
281
324
  const output = limitOutput(result.viewport, maxBytes);
@@ -286,38 +329,40 @@ function terminalResult(result, maxBytes, startedAt) {
286
329
  });
287
330
  }
288
331
  /** Map a detached shell process onto the generic DSH job outcome contract. */
289
- function backgroundOutcome(process) {
290
- if (process.status === "killed") return {
332
+ function backgroundOutcome(process, escalationAvailable, sandbox = process.sandbox) {
333
+ const base = process.status === "killed" ? {
291
334
  status: "killed",
292
335
  detail: process.signal !== null ? `signal: ${process.signal}` : "killed before exit"
293
- };
294
- return {
336
+ } : {
295
337
  status: "completed",
296
338
  detail: `exit code: ${process.exitCode ?? 0}`
297
339
  };
340
+ const notes = sandboxNotes(sandbox, escalationAvailable);
341
+ return notes.length === 0 ? base : {
342
+ ...base,
343
+ detail: `${base.detail}; ${notes.join(" ")}`
344
+ };
298
345
  }
299
- function sleep(ms, signal) {
300
- return new Promise((resolve) => {
301
- let timer;
302
- const finish = (result) => {
303
- if (timer !== void 0) clearTimeout(timer);
304
- signal.removeEventListener("abort", onAbort);
305
- resolve(result);
306
- };
307
- const onAbort = () => finish("aborted");
346
+ async function waitForShell(process, ms, signal) {
347
+ let timer;
348
+ let onAbort = () => {};
349
+ const elapsed = new Promise((resolve) => {
350
+ onAbort = () => resolve(false);
308
351
  if (signal.aborted) {
309
- finish("aborted");
352
+ onAbort();
310
353
  return;
311
354
  }
312
355
  signal.addEventListener("abort", onAbort, { once: true });
313
- timer = setTimeout(() => finish("elapsed"), ms);
356
+ timer = setTimeout(() => resolve(void 0), ms);
314
357
  });
315
- }
316
- async function waitForShell(process, ms, signal) {
317
- const timer = sleep(ms, signal);
318
- const completed = await Promise.race([process.done.then(() => true), timer.then((result) => result === "aborted" ? false : void 0)]);
319
- if (signal.aborted) signal.throwIfAborted();
320
- return completed === true || process.status !== "running";
358
+ try {
359
+ const completed = await Promise.race([process.done.then(() => true), elapsed]);
360
+ if (signal.aborted) signal.throwIfAborted();
361
+ return completed === true || process.status !== "running";
362
+ } finally {
363
+ if (timer !== void 0) clearTimeout(timer);
364
+ signal.removeEventListener("abort", onAbort);
365
+ }
321
366
  }
322
367
  /** Stop a pipe-backed session when the current Codex tool is cancelled. */
323
368
  async function stopShellOnAbort(process, signal) {
@@ -347,7 +392,35 @@ async function runExecCommand(ctx, args, exec, config) {
347
392
  if (args.cmd.trim().length === 0) throw new Error("cmd must be a non-empty string");
348
393
  positiveFinite("yield_time_ms", args.yield_time_ms);
349
394
  const maxBytes = outputLimit(config.maxOutputBytes, args.max_output_tokens);
350
- const workdir = sessionCwd$1(exec, args.workdir);
395
+ const legacyShellOptions = supportsLegacyShellOptions(ctx);
396
+ if (!legacyShellOptions && (args.shell !== void 0 || args.login !== void 0)) throw new Error("exec_command: this host selects the shell and startup mode in its configuration; per-call shell/login options are unavailable");
397
+ validateEscalationArgs(args.sandbox_permissions, args.justification);
398
+ const confines = ctx.get("shell")?.sandboxMode !== void 0;
399
+ const policyService = ctx.get("sandboxPolicy");
400
+ if (confines && policyService === void 0) throw new Error("exec_command: a sandboxing shell requires ctx.sandboxPolicy");
401
+ if (confines && args.tty === true) throw new Error("exec_command: tty=true cannot carry the sandbox policy; use pipe-backed execution on this host");
402
+ let policy = policyService?.resolve(exec.agent === void 0 ? {} : { session: exec.agent.session });
403
+ if (args.sandbox_permissions !== void 0) {
404
+ if (!confines) throw new Error("sandbox_permissions is not available in this composition (no sandboxing executor to escalate)");
405
+ const approvedMode = await approveEscalation({
406
+ requestedMode: args.sandbox_permissions,
407
+ justification: args.justification,
408
+ effectiveMode: policy.mode,
409
+ subject: "command"
410
+ }, {
411
+ approver: ctx.get("approval"),
412
+ agent: exec.agent,
413
+ callId: exec.callId,
414
+ toolName: "exec_command",
415
+ signal: exec.signal
416
+ });
417
+ exec.signal.throwIfAborted();
418
+ policy = {
419
+ ...policy,
420
+ mode: approvedMode
421
+ };
422
+ }
423
+ const workdir = sessionCwd$1(ctx, exec, args.workdir);
351
424
  const startedAt = performance.now();
352
425
  if (args.run_in_background === true && args.tty === true) throw new Error("run_in_background is only supported for pipe-backed commands; omit tty");
353
426
  if (args.tty === true) {
@@ -356,8 +429,10 @@ async function runExecCommand(ctx, args, exec, config) {
356
429
  if (agent === void 0 || terminals === void 0) throw new Error("exec_command with tty=true requires the dsh terminal capability and an owning agent session");
357
430
  const spawnRequest = {
358
431
  type: "shell",
359
- ...args.shell === void 0 ? {} : { shell: args.shell },
360
- login: args.login ?? true,
432
+ ...legacyShellOptions ? {
433
+ ...args.shell === void 0 ? {} : { shell: args.shell },
434
+ login: args.login ?? true
435
+ } : {},
361
436
  ...workdir === void 0 ? {} : { cwd: workdir }
362
437
  };
363
438
  const spawned = await terminals.spawn(agent, spawnRequest, exec.signal);
@@ -385,12 +460,14 @@ async function runExecCommand(ctx, args, exec, config) {
385
460
  if (!retained) await terminals.kill(agent, spawned.sessionId, closeReason);
386
461
  }
387
462
  }
388
- const policy = ctx.get("sandboxPolicy")?.resolve(exec.agent === void 0 ? {} : { session: exec.agent.session });
389
463
  const dshEnv = ctx.get("shellEnv")?.collect(exec);
390
464
  const shellRequest = {
391
465
  command: commandFor(args),
392
- ...args.shell === void 0 ? {} : { shell: args.shell },
393
- login: args.login ?? true,
466
+ onExpiry: "none",
467
+ ...legacyShellOptions ? {
468
+ ...args.shell === void 0 ? {} : { shell: args.shell },
469
+ login: args.login ?? true
470
+ } : {},
394
471
  ...workdir === void 0 ? {} : { workdir },
395
472
  stdoutMaxBytes: maxBytes,
396
473
  ...dshEnv === void 0 ? {} : { dshEnv },
@@ -405,19 +482,57 @@ async function runExecCommand(ctx, args, exec, config) {
405
482
  exec.signal.throwIfAborted();
406
483
  throw new Error("tool call aborted");
407
484
  }
485
+ const ringBacked = typeof jobs.readAt === "function";
486
+ let process;
487
+ let cancelled = false;
488
+ const lifetime = new AbortController();
489
+ const start = () => {
490
+ const prepared = startShell(ctx, {
491
+ ...shellRequest,
492
+ ...ringBacked ? { signal: lifetime.signal } : {}
493
+ });
494
+ return {
495
+ cancel: () => {
496
+ cancelled = true;
497
+ lifetime.abort();
498
+ process?.kill();
499
+ },
500
+ done: (async () => {
501
+ try {
502
+ process = "then" in prepared ? await prepared : prepared;
503
+ if (cancelled) process.kill();
504
+ await process.done;
505
+ const completed = await assertShellCompleted(process, confines);
506
+ return backgroundOutcome(process, confines, completed?.sandbox ?? process.sandbox);
507
+ } catch (error) {
508
+ if (cancelled) return {
509
+ status: "killed",
510
+ detail: "cancelled during shell preparation"
511
+ };
512
+ return {
513
+ status: "failed",
514
+ detail: [error instanceof Error ? error.message : String(error), ...sandboxNotes(process?.sandbox, confines)].join("; ")
515
+ };
516
+ }
517
+ })(),
518
+ ...ringBacked ? {} : { readOutput: () => process === void 0 ? "" : readShellOutput(process.readOutput(), maxBytes, process.sandbox, confines) }
519
+ };
520
+ };
521
+ const output = ["stdout", "stderr"].map((channel) => ({
522
+ channel,
523
+ read: (fromByte) => process?.observed?.[channel].readFrom(fromByte) ?? {
524
+ text: "",
525
+ nextOffset: fromByte,
526
+ lossy: false
527
+ }
528
+ }));
408
529
  const id = jobs.start({
409
530
  kind: "bash",
410
531
  label: args.cmd,
411
- owner,
532
+ owner: ringBacked ? owner.id : owner,
412
533
  outputLimitBytes: maxBytes,
413
- run: () => {
414
- const process = ctx.shell.start(ctx.shell.resolve(shellRequest));
415
- return {
416
- cancel: () => void process.kill(),
417
- done: process.done.then(() => backgroundOutcome(process)),
418
- readOutput: () => readShellOutput(process.readOutput(), maxBytes)
419
- };
420
- }
534
+ ...ringBacked ? { output } : {},
535
+ run: start
421
536
  });
422
537
  return withChunkId({
423
538
  wall_time_seconds: (performance.now() - startedAt) / 1e3,
@@ -425,20 +540,26 @@ async function runExecCommand(ctx, args, exec, config) {
425
540
  output: `Started background job ${id}. Use job_output with job_id "${id}" to read output.`
426
541
  });
427
542
  }
428
- const process = ctx.shell.start(ctx.shell.resolve({
543
+ const prepared = startShell(ctx, {
429
544
  ...shellRequest,
430
545
  signal: exec.signal
431
- }));
546
+ });
547
+ const process = "then" in prepared ? await prepared : prepared;
432
548
  try {
433
549
  await waitForShell(process, normalizeWaitMs(args.yield_time_ms, config.defaultYieldTimeMs, false, true), exec.signal);
434
- const output = readShellOutput(process.readOutput(), maxBytes);
550
+ const read = process.readOutput();
435
551
  if (process.status === "running") {
552
+ const output = readShellOutput(read, maxBytes, process.sandbox, confines);
436
553
  if (exec.agent === void 0) {
437
554
  process.kill();
438
555
  await process.done;
556
+ const completed = await assertShellCompleted(process, confines);
439
557
  return withChunkId({
440
558
  wall_time_seconds: (performance.now() - startedAt) / 1e3,
441
- output: readShellOutput(process.readOutput(), maxBytes)
559
+ output: readShellOutput({
560
+ ...read,
561
+ delta: read.delta + process.readOutput().delta
562
+ }, maxBytes, completed?.sandbox ?? process.sandbox, confines)
442
563
  });
443
564
  }
444
565
  return withChunkId({
@@ -446,13 +567,15 @@ async function runExecCommand(ctx, args, exec, config) {
446
567
  output,
447
568
  session_id: allocateSession(exec.agent, {
448
569
  kind: "shell",
449
- process
570
+ process,
571
+ escalationAvailable: confines
450
572
  })
451
573
  });
452
574
  }
575
+ const completed = await assertShellCompleted(process, confines);
453
576
  return withChunkId({
454
577
  wall_time_seconds: (performance.now() - startedAt) / 1e3,
455
- output,
578
+ output: readShellOutput(read, maxBytes, completed?.sandbox ?? process.sandbox, confines),
456
579
  ...process.exitCode === null ? {} : { exit_code: process.exitCode }
457
580
  });
458
581
  } finally {
@@ -461,6 +584,8 @@ async function runExecCommand(ctx, args, exec, config) {
461
584
  }
462
585
  /** Poll or write to one session returned by {@link runExecCommand}. */
463
586
  async function runWriteStdin(ctx, args, exec, config) {
587
+ const escalation = args;
588
+ if (escalation.sandbox_permissions !== void 0 || escalation.justification !== void 0) throw new Error("write_stdin cannot change an existing command sandbox; use exec_command for an approved one-shot retry");
464
589
  positiveFinite("yield_time_ms", args.yield_time_ms);
465
590
  if (!Number.isSafeInteger(args.session_id) || args.session_id <= 0) throw new Error("session_id must be a positive integer");
466
591
  const agent = exec.agent;
@@ -473,18 +598,19 @@ async function runWriteStdin(ctx, args, exec, config) {
473
598
  if (chars.length > 0) throw new Error("this unified exec session uses pipes and does not accept stdin; rerun exec_command with tty=true");
474
599
  try {
475
600
  await waitForShell(session.process, normalizeWaitMs(args.yield_time_ms, config.pollYieldTimeMs, true), exec.signal);
476
- const output = readShellOutput(session.process.readOutput(), maxBytes);
601
+ const read = session.process.readOutput();
477
602
  if (session.process.status !== "running") {
478
603
  forgetSession(agent, args.session_id);
604
+ const completed = await assertShellCompleted(session.process, session.escalationAvailable);
479
605
  return withChunkId({
480
606
  wall_time_seconds: (performance.now() - startedAt) / 1e3,
481
- output,
607
+ output: readShellOutput(read, maxBytes, completed?.sandbox ?? session.process.sandbox, session.escalationAvailable),
482
608
  ...session.process.exitCode === null ? {} : { exit_code: session.process.exitCode }
483
609
  });
484
610
  }
485
611
  return withChunkId({
486
612
  wall_time_seconds: (performance.now() - startedAt) / 1e3,
487
- output,
613
+ output: readShellOutput(read, maxBytes, session.process.sandbox, session.escalationAvailable),
488
614
  session_id: args.session_id
489
615
  });
490
616
  } finally {
@@ -524,6 +650,18 @@ async function runWriteStdin(ctx, args, exec, config) {
524
650
  }
525
651
  }
526
652
  //#endregion
653
+ //#region lib/types/host-settings.js
654
+ /** Host-only reads: never expose the unredacted provider configuration to clients. */
655
+ function readHostSettings(ctx, namespace) {
656
+ const settings = ctx.get("settings");
657
+ if (typeof settings?.get === "function") return settings.get(namespace);
658
+ if (namespace === "codex") {
659
+ const preferences = ctx.get("codexPreferences");
660
+ if (preferences !== void 0) return preferences.current();
661
+ }
662
+ return settings?.describe?.().find((row) => row.ns === namespace)?.value;
663
+ }
664
+ //#endregion
527
665
  //#region lib/types/remote.js
528
666
  const SETTINGS_NAMESPACE = "llm-pi-ai";
529
667
  const REMOTE_COMPACTION_OPEN = "<codex-remote-compaction>";
@@ -541,7 +679,7 @@ function isGptModel$2(model) {
541
679
  return typeof model === "string" && /(?:^|\/)(?:gpt|chatgpt)(?:[-_.]|\d|$)/i.test(model);
542
680
  }
543
681
  function settingsOf(ctx) {
544
- return ctx.get("settings")?.get?.(SETTINGS_NAMESPACE);
682
+ return readHostSettings(ctx, SETTINGS_NAMESPACE);
545
683
  }
546
684
  function profileOf(ctx, provider) {
547
685
  return settingsOf(ctx)?.providers?.[provider];
@@ -895,7 +1033,7 @@ function installHostedWebSearch() {
895
1033
  /** Iterate an existing DSH stream with the hosted-request context installed. */
896
1034
  function hostedWebSearchStream(next, options = {}) {
897
1035
  return (async function* () {
898
- const iterator = next()[Symbol.asyncIterator]();
1036
+ const iterator = HOSTED_REQUESTS.run(options, () => next()[Symbol.asyncIterator]());
899
1037
  let completed = false;
900
1038
  try {
901
1039
  while (true) {
@@ -907,7 +1045,7 @@ function hostedWebSearchStream(next, options = {}) {
907
1045
  yield item.value;
908
1046
  }
909
1047
  } finally {
910
- if (!completed) await iterator.return?.();
1048
+ if (!completed) await HOSTED_REQUESTS.run(options, () => iterator.return?.());
911
1049
  }
912
1050
  })();
913
1051
  }
@@ -949,7 +1087,16 @@ function textOf(message) {
949
1087
  function responsesInput(messages) {
950
1088
  const result = [];
951
1089
  for (const message of messages) {
1090
+ if (message.content.some((block) => block.type === "image" || block.type === "file" || block.type === "tool-addition" || block.type === "tool-removal")) throw new Error("Codex remote compaction requires the DSH adapter for attachments or tool-history updates");
952
1091
  const text = textOf(message);
1092
+ if (message.role === "tool") {
1093
+ result.push({
1094
+ type: "function_call_output",
1095
+ call_id: message.toolCallId,
1096
+ output: text
1097
+ });
1098
+ continue;
1099
+ }
953
1100
  if (message.role === "assistant") {
954
1101
  if (text.length > 0) result.push({
955
1102
  type: "message",
@@ -967,7 +1114,7 @@ function responsesInput(messages) {
967
1114
  });
968
1115
  continue;
969
1116
  }
970
- const role = message.role === "system" ? "developer" : "user";
1117
+ const role = message.role === "system" || message.role === "developer" ? "developer" : "user";
971
1118
  if (text.length > 0) result.push({
972
1119
  type: "message",
973
1120
  role,
@@ -976,12 +1123,15 @@ function responsesInput(messages) {
976
1123
  text
977
1124
  }]
978
1125
  });
979
- for (const block of message.content) {
980
- if (block.type !== "tool-result") continue;
1126
+ const legacyBlocks = message.content;
1127
+ for (const candidate of legacyBlocks) {
1128
+ if (typeof candidate !== "object" || candidate === null) continue;
1129
+ const block = candidate;
1130
+ if (block.type !== "tool-result" || typeof block.toolCallId !== "string" || !Array.isArray(block.content)) continue;
981
1131
  result.push({
982
1132
  type: "function_call_output",
983
1133
  call_id: block.toolCallId,
984
- output: block.content.filter((item) => item.type === "text").map((item) => item.text).join("")
1134
+ output: block.content.filter((item) => item.type === "text").map((item) => item.text ?? "").join("")
985
1135
  });
986
1136
  }
987
1137
  }
@@ -1124,12 +1274,33 @@ function isTokenDelta(chunk) {
1124
1274
  default: return false;
1125
1275
  }
1126
1276
  }
1127
- /** Only a non-empty model delta starts the reply phase; usage and finish frames do not. */
1128
- function startsModelReply(event) {
1129
- if (event.type === "assistant/message") return true;
1130
- if (event.type !== "assistant/chunk" || typeof event.data !== "object" || event.data === null) return false;
1131
- const chunk = event.data.chunk;
1132
- return chunk !== void 0 && isTokenDelta(chunk);
1277
+ /** Read packed v2 streams without importing a helper absent from older DSH packages. */
1278
+ function streamReplyTime(stream) {
1279
+ for (const value of stream) {
1280
+ if (typeof value !== "object" || value === null) continue;
1281
+ const record = value;
1282
+ if (record.type === "chunk") {
1283
+ if (record.chunk !== void 0 && isTokenDelta(record.chunk)) return record.time;
1284
+ continue;
1285
+ }
1286
+ if (record.type !== "text-chunks" && record.type !== "reasoning-chunks" && record.type !== "tool-call-chunks") continue;
1287
+ const fragments = record.type === "tool-call-chunks" ? record.args : record.texts;
1288
+ if (fragments === void 0 || record.time0 === void 0) continue;
1289
+ let time = record.time0;
1290
+ for (const [index, text] of fragments.entries()) {
1291
+ if (index > 0) time += record.dt?.[index - 1] ?? 0;
1292
+ if (text !== "" || record.type === "tool-call-chunks" && record.name !== void 0) return time;
1293
+ }
1294
+ }
1295
+ }
1296
+ /** Only a non-empty delta starts the reply phase; preserve its original stream time. */
1297
+ function modelReplyTime(event) {
1298
+ const data = typeof event.data === "object" && event.data !== null ? event.data : void 0;
1299
+ if (event.type === "assistant/chunk") return data?.chunk !== void 0 && isTokenDelta(data.chunk) ? event.time : void 0;
1300
+ if (event.type === "assistant/message" || event.type === "assistant/attempt") {
1301
+ if (data?.stream !== void 0) return streamReplyTime(data.stream);
1302
+ if (event.type === "assistant/message") return event.time;
1303
+ }
1133
1304
  }
1134
1305
  /** Persisted and wire shape of the Codex activity value. */
1135
1306
  const codexActivitySchema = z$1.union([
@@ -1161,10 +1332,13 @@ function applyCodexActivity(state, event) {
1161
1332
  activity: "requesting-model",
1162
1333
  startedAt: event.time
1163
1334
  };
1164
- if (startsModelReply(event) && (state?.activity === "requesting-model" || state?.activity === "awaiting-model")) return {
1165
- activity: "model-reply",
1166
- startedAt: event.time
1167
- };
1335
+ if (state?.activity === "requesting-model" || state?.activity === "awaiting-model") {
1336
+ const startedAt = modelReplyTime(event);
1337
+ if (startedAt !== void 0) return {
1338
+ activity: "model-reply",
1339
+ startedAt
1340
+ };
1341
+ }
1168
1342
  if (event.type === "turn/start" || event.type === "turn/end" || event.type === "compaction/end") return null;
1169
1343
  if ((state?.activity === "requesting-model" || state?.activity === "model-reply" || state?.activity === "awaiting-model") && (event.type === "llm/retry" || event.type === "tool/call" || event.type === "step/end")) return null;
1170
1344
  return state;
@@ -1180,12 +1354,12 @@ const codexActivityProjection = {
1180
1354
  },
1181
1355
  schema: codexActivitySchema,
1182
1356
  view: (state) => state,
1183
- stateVersion: 2
1357
+ stateVersion: 3
1184
1358
  };
1185
1359
  /** Register the optional activity unit without requiring the projection seam in every assembly. */
1186
1360
  function registerCodexActivityProjection(ctx) {
1187
- ctx.inject(["sessionProjections"], (projectionCtx) => {
1188
- projectionCtx.sessionProjections.register(codexActivityProjection);
1361
+ ctx.inject(["sessionProjections"], async (projectionCtx) => {
1362
+ await projectionCtx.sessionProjections.register(codexActivityProjection);
1189
1363
  });
1190
1364
  }
1191
1365
  //#endregion
@@ -1193,7 +1367,7 @@ function registerCodexActivityProjection(ctx) {
1193
1367
  /** Default plugin-owned Codex operating prompt. */
1194
1368
  const DEFAULT_CODEX_SYSTEM_PROMPT = String.raw`## General
1195
1369
 
1196
- - When searching for text or files, prefer using rg or rg --files respectively because rg is much faster than alternatives like grep. If rg is not available, use the next best alternative.
1370
+ - Follow the current tool catalog, not assumptions from another Codex client. For unknown paths, use the available list/search tools instead of guessing and reuse the returned paths. If only shell search is available, prefer rg or rg --files.
1197
1371
 
1198
1372
  ## Editing constraints
1199
1373
 
@@ -1209,6 +1383,8 @@ const DEFAULT_CODEX_SYSTEM_PROMPT = String.raw`## General
1209
1383
  ## dsh session
1210
1384
 
1211
1385
  - The user and you share one workspace. Inspect the repository and every applicable AGENTS.md before editing.
1386
+ - For Harness APIs, first load the relevant Harness skill. When Inspect tools are available, start with cordis_inspect_list, then query the provider's directory before an exact Service contract. Reuse returned names; Inspect is read-only.
1387
+ - A not-found path or unknown Service is a discovery error: check the file list or Service directory before retrying. Preserve actual failures; do not hide them or bypass permission denials.
1212
1388
 
1213
1389
  ## Task execution
1214
1390
 
@@ -1230,7 +1406,7 @@ const DEFAULT_CODEX_SYSTEM_PROMPT = String.raw`## General
1230
1406
  /** Default deployment Persona template used by the Codex preset. */
1231
1407
  const DEFAULT_CODEX_PERSONA = String.raw`You are Codex, a coding agent based on the {{model}} model. Your working directory is {{cwd}}.`;
1232
1408
  /** Default DSH Core source-checkout guidance template. */
1233
- const DEFAULT_DSH_CORE_SOURCE_PROMPT = String.raw`The DeepSeek Harness implementation checkout is at {{sourceRoot}}. The checkout location and current working directory are separate values and may differ; never infer the working directory from this path. Use pwd to determine the current working directory. Use this checkout only to inspect or extend DSH itself.`;
1409
+ const DEFAULT_DSH_CORE_SOURCE_PROMPT = String.raw`The DeepSeek Harness implementation checkout is at {{sourceRoot}}. The checkout location and current working directory are separate values and may differ; never infer the working directory from this path. Use pwd to determine the current working directory. Use this checkout only to inspect or extend DSH itself. If the supplied path is inside app.asar, treat it as a packaged runtime rather than a source checkout. Discover the installed packageDir via Inspect and read its README and package.json exports; do not assume src or individual lib/types filenames exist. Use Host file-read tools for app.asar; native shell search and glob cannot traverse it.`;
1234
1410
  /** Default DSH Web runtime guidance template. */
1235
1411
  const DEFAULT_DSH_CORE_WEB_PROMPT = [
1236
1412
  "You are interacting with the user through the DeepSeek Harness Web GUI at {{webUrl}}.",
@@ -1279,9 +1455,9 @@ const CODEX_SETTINGS_SCHEMA = z.object({
1279
1455
  webSurfacePrompt: z.string().default(DEFAULT_DSH_CORE_WEB_PROMPT),
1280
1456
  systemPrompt: z.string().default(DEFAULT_CODEX_SYSTEM_PROMPT),
1281
1457
  promptEnabled: z.boolean().default(true),
1282
- terminalToolsEnabled: z.boolean().default(true),
1283
- patchToolEnabled: z.boolean().default(true),
1284
- planToolEnabled: z.boolean().default(true),
1458
+ terminalToolsEnabled: z.boolean().default(true).hidden(),
1459
+ patchToolEnabled: z.boolean().default(true).hidden(),
1460
+ planToolEnabled: z.boolean().default(true).hidden(),
1285
1461
  hostedWebSearchEnabled: z.boolean().default(true),
1286
1462
  remoteCompactionEnabled: z.boolean().default(true),
1287
1463
  activityIndicatorEnabled: z.boolean().default(true)
@@ -1315,8 +1491,8 @@ function isGptModel$1(model) {
1315
1491
  /** Read the live Codex capacity without requiring a custom LLM service API. */
1316
1492
  function configuredContextWindow(ctx) {
1317
1493
  const settings = ctx.get("settings");
1318
- if (settings?.get === void 0) return { available: false };
1319
- const value = settings?.get?.(CODEX_SETTINGS_NAMESPACE$1);
1494
+ if (settings?.get === void 0 && settings?.describe === void 0) return { available: false };
1495
+ const value = readHostSettings(ctx, CODEX_SETTINGS_NAMESPACE$1);
1320
1496
  return {
1321
1497
  available: true,
1322
1498
  ...value?.contextWindow !== void 0 && Number.isSafeInteger(value.contextWindow) && value.contextWindow > 0 ? { value: value.contextWindow } : {}
@@ -1377,11 +1553,327 @@ function withDurableContextCapacity(llm, ctx, activeSession) {
1377
1553
  compactIfNeeded(agent, trigger, signal) {
1378
1554
  return this.activeSession.run(agent.session, () => super.compactIfNeeded(agent, trigger, signal));
1379
1555
  }
1556
+ compactRegion(...args) {
1557
+ return this.activeSession.run(args[2].session, () => super.compactRegion(...args));
1558
+ }
1380
1559
  compactNow(agent, signal, sourceCommandId) {
1381
1560
  return this.activeSession.run(agent.session, () => super.compactNow(agent, signal, sourceCommandId));
1382
1561
  }
1383
1562
  });
1384
1563
  //#endregion
1564
+ //#region lib/types/tool-capabilities.js
1565
+ const OWNED_TOOL = Symbol.for("@shuind/dsh-codex-harness:tool-capability:v1");
1566
+ const CAPABILITIES = [
1567
+ "terminalToolsEnabled",
1568
+ "planToolEnabled",
1569
+ "patchToolEnabled"
1570
+ ];
1571
+ /** Only our old presentation hooks consume this; registrations remain provider-owned. */
1572
+ function hasPresetPromptOverride(ctx, context, name) {
1573
+ if (context.codexPresetPromptProbe === true) return [
1574
+ "deployment:persona-prefix",
1575
+ "deployment:persona-suffix",
1576
+ "codex:base"
1577
+ ].includes(name);
1578
+ return context.scope !== void 0 && ctx.get("codexToolPolicy")?.hasPromptOverride?.(context.scope, name) === true;
1579
+ }
1580
+ function markCodexTool(definition, metadata) {
1581
+ Object.defineProperty(definition, OWNED_TOOL, { value: Object.freeze({ ...metadata }) });
1582
+ return definition;
1583
+ }
1584
+ function codexToolMetadata(definition) {
1585
+ const value = definition[OWNED_TOOL];
1586
+ if (value === null || typeof value !== "object") return void 0;
1587
+ const data = value;
1588
+ if (!CAPABILITIES.includes(data.capability) || typeof data.presetEnabled !== "boolean" || data.presetOverridesLegacy !== void 0 && typeof data.presetOverridesLegacy !== "boolean") return void 0;
1589
+ return {
1590
+ capability: data.capability,
1591
+ presetEnabled: data.presetEnabled,
1592
+ ...data.presetOverridesLegacy === void 0 ? {} : { presetOverridesLegacy: data.presetOverridesLegacy }
1593
+ };
1594
+ }
1595
+ /** Read once for a new Agent or catalog. No caller keeps the live preference object. */
1596
+ function readLegacyCapabilities(ctx) {
1597
+ const current = readHostSettings(ctx, CODEX_SETTINGS_NAMESPACE);
1598
+ return Object.freeze(Object.fromEntries(CAPABILITIES.map((key) => [key, current?.[key] ?? CODEX_SETTINGS_ENTRY[key]])));
1599
+ }
1600
+ function codexToolEnabled(ctx, agent, name, metadata, fallback, authority) {
1601
+ if (!metadata.presetEnabled) return false;
1602
+ if (authority !== void 0) return authority;
1603
+ return (agent === void 0 ? void 0 : ctx.get("codexToolPolicy")?.enabled(agent, name, metadata)) ?? fallback()[metadata.capability] !== false;
1604
+ }
1605
+ //#endregion
1606
+ //#region lib/types/preset-tool-catalog.js
1607
+ async function readPresetToolCatalog(ctx, preset) {
1608
+ if (typeof preset !== "string" || !preset.trim() || preset.length > 256) throw new Error("invalid-preset-id");
1609
+ const registry = ctx.get("agentPresets");
1610
+ const tools = ctx.get("tools");
1611
+ if (registry === void 0 || typeof registry.acquireScope !== "function" || tools === void 0) throw new Error("preset-tool-catalog-unavailable");
1612
+ const lease = await registry.acquireScope(preset);
1613
+ let view;
1614
+ try {
1615
+ const key = {};
1616
+ view = createScope(ctx, key, { parent: lease.key });
1617
+ const definitions = tools.definitions(key);
1618
+ const names = new Set(definitions.map((tool) => tool.name));
1619
+ return {
1620
+ preset,
1621
+ registeredOnly: true,
1622
+ legacyCapabilities: readLegacyCapabilities(ctx),
1623
+ tools: definitions.map((definition) => {
1624
+ const conditional = tools.executable(definition.name, key) !== definition;
1625
+ const replacements = [];
1626
+ const action = definition.name === "bash" || definition.name === "pwsh" ? "codex-exec" : definition.name === "todo_write" ? "codex-plan" : void 0;
1627
+ if (action !== void 0) {
1628
+ const targets = action === "codex-exec" ? ["exec_command", "write_stdin"] : ["update_plan"];
1629
+ const reason = conditional ? "conditional" : targets.some((target) => names.has(target)) ? "target-exists" : void 0;
1630
+ replacements.push({
1631
+ action,
1632
+ tools: targets,
1633
+ available: reason === void 0,
1634
+ ...reason === void 0 ? {} : { reason }
1635
+ });
1636
+ }
1637
+ const codexTool = codexToolMetadata(definition);
1638
+ return {
1639
+ name: definition.name,
1640
+ description: definition.description.slice(0, 300),
1641
+ conditional,
1642
+ replacements,
1643
+ ...codexTool === void 0 ? {} : { codexTool }
1644
+ };
1645
+ }).sort((a, b) => a.name.localeCompare(b.name, "en"))
1646
+ };
1647
+ } finally {
1648
+ try {
1649
+ await view?.dispose();
1650
+ } finally {
1651
+ await lease[Symbol.asyncDispose]();
1652
+ }
1653
+ }
1654
+ }
1655
+ //#endregion
1656
+ //#region lib/types/preset-prompt-catalog.js
1657
+ /** Public, read-only preset prompt discovery. No private registry, Agent, or JS/YAML evaluation. */
1658
+ function literal(map, key) {
1659
+ const node = map.get(key, true);
1660
+ return isScalar(node) && !node.tag ? node.value : void 0;
1661
+ }
1662
+ /** Native Persona's public source owns these exact names/placements/complete semantics. */
1663
+ function candidates(content, placement) {
1664
+ const doc = parseDocument(content, {
1665
+ strict: true,
1666
+ uniqueKeys: true
1667
+ });
1668
+ if (doc.errors.length || !isSeq(doc.contents)) throw new Error("invalid-preset-prompt-declaration");
1669
+ const found = [];
1670
+ const readonly = [];
1671
+ function visit(rows, parent = "", conditionalParent = false, isolatedParent = false) {
1672
+ if (!isSeq(rows)) return;
1673
+ for (const [index, row] of rows.items.entries()) {
1674
+ if (!isMap(row) || literal(row, "disabled") === true) continue;
1675
+ const module = literal(row, "name");
1676
+ const path = `${parent}/${String(literal(row, "id") ?? index)}`;
1677
+ const conditionalRow = conditionalParent || row.has("disabled") && literal(row, "disabled") === void 0;
1678
+ const isolation = row.get("isolate", true);
1679
+ const isolated = isolatedParent || row.has("isolate") && (!isMap(isolation) || isolation.has("systemPrompt"));
1680
+ let config = row.get("config", true);
1681
+ if (isSeq(config)) {
1682
+ visit(config, path, conditionalRow, isolated);
1683
+ continue;
1684
+ }
1685
+ if (config === void 0 && module === "@shuind/dsh-codex-harness") config = new YAMLMap();
1686
+ if (typeof module !== "string" || !isMap(config)) continue;
1687
+ if (module === "@deepseek-ai/dsh-persona") {
1688
+ const completeNode = config.get("complete", true);
1689
+ const complete = literal(config, "complete");
1690
+ const uncertain = conditionalRow || completeNode !== void 0 && typeof complete !== "boolean";
1691
+ for (const [key, name, order, label] of [[
1692
+ "prefix",
1693
+ PERSONA_PREFIX_SECTION,
1694
+ placement("DEPLOYMENT_PERSONA_PREFIX"),
1695
+ "Persona"
1696
+ ], [
1697
+ "suffix",
1698
+ PERSONA_SUFFIX_SECTION,
1699
+ placement("DEPLOYMENT_PERSONA_SUFFIX"),
1700
+ "Persona · suffix"
1701
+ ]]) {
1702
+ const text = literal(config, key);
1703
+ const missingSuffix = key === "suffix" && !config.has(key);
1704
+ const reason = isolated ? "isolated-prompt-registry" : uncertain ? "dynamic-declaration" : void 0;
1705
+ found.push({
1706
+ name,
1707
+ label,
1708
+ module,
1709
+ order,
1710
+ complete: key === "prefix" && complete === true,
1711
+ interpolate: true,
1712
+ ...typeof text === "string" ? { literal: text } : missingSuffix ? { literal: "" } : {},
1713
+ ...reason === void 0 ? {} : { reason }
1714
+ });
1715
+ }
1716
+ } else if (module === "@shuind/dsh-codex-harness" && literal(config, "codexCore") !== false) found.push({
1717
+ name: "codex:base",
1718
+ label: "Codex 操作提示词",
1719
+ module,
1720
+ order: 10,
1721
+ complete: false,
1722
+ interpolate: true,
1723
+ ...isolated ? { reason: "isolated-prompt-registry" } : conditionalRow || config.has("codexCore") && literal(config, "codexCore") === void 0 ? { reason: "dynamic-declaration" } : {}
1724
+ });
1725
+ else for (const key of [
1726
+ "prefix",
1727
+ "suffix",
1728
+ "text",
1729
+ "section",
1730
+ "prompt",
1731
+ "systemPrompt",
1732
+ "instructions"
1733
+ ]) {
1734
+ if (!config.has(key) || module === "@deepseek-ai/dsh-plan-mode") continue;
1735
+ const text = literal(config, key);
1736
+ readonly.push({
1737
+ name: `declaration:${path}:${key}`,
1738
+ label: `${module} · ${key}`,
1739
+ text: typeof text === "string" ? text : "",
1740
+ editable: false,
1741
+ reason: typeof text === "string" ? "unknown-section-contract" : "dynamic-declaration"
1742
+ });
1743
+ }
1744
+ }
1745
+ }
1746
+ visit(doc.contents);
1747
+ return {
1748
+ found,
1749
+ readonly
1750
+ };
1751
+ }
1752
+ function moduleSignature(rows) {
1753
+ return JSON.stringify(rows.map((row) => [
1754
+ row.moduleName,
1755
+ row.baseUrl ?? "",
1756
+ row.useHostBase
1757
+ ]));
1758
+ }
1759
+ /** The opaque scope identity is retained only for runtime revision validation, not sent over RPC. */
1760
+ async function probePresetPrompts(ctx, preset, expectedScope) {
1761
+ if (typeof preset !== "string" || !preset.trim() || preset.length > 256) throw new Error("invalid-preset-id");
1762
+ const registry = ctx.get("agentPresets");
1763
+ const prompt = ctx.get("systemPrompt");
1764
+ if (registry === void 0 || prompt === void 0 || typeof registry.acquireScope !== "function" || typeof registry.readDocument !== "function" || typeof registry.inspectCompositions !== "function") throw new Error("preset-prompt-catalog-unavailable");
1765
+ const document = await registry.readDocument(preset);
1766
+ const lease = await registry.acquireScope(preset);
1767
+ let view;
1768
+ try {
1769
+ if (expectedScope !== void 0 && lease.key !== expectedScope) throw new Error("preset-prompt-revision-mismatch");
1770
+ const key = {};
1771
+ view = createScope(ctx, key, { parent: lease.key });
1772
+ const inspection = registry.inspectCompositions(view.ctx);
1773
+ if (inspection.length !== 1 || inspection[0]?.id !== preset) throw new Error("preset-prompt-revision-unavailable");
1774
+ const modules = moduleSignature(inspection[0].modules);
1775
+ const active = new Set(inspection[0].modules.map((row) => row.moduleName));
1776
+ const declared = candidates(document.content, (name) => prompt.getSectionOrder(name));
1777
+ const definitions = /* @__PURE__ */ new Map();
1778
+ const sections = [];
1779
+ let baseline;
1780
+ try {
1781
+ baseline = await prompt.assemble({ scope: key });
1782
+ } catch {
1783
+ return {
1784
+ scope: lease.key,
1785
+ modules,
1786
+ definitions,
1787
+ catalog: {
1788
+ preset,
1789
+ sections: [...declared.found.map((row) => ({
1790
+ name: row.name,
1791
+ label: row.label,
1792
+ text: row.literal ?? "",
1793
+ editable: false,
1794
+ reason: "assembly-unavailable"
1795
+ })), ...declared.readonly].slice(0, 200)
1796
+ }
1797
+ };
1798
+ }
1799
+ const seen = /* @__PURE__ */ new Set();
1800
+ for (const row of declared.found) {
1801
+ if (seen.has(row.name)) continue;
1802
+ seen.add(row.name);
1803
+ const actual = baseline.sections.find((section) => section.name === row.name);
1804
+ let reason = row.reason ?? (!active.has(row.module) ? "inactive-contribution" : void 0) ?? (declared.found.filter((candidate) => candidate.name === row.name).length !== 1 ? "ambiguous-contribution" : void 0) ?? (actual === void 0 ? "not-effective-or-complete-suppressed" : void 0);
1805
+ if (reason === void 0 && row.complete && (baseline.sections.length !== 1 || baseline.sections[0]?.name !== row.name)) reason = "complete-contract-mismatch";
1806
+ if (reason === void 0) {
1807
+ const marker = `preset-prompt-probe:${randomUUID()}`;
1808
+ const undo = view.ctx.get("systemPrompt").section({
1809
+ name: row.name,
1810
+ order: row.order,
1811
+ complete: row.complete,
1812
+ interpolate: row.interpolate,
1813
+ text: marker
1814
+ });
1815
+ try {
1816
+ const probed = await prompt.assemble({
1817
+ scope: key,
1818
+ codexPresetPromptProbe: true
1819
+ });
1820
+ if (probed.sections.find((section) => section.name === row.name)?.text !== marker || JSON.stringify(probed.sections.map((section) => section.name)) !== JSON.stringify(baseline.sections.map((section) => section.name)) || row.complete && (probed.sections.length !== 1 || probed.sections[0]?.name !== row.name)) reason = "not-directly-overridable";
1821
+ } catch {
1822
+ reason = "not-directly-overridable";
1823
+ } finally {
1824
+ undo();
1825
+ }
1826
+ }
1827
+ const text = actual?.text ?? row.literal ?? "";
1828
+ if (text.length > 1e6) reason = "prompt-too-large";
1829
+ sections.push({
1830
+ name: row.name,
1831
+ label: row.label,
1832
+ text: text.slice(0, 1e6),
1833
+ editable: reason === void 0,
1834
+ order: row.order,
1835
+ complete: row.complete,
1836
+ interpolate: row.interpolate,
1837
+ ...reason === void 0 ? {} : { reason }
1838
+ });
1839
+ if (reason === void 0) definitions.set(row.name, {
1840
+ name: row.name,
1841
+ order: row.order,
1842
+ complete: row.complete,
1843
+ interpolate: row.interpolate,
1844
+ text
1845
+ });
1846
+ }
1847
+ for (const row of baseline.sections) if (!seen.has(row.name)) sections.push({
1848
+ name: row.name,
1849
+ label: row.name,
1850
+ text: row.text.slice(0, 1e6),
1851
+ editable: false,
1852
+ reason: "unknown-or-host-owned-section"
1853
+ });
1854
+ sections.push(...declared.readonly);
1855
+ if ((await registry.readDocument(preset)).content !== document.content) throw new Error("preset-prompt-revision-mismatch");
1856
+ return {
1857
+ scope: lease.key,
1858
+ modules,
1859
+ definitions,
1860
+ catalog: {
1861
+ preset,
1862
+ sections: sections.slice(0, 200)
1863
+ }
1864
+ };
1865
+ } finally {
1866
+ try {
1867
+ await view?.dispose();
1868
+ } finally {
1869
+ await lease[Symbol.asyncDispose]();
1870
+ }
1871
+ }
1872
+ }
1873
+ async function readPresetPromptCatalog(ctx, preset) {
1874
+ return (await probePresetPrompts(ctx, preset)).catalog;
1875
+ }
1876
+ //#endregion
1385
1877
  //#region lib/types/preset-editor.js
1386
1878
  let atomicWriteModule;
1387
1879
  function loadAtomicWrite() {
@@ -1440,9 +1932,9 @@ function promptFields(doc) {
1440
1932
  const fields = [];
1441
1933
  function visit(sequence, parents = []) {
1442
1934
  if (!isSeq(sequence)) return;
1443
- for (const row of sequence.items) {
1935
+ for (const [index, row] of sequence.items.entries()) {
1444
1936
  if (!isMap(row) || row.get("disabled") === true) continue;
1445
- const path = [...parents, String(row.get("id"))];
1937
+ const path = [...parents, String(row.get("id") ?? `row:${index}`)];
1446
1938
  const config = row.get("config", true);
1447
1939
  if (isSeq(config)) {
1448
1940
  visit(config, path);
@@ -1747,13 +2239,14 @@ async function assertWithinRoot(path, roots) {
1747
2239
  var CodexPresetEditor = class extends TypertRemoteService {
1748
2240
  static inject = ["agentPresets", "settings"];
1749
2241
  agentPresets;
2242
+ toolContext;
1750
2243
  sharedSettings;
1751
2244
  indexed;
1752
2245
  constructor(ctx, _config) {
1753
2246
  super(ctx, "codexPresetEditor");
2247
+ this.toolContext = ctx;
1754
2248
  this.agentPresets = ctx.get("agentPresets");
1755
- const settings = ctx.get("settings");
1756
- this.sharedSettings = () => settings?.get("codex") ?? {};
2249
+ this.sharedSettings = () => readHostSettings(ctx, "codex") ?? {};
1757
2250
  }
1758
2251
  async catalog() {
1759
2252
  if (this.agentPresets.list) {
@@ -1764,13 +2257,14 @@ var CodexPresetEditor = class extends TypertRemoteService {
1764
2257
  id: row.id,
1765
2258
  name: row.name || row.id,
1766
2259
  description: row.description ?? "",
1767
- editable: row.trust === "user",
2260
+ editable: !!row.path && row.trust === "user",
1768
2261
  isDefault: row.id === this.agentPresets.defaultId
1769
2262
  })),
1770
- authorable: this.agentPresets.authorable ?? false,
2263
+ authorable: !!this.agentPresets.copy && !!this.agentPresets.remove && (this.agentPresets.authorable ?? false),
1771
2264
  excludedCount: rows.filter((row) => row.broken !== void 0).length
1772
2265
  };
1773
2266
  }
2267
+ if (!this.agentPresets.remoteExportList) throw new Error("preset-catalog-unavailable");
1774
2268
  const roster = await this.agentPresets.remoteExportList();
1775
2269
  const presets = roster.presets.filter((row) => row.broken === void 0).map((row) => ({
1776
2270
  id: row.id,
@@ -1781,23 +2275,33 @@ var CodexPresetEditor = class extends TypertRemoteService {
1781
2275
  }));
1782
2276
  return {
1783
2277
  presets,
1784
- authorable: roster.authorable,
2278
+ authorable: !!this.agentPresets.copy && !!this.agentPresets.remove && (roster.authorable ?? false),
1785
2279
  excludedCount: roster.presets.length - presets.length
1786
2280
  };
1787
2281
  }
2282
+ async tools(id) {
2283
+ return readPresetToolCatalog(this.toolContext, id);
2284
+ }
2285
+ async prompts(id) {
2286
+ return readPresetPromptCatalog(this.toolContext, id);
2287
+ }
1788
2288
  async read(id) {
1789
2289
  const preset = this.indexed?.get(id) ?? await this.preset(id);
1790
2290
  if (preset.broken !== void 0) throw new Error("invalid-preset");
1791
- const [composition, metadata] = await Promise.all([readFile(preset.path, "utf8"), optionalFile(resolve(dirname(preset.path), "preset.yml"))]);
2291
+ const inline = preset.path === void 0 ? await this.agentPresets.readDocument(id) : void 0;
2292
+ const [composition, metadata] = preset.path === void 0 ? [inline.content, void 0] : await Promise.all([readFile(preset.path, "utf8"), optionalFile(resolve(dirname(preset.path), "preset.yml"))]);
1792
2293
  const meta = metadata ? yaml(metadata) : void 0;
1793
- validateComposition(composition);
2294
+ if (inline) {
2295
+ const doc = yaml(composition);
2296
+ if (!isSeq(doc.contents) || doc.contents.items.some((row) => !isMap(row) || typeof row.get("name") !== "string")) throw new Error("invalid-preset-yaml");
2297
+ } else validateComposition(composition);
1794
2298
  const codex = supportsCodex(composition);
1795
2299
  const prompt = codex ? explicitPrompt(composition) : void 0;
1796
2300
  const shared = this.sharedSettings?.() ?? {};
1797
2301
  const promptSections = readPromptSections(composition, shared);
1798
2302
  for (const field of promptFields(yaml(composition))) {
1799
2303
  const reference = promptFile(field.node);
1800
- if (!reference) continue;
2304
+ if (!reference || preset.path === void 0) continue;
1801
2305
  const section = promptSections.find((section) => section.id === field.id);
1802
2306
  try {
1803
2307
  const root = await realpath(dirname(preset.path));
@@ -1809,14 +2313,15 @@ var CodexPresetEditor = class extends TypertRemoteService {
1809
2313
  section.editable = true;
1810
2314
  } catch {}
1811
2315
  }
2316
+ if (inline) for (const section of promptSections) section.editable = false;
1812
2317
  return {
1813
2318
  id,
1814
- name: String(meta?.get("name") ?? id),
1815
- description: String(meta?.get("description") ?? ""),
2319
+ name: String(meta?.get("name") ?? inline?.name ?? preset.name ?? id),
2320
+ description: String(meta?.get("description") ?? inline?.description ?? preset.description ?? ""),
1816
2321
  systemPrompt: prompt ?? shared.systemPrompt ?? DEFAULT_CODEX_SYSTEM_PROMPT,
1817
2322
  inheritPrompt: prompt === void 0,
1818
2323
  revision: revision(composition, metadata),
1819
- editable: preset.trust === "user",
2324
+ editable: !!preset.path && preset.trust === "user",
1820
2325
  codex,
1821
2326
  codexOptions: readCodexPresetOptions(composition),
1822
2327
  composition,
@@ -1824,6 +2329,7 @@ var CodexPresetEditor = class extends TypertRemoteService {
1824
2329
  };
1825
2330
  }
1826
2331
  async create(rawInput) {
2332
+ if (!this.agentPresets.copy || !this.agentPresets.remove) throw new Error("preset-registry-read-only: this host does not support preset copies");
1827
2333
  const input = validate(rawInput);
1828
2334
  await this.preset(input.sourceId);
1829
2335
  const id = `codex-${randomUUID().slice(0, 12)}`;
@@ -1850,6 +2356,7 @@ var CodexPresetEditor = class extends TypertRemoteService {
1850
2356
  async update(rawInput) {
1851
2357
  const input = validate(rawInput);
1852
2358
  const preset = await this.preset(input.id);
2359
+ if (preset.path === void 0) throw new Error("preset-registry-read-only: this host exposes presets for viewing only");
1853
2360
  if (preset.trust !== "user") throw new Error("built-in presets cannot be edited here");
1854
2361
  const composition = resolve(preset.path);
1855
2362
  if (composition.split(/[\\/]/).at(-1) !== "agent.cordis.yml") throw new Error("invalid-preset-path");
@@ -1936,7 +2443,9 @@ for (const method of [
1936
2443
  "read",
1937
2444
  "update",
1938
2445
  "catalog",
1939
- "create"
2446
+ "create",
2447
+ "tools",
2448
+ "prompts"
1940
2449
  ]) markRemoteMethod(method);
1941
2450
  //#endregion
1942
2451
  //#region lib/types/prompt-sections.js
@@ -1946,19 +2455,20 @@ const Config$1 = z.object({
1946
2455
  webSurfacePrompt: z.string()
1947
2456
  });
1948
2457
  /** Override only existing sections; dynamic runtime context and tool guidance remain host-owned. */
1949
- function applyPromptSections(assembly, config) {
2458
+ function applyPromptSections(assembly, config, protectedNames) {
1950
2459
  const variables = { ...assembly.variables };
1951
2460
  variables.sourceRoot ??= assembly.sections.find((s) => s.name === "harness:source")?.text.match(/^The DeepSeek Harness implementation checkout is at (.+?)\. The checkout location/u)?.[1];
1952
2461
  variables.webUrl ??= assembly.sections.find((s) => s.name === "app:web-surface")?.text.match(/^You are interacting with the user through the DeepSeek Harness Web GUI at (.+?)\. When/u)?.[1];
1953
2462
  const values = {
1954
2463
  "deployment:persona": config.persona,
2464
+ "deployment:persona-prefix": config.persona,
1955
2465
  "harness:source": config.harnessSourcePrompt,
1956
2466
  "app:web-surface": config.webSurfacePrompt
1957
2467
  };
1958
2468
  return {
1959
2469
  ...assembly,
1960
2470
  sections: assembly.sections.map((section) => {
1961
- const text = values[section.name];
2471
+ const text = protectedNames?.has(section.name) ? void 0 : values[section.name];
1962
2472
  return text === void 0 ? section : {
1963
2473
  ...section,
1964
2474
  text: text.replace(/\{\{([\w.-]+)\}\}/g, (whole, key) => variables[key] ?? whole)
@@ -2065,7 +2575,7 @@ function enrichCodexOverride(id, model) {
2065
2575
  async function enrichConfiguredGptModels(ctx) {
2066
2576
  const settings = ctx.get("settings");
2067
2577
  if (settings === void 0) return;
2068
- const current = settings.get(LLM_PI_AI_SETTINGS);
2578
+ const current = readHostSettings(ctx, LLM_PI_AI_SETTINGS);
2069
2579
  if (current?.providers === void 0) return;
2070
2580
  const providers = {};
2071
2581
  let changed = false;
@@ -2147,7 +2657,7 @@ function installCodexSettings(ctx, systemPrompt, persona, harnessSourcePrompt, w
2147
2657
  if (!attachSettings(ctx.get("settings"))) ctx.inject(["settings"], (settingsCtx) => {
2148
2658
  attachSettings(settingsCtx.settings);
2149
2659
  });
2150
- return { current: () => withDefaults(source()) };
2660
+ return { current: () => withDefaults(readHostSettings(ctx, "codex") ?? source()) };
2151
2661
  }
2152
2662
  /** Read the event snapshot across the pre- and post-0.1.2 DSH session APIs. */
2153
2663
  function sessionEvents(session) {
@@ -2178,7 +2688,8 @@ function syncCodexContextWindow(session, contextWindow) {
2178
2688
  session.append("request/context", {
2179
2689
  provider: config.provider,
2180
2690
  model: config.model,
2181
- contextWindow
2691
+ contextWindow,
2692
+ ...current?.provider === config.provider && current.model === config.model ? { ...current.systemPromptUpdate === void 0 ? {} : { systemPromptUpdate: current.systemPromptUpdate } } : {}
2182
2693
  });
2183
2694
  }
2184
2695
  /** Keep the official context meter synchronized with a live Codex override. */
@@ -2205,9 +2716,7 @@ function installCodexContextProjection(ctx, current) {
2205
2716
  ctx.on("session/event", (session, event) => {
2206
2717
  if (event.type === "request/header" || event.type === "request/context") syncAfterPublication(session);
2207
2718
  });
2208
- ctx.on("session/created", (session) => {
2209
- sync(session);
2210
- });
2719
+ ctx.on("session/created", syncAfterPublication);
2211
2720
  ctx.on("settings/updated", (ns, next) => {
2212
2721
  if (ns === "codex") syncAll(next.contextWindow);
2213
2722
  });
@@ -2229,14 +2738,14 @@ function applyCodexRequestSettings(request, settings) {
2229
2738
  /** Put the agent persona first and omit the generic Harness identity opener. */
2230
2739
  function normalizeCodexPromptAssembly(assembly) {
2231
2740
  const sections = assembly.sections.filter((section) => section.name !== "harness:identity");
2232
- const persona = sections.find((section) => section.name === "deployment:persona");
2741
+ const persona = sections.find((section) => section.name === "deployment:persona-prefix") ?? sections.find((section) => section.name === "deployment:persona");
2233
2742
  if (persona === void 0) return {
2234
2743
  ...assembly,
2235
2744
  sections
2236
2745
  };
2237
2746
  return {
2238
2747
  ...assembly,
2239
- sections: [persona, ...sections.filter((section) => section.name !== "deployment:persona")]
2748
+ sections: [persona, ...sections.filter((section) => section !== persona)]
2240
2749
  };
2241
2750
  }
2242
2751
  function sectionText(assembly, name) {
@@ -2261,11 +2770,13 @@ function interpolateCodexPrompt(text, variables) {
2261
2770
  function applyCodexPromptOverrides(assembly, settings) {
2262
2771
  const overrides = {
2263
2772
  "deployment:persona": settings.persona,
2773
+ "deployment:persona-prefix": settings.persona,
2264
2774
  "harness:source": settings.harnessSourcePrompt,
2265
2775
  "app:web-surface": settings.webSurfacePrompt
2266
2776
  };
2267
2777
  const defaults = {
2268
2778
  "deployment:persona": DEFAULT_CODEX_PERSONA,
2779
+ "deployment:persona-prefix": DEFAULT_CODEX_PERSONA,
2269
2780
  "harness:source": DEFAULT_DSH_CORE_SOURCE_PROMPT,
2270
2781
  "app:web-surface": DEFAULT_DSH_CORE_WEB_PROMPT
2271
2782
  };
@@ -2296,10 +2807,17 @@ function applyCodexCapabilitySettings(assembly, settings) {
2296
2807
  if (settings[setting]) continue;
2297
2808
  for (const name of names) disabled.add(name);
2298
2809
  }
2299
- const withOverrides = applyCodexPromptOverrides(disabled.size === 0 ? assembly : {
2810
+ const tools = assembly.tools;
2811
+ return applyCodexPresentationSettings(disabled.size === 0 || tools === void 0 ? assembly : {
2300
2812
  ...assembly,
2301
- tools: assembly.tools.filter((tool) => !disabled.has(tool.name))
2813
+ tools: tools.filter((tool) => !disabled.has(tool.name))
2302
2814
  }, settings);
2815
+ }
2816
+ /** Current SDK declarations remain registry-owned; preferences affect presentation only. */
2817
+ function applyCodexPresentationSettings(assembly, settings, protectedNames) {
2818
+ const promptSettings = { ...settings };
2819
+ if (protectedNames?.has("deployment:persona-prefix")) delete promptSettings.persona;
2820
+ const withOverrides = applyCodexPromptOverrides(assembly, promptSettings);
2303
2821
  return settings.promptEnabled ? normalizeCodexPromptAssembly(withOverrides) : withOverrides;
2304
2822
  }
2305
2823
  /** Build the complete plugin-owned prompt, preserving an intentional empty value. */
@@ -2314,17 +2832,18 @@ const PLAN_STATUSES = [
2314
2832
  "in_progress",
2315
2833
  "completed"
2316
2834
  ];
2317
- function assertCapabilityEnabled(current, setting, toolName) {
2318
- if (!current()[setting]) throw new Error(`${toolName}: disabled in Codex Harness plugin settings`);
2835
+ function assertCapabilityEnabled(ctx, current, toolName, agent, metadata, authority) {
2836
+ if (!codexToolEnabled(ctx, agent, toolName, metadata, current, authority)) throw new Error(`${toolName}: disabled in Codex Harness plugin settings`);
2319
2837
  }
2320
- function sessionCwd(exec) {
2321
- return exec.agent?.session.header.cwd;
2838
+ function sessionCwd(ctx, exec) {
2839
+ if (exec.agent === void 0) return void 0;
2840
+ return ctx.get("workingDirectory")?.get(exec.agent.session) ?? exec.agent.session.header.cwd;
2322
2841
  }
2323
2842
  function resolvePolicy(ctx, exec) {
2324
2843
  return ctx.get("sandboxPolicy")?.resolve(exec.agent === void 0 ? {} : { session: exec.agent.session });
2325
2844
  }
2326
2845
  async function resolveTarget(ctx, path, exec) {
2327
- const cwd = sessionCwd(exec);
2846
+ const cwd = sessionCwd(ctx, exec);
2328
2847
  return ctx.fs.resolve(path, cwd === void 0 ? { signal: exec.signal } : {
2329
2848
  cwd,
2330
2849
  signal: exec.signal
@@ -2350,9 +2869,11 @@ async function writePatchedFile(ctx, target, content, fallback, exec, policy) {
2350
2869
  return outcome.operation === "create" ? "created" : "updated";
2351
2870
  }
2352
2871
  async function deletePatchedFile(ctx, target, version, exec, policy) {
2353
- const remove = ctx.fs.remove;
2872
+ const fs = ctx.fs;
2873
+ const remove = fs.deleteFile ?? fs.remove;
2354
2874
  if (typeof remove !== "function") throw new Error("apply_patch: the configured dsh filesystem does not support file deletion");
2355
- await remove.call(ctx.fs, target, { version }, exec.signal, policy);
2875
+ const expected = await ctx.waterfall("fs/delete-intent", target, exec, () => ({ version }));
2876
+ await remove.call(ctx.fs, target, expected, exec.signal, policy);
2356
2877
  ctx.emit("fs/observed", target, { kind: "absent" }, exec);
2357
2878
  }
2358
2879
  async function applyOnePatch(ctx, file, exec, policy) {
@@ -2438,10 +2959,34 @@ function planTodos(args) {
2438
2959
  if (active > 1) throw new Error("update_plan: at most one step may be in_progress");
2439
2960
  return todos;
2440
2961
  }
2962
+ /** Release every registration once, even when one release fails. */
2963
+ function composeToolDisposers(disposers) {
2964
+ return () => {
2965
+ const errors = [];
2966
+ for (const dispose of disposers.splice(0).reverse()) try {
2967
+ dispose();
2968
+ } catch (error) {
2969
+ errors.push(error);
2970
+ }
2971
+ if (errors.length > 0) throw new AggregateError(errors, "Could not unregister Codex tools");
2972
+ };
2973
+ }
2441
2974
  function registerExecTools(ctx, config) {
2442
- ctx.tools.register(defineTool({
2975
+ const tools = ctx.get("tools");
2976
+ if (tools === void 0) throw new Error("Codex execution tools require ctx.tools");
2977
+ const shell = ctx.get("shell");
2978
+ if (shell === void 0) throw new Error("Codex execution tools require ctx.shell");
2979
+ const confines = shell.sandboxMode !== void 0;
2980
+ if (confines && ctx.get("sandboxPolicy") === void 0) throw new Error("Codex execution tools: a sandboxing shell requires ctx.sandboxPolicy");
2981
+ const legacyShellOptions = supportsLegacyShellOptions(ctx);
2982
+ const metadata = {
2983
+ capability: "terminalToolsEnabled",
2984
+ presetEnabled: config.presetEnabled !== false,
2985
+ ...config.presetOverridesLegacy ? { presetOverridesLegacy: true } : {}
2986
+ };
2987
+ const unregisterExec = tools.register(markCodexTool(defineTool({
2443
2988
  name: "exec_command",
2444
- description: EXEC_COMMAND_DESCRIPTION,
2989
+ description: legacyShellOptions ? EXEC_COMMAND_DESCRIPTION : EXEC_COMMAND_DESCRIPTION.replace("Runs a shell command.", "Runs a command in the host-configured shell."),
2445
2990
  parameters: {
2446
2991
  cmd: {
2447
2992
  type: "string",
@@ -2454,7 +2999,7 @@ function registerExecTools(ctx, config) {
2454
2999
  },
2455
3000
  tty: {
2456
3001
  type: "boolean",
2457
- description: "True allocates a PTY for the command; false or omitted uses plain pipes."
3002
+ description: confines ? "This host cannot carry sandbox policy into a PTY; omit tty or use false." : "True allocates a PTY for the command; false or omitted uses plain pipes."
2458
3003
  },
2459
3004
  run_in_background: {
2460
3005
  type: "boolean",
@@ -2468,14 +3013,27 @@ function registerExecTools(ctx, config) {
2468
3013
  type: "number",
2469
3014
  description: "Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy."
2470
3015
  },
2471
- shell: {
2472
- type: "string",
2473
- description: "Shell binary to launch. Defaults to the user's default shell."
2474
- },
2475
- login: {
2476
- type: "boolean",
2477
- description: "True runs the shell with -l/-i semantics; false disables them. Defaults to true."
2478
- }
3016
+ ...confines ? {
3017
+ sandbox_permissions: {
3018
+ type: "string",
3019
+ enum: [...ESCALATION_TARGETS],
3020
+ description: sandboxPermissionsDescription("command")
3021
+ },
3022
+ justification: {
3023
+ type: "string",
3024
+ description: "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access. Use the language of the user’s current request."
3025
+ }
3026
+ } : {},
3027
+ ...legacyShellOptions ? {
3028
+ shell: {
3029
+ type: "string",
3030
+ description: "Shell binary to launch. Defaults to the user's default shell."
3031
+ },
3032
+ login: {
3033
+ type: "boolean",
3034
+ description: "True runs the shell with -l/-i semantics; false disables them. Defaults to true."
3035
+ }
3036
+ } : {}
2479
3037
  },
2480
3038
  output: {
2481
3039
  schema: {
@@ -2503,7 +3061,7 @@ function registerExecTools(ctx, config) {
2503
3061
  }]
2504
3062
  },
2505
3063
  async execute(args, exec) {
2506
- assertCapabilityEnabled(config.currentSettings, "terminalToolsEnabled", "exec_command");
3064
+ assertCapabilityEnabled(ctx, config.currentSettings, "exec_command", exec.agent, metadata, config.authority);
2507
3065
  return runExecCommand(ctx, args, exec, config);
2508
3066
  },
2509
3067
  presentCall: (args) => ({
@@ -2511,61 +3069,71 @@ function registerExecTools(ctx, config) {
2511
3069
  title: args.cmd,
2512
3070
  ...args.workdir === void 0 ? {} : { cwd: args.workdir }
2513
3071
  })
2514
- }));
2515
- ctx.tools.register(defineTool({
2516
- name: "write_stdin",
2517
- description: WRITE_STDIN_DESCRIPTION,
2518
- parameters: {
2519
- session_id: {
2520
- type: "number",
2521
- required: true,
2522
- description: "Identifier of the running unified exec session."
2523
- },
2524
- chars: {
2525
- type: "string",
2526
- description: "Characters to send to a PTY session created with tty=true. Leave empty to poll output without writing; pipe-backed sessions do not accept input."
2527
- },
2528
- yield_time_ms: {
2529
- type: "number",
2530
- description: "Wait before yielding output. Non-empty writes default to 250 ms and cap at 30000 ms; empty polls wait 5000-300000 ms by default."
3072
+ }), metadata), { when: (context) => codexToolEnabled(ctx, context?.agent, "exec_command", metadata, config.currentSettings, config.authority) });
3073
+ try {
3074
+ return composeToolDisposers([unregisterExec, tools.register(markCodexTool(defineTool({
3075
+ name: "write_stdin",
3076
+ description: WRITE_STDIN_DESCRIPTION,
3077
+ parameters: {
3078
+ session_id: {
3079
+ type: "number",
3080
+ required: true,
3081
+ description: "Identifier of the running unified exec session."
3082
+ },
3083
+ chars: {
3084
+ type: "string",
3085
+ description: "Characters to send to a PTY session created with tty=true. Leave empty to poll output without writing; pipe-backed sessions do not accept input."
3086
+ },
3087
+ yield_time_ms: {
3088
+ type: "number",
3089
+ description: "Wait before yielding output. Non-empty writes default to 250 ms and cap at 30000 ms; empty polls wait 5000-300000 ms by default."
3090
+ },
3091
+ max_output_tokens: {
3092
+ type: "number",
3093
+ description: "Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy."
3094
+ }
2531
3095
  },
2532
- max_output_tokens: {
2533
- type: "number",
2534
- description: "Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy."
2535
- }
2536
- },
2537
- output: {
2538
- schema: {
2539
- type: "object",
2540
- additionalProperties: false,
2541
- properties: {
2542
- chunk_id: { type: "string" },
2543
- wall_time_seconds: {
2544
- type: "number",
2545
- required: true
2546
- },
2547
- exit_code: { type: "number" },
2548
- session_id: { type: "number" },
2549
- original_token_count: { type: "number" },
2550
- output: {
2551
- type: "string",
2552
- required: true
3096
+ output: {
3097
+ schema: {
3098
+ type: "object",
3099
+ additionalProperties: false,
3100
+ properties: {
3101
+ chunk_id: { type: "string" },
3102
+ wall_time_seconds: {
3103
+ type: "number",
3104
+ required: true
3105
+ },
3106
+ exit_code: { type: "number" },
3107
+ session_id: { type: "number" },
3108
+ original_token_count: { type: "number" },
3109
+ output: {
3110
+ type: "string",
3111
+ required: true
3112
+ }
2553
3113
  }
2554
- }
3114
+ },
3115
+ render: (_args, value) => [{
3116
+ type: "text",
3117
+ text: renderExecResult(value)
3118
+ }]
2555
3119
  },
2556
- render: (_args, value) => [{
2557
- type: "text",
2558
- text: renderExecResult(value)
2559
- }]
2560
- },
2561
- async execute(args, exec) {
2562
- assertCapabilityEnabled(config.currentSettings, "terminalToolsEnabled", "write_stdin");
2563
- return runWriteStdin(ctx, args, exec, config);
2564
- }
2565
- }));
3120
+ async execute(args, exec) {
3121
+ assertCapabilityEnabled(ctx, config.currentSettings, "write_stdin", exec.agent, metadata, config.authority);
3122
+ return runWriteStdin(ctx, args, exec, config);
3123
+ }
3124
+ }), metadata), { when: (context) => codexToolEnabled(ctx, context?.agent, "write_stdin", metadata, config.currentSettings, config.authority) })]);
3125
+ } catch (error) {
3126
+ unregisterExec();
3127
+ throw error;
3128
+ }
2566
3129
  }
2567
- function registerPatchTool(ctx, currentSettings) {
2568
- ctx.tools.register(defineTool({
3130
+ function registerPatchTool(ctx, currentSettings, presetEnabled = true, presetOverridesLegacy = false) {
3131
+ const metadata = {
3132
+ capability: "patchToolEnabled",
3133
+ presetEnabled,
3134
+ ...presetOverridesLegacy ? { presetOverridesLegacy: true } : {}
3135
+ };
3136
+ ctx.tools.register(markCodexTool(defineTool({
2569
3137
  name: "apply_patch",
2570
3138
  description: APPLY_PATCH_DESCRIPTION,
2571
3139
  parameters: { input: {
@@ -2609,7 +3177,7 @@ function registerPatchTool(ctx, currentSettings) {
2609
3177
  }]
2610
3178
  },
2611
3179
  async execute(args, exec) {
2612
- assertCapabilityEnabled(currentSettings, "patchToolEnabled", "apply_patch");
3180
+ assertCapabilityEnabled(ctx, currentSettings, "apply_patch", exec.agent, metadata);
2613
3181
  const files = parsePatch(args.input);
2614
3182
  const policy = resolvePolicy(ctx, exec);
2615
3183
  const applied = [];
@@ -2624,10 +3192,17 @@ function registerPatchTool(ctx, currentSettings) {
2624
3192
  rawInput: args.input
2625
3193
  };
2626
3194
  }
2627
- }));
2628
- }
2629
- function registerPlanTool(ctx, currentSettings) {
2630
- ctx.tools.register(defineTool({
3195
+ }), metadata), { when: (context) => codexToolEnabled(ctx, context?.agent, "apply_patch", metadata, currentSettings) });
3196
+ }
3197
+ function registerPlanTool(ctx, currentSettings, presetEnabled = true, authority, presetOverridesLegacy = false) {
3198
+ const tools = ctx.get("tools");
3199
+ if (tools === void 0) throw new Error("Codex plan tools require ctx.tools");
3200
+ const metadata = {
3201
+ capability: "planToolEnabled",
3202
+ presetEnabled,
3203
+ ...presetOverridesLegacy ? { presetOverridesLegacy: true } : {}
3204
+ };
3205
+ return tools.register(markCodexTool(defineTool({
2631
3206
  name: "update_plan",
2632
3207
  description: UPDATE_PLAN_DESCRIPTION,
2633
3208
  parameters: {
@@ -2670,13 +3245,40 @@ function registerPlanTool(ctx, currentSettings) {
2670
3245
  }]
2671
3246
  },
2672
3247
  execute(args, exec) {
2673
- assertCapabilityEnabled(currentSettings, "planToolEnabled", "update_plan");
3248
+ assertCapabilityEnabled(ctx, currentSettings, "update_plan", exec.agent, metadata, authority);
2674
3249
  const agent = exec.agent;
2675
3250
  if (agent === void 0) throw new Error("update_plan requires an owning agent session");
2676
3251
  agent.session.append("todo/write", { todos: planTodos(args) });
2677
3252
  return Promise.resolve({});
2678
3253
  }
2679
- }));
3254
+ }), metadata), { when: (context) => codexToolEnabled(ctx, context?.agent, "update_plan", metadata, currentSettings, authority) });
3255
+ }
3256
+ /**
3257
+ * Register selected Codex tools through the existing pipeline, without file tools or prompt hooks.
3258
+ * Compiled adapters receive authority once; the disposer supports an additional owner.
3259
+ */
3260
+ function registerCodexExecAndPlan(ctx, options = {}) {
3261
+ const currentSettings = () => ({
3262
+ ...CODEX_SETTINGS_ENTRY,
3263
+ ...readHostSettings(ctx, CODEX_SETTINGS_NAMESPACE)
3264
+ });
3265
+ const disposers = [];
3266
+ const dispose = composeToolDisposers(disposers);
3267
+ try {
3268
+ if (options.terminal !== false) disposers.push(registerExecTools(ctx, {
3269
+ defaultYieldTimeMs: options.defaultYieldTimeMs ?? 1e4,
3270
+ pollYieldTimeMs: options.pollYieldTimeMs ?? 5e3,
3271
+ writeYieldTimeMs: options.writeYieldTimeMs ?? 250,
3272
+ maxOutputBytes: options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
3273
+ currentSettings,
3274
+ ...options.capabilityAuthority?.terminalToolsEnabled === void 0 ? {} : { authority: options.capabilityAuthority.terminalToolsEnabled }
3275
+ }));
3276
+ if (options.plan !== false) disposers.push(registerPlanTool(ctx, currentSettings, true, options.capabilityAuthority?.planToolEnabled));
3277
+ return dispose;
3278
+ } catch (error) {
3279
+ dispose();
3280
+ throw error;
3281
+ }
2680
3282
  }
2681
3283
  /** Explicit preset instructions win without changing shared tools or permissions. */
2682
3284
  function withPresetPrompt(settings, presetPrompt) {
@@ -2687,7 +3289,6 @@ function withPresetPrompt(settings, presetPrompt) {
2687
3289
  }
2688
3290
  /** Mount the Codex prompt/tool layer inside one fixed agent preset. */
2689
3291
  function apply(ctx, config = {}) {
2690
- installPresetEditor(ctx);
2691
3292
  const resolved = {
2692
3293
  globalEnhancements: config.globalEnhancements ?? true,
2693
3294
  codexCore: config.codexCore ?? true,
@@ -2717,9 +3318,12 @@ function apply(ctx, config = {}) {
2717
3318
  } };
2718
3319
  const execConfig = {
2719
3320
  ...resolved,
2720
- currentSettings: codexSettings.current
3321
+ currentSettings: codexSettings.current,
3322
+ presetEnabled: config.terminalToolsEnabled !== false,
3323
+ presetOverridesLegacy: config.terminalToolsEnabled !== void 0
2721
3324
  };
2722
3325
  if (resolved.globalEnhancements) {
3326
+ installPresetEditor(ctx);
2723
3327
  watchConfiguredGptModels(ctx);
2724
3328
  registerCodexActivityProjection(ctx);
2725
3329
  installCodexContextProjection(ctx, codexSettings.current);
@@ -2743,7 +3347,7 @@ function apply(ctx, config = {}) {
2743
3347
  return legacySafeNext();
2744
3348
  }
2745
3349
  if (options.purpose === void 0 && isGptModel(options.model)) return repairLegacyPiAiContextOverflow(hostedWebSearchStream(next, {
2746
- serviceTier: options.serviceTier,
3350
+ serviceTier: options.serviceTier ?? (settings.fast ? "priority" : void 0),
2747
3351
  hostedWebSearch: resolved.hostedWebSearch && settings.hostedWebSearchEnabled,
2748
3352
  customApplyPatch: settings.patchToolEnabled
2749
3353
  }), options.model, contextWindow);
@@ -2751,15 +3355,22 @@ function apply(ctx, config = {}) {
2751
3355
  }));
2752
3356
  }
2753
3357
  if (resolved.codexCore) {
2754
- ctx.on("system-prompt/assemble", async (_assembly, _context, next) => applyPromptSections(applyCodexCapabilitySettings(await next(), codexSettings.current()), config.presetSections ?? {}));
3358
+ ctx.on("system-prompt/assemble", async (_assembly, context, next) => {
3359
+ const protectedNames = new Set([
3360
+ "deployment:persona-prefix",
3361
+ "deployment:persona-suffix",
3362
+ "codex:base"
3363
+ ].filter((name) => hasPresetPromptOverride(ctx, context, name)));
3364
+ return applyPromptSections(applyCodexPresentationSettings(await next(), codexSettings.current(), protectedNames), config.presetSections ?? {}, protectedNames);
3365
+ });
2755
3366
  ctx.systemPrompt.section({
2756
3367
  name: "codex:base",
2757
3368
  order: 10,
2758
3369
  text: () => codexSettings.current().promptEnabled ? resolveCodexSystemPrompt(codexSettings.current().systemPrompt) : ""
2759
3370
  });
2760
3371
  registerExecTools(ctx, execConfig);
2761
- registerPatchTool(ctx, codexSettings.current);
2762
- registerPlanTool(ctx, codexSettings.current);
3372
+ registerPatchTool(ctx, codexSettings.current, config.patchToolEnabled !== false, config.patchToolEnabled !== void 0);
3373
+ registerPlanTool(ctx, codexSettings.current, config.planToolEnabled !== false, void 0, config.planToolEnabled !== void 0);
2763
3374
  }
2764
3375
  }
2765
3376
  var types_default = {
@@ -2769,4 +3380,4 @@ var types_default = {
2769
3380
  apply
2770
3381
  };
2771
3382
  //#endregion
2772
- export { CODEX_SETTINGS_NAMESPACE, CODEX_SETTINGS_SCHEMA, Config, DEFAULT_CODEX_PERSONA, DEFAULT_CODEX_SYSTEM_PROMPT, DEFAULT_DSH_CORE_SOURCE_PROMPT, DEFAULT_DSH_CORE_WEB_PROMPT, apply, applyCodexCapabilitySettings, applyCodexRequestSettings, buildCodexSystemPrompt, types_default as default, enrichCodexModel, inject, name, normalizeCodexPromptAssembly, syncCodexContextWindow, withPresetPrompt };
3383
+ export { CODEX_SETTINGS_NAMESPACE, CODEX_SETTINGS_SCHEMA, Config, DEFAULT_CODEX_PERSONA, DEFAULT_CODEX_SYSTEM_PROMPT, DEFAULT_DSH_CORE_SOURCE_PROMPT, DEFAULT_DSH_CORE_WEB_PROMPT, apply, applyCodexCapabilitySettings, applyCodexRequestSettings, buildCodexSystemPrompt, types_default as default, enrichCodexModel, inject, name, normalizeCodexPromptAssembly, registerCodexExecAndPlan, syncCodexContextWindow, withPresetPrompt };