@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
@@ -1,8 +1,9 @@
1
1
  /** Codex-compatible prompt overlay and core tools for a dsh agent preset. */
2
2
  import z from '@deepseek-ai/schemastery';
3
3
  import { defineTool } from '@deepseek-ai/dsh-tools';
4
+ import { ESCALATION_TARGETS, sandboxPermissionsDescription } from '@deepseek-ai/dsh-sandbox';
4
5
  import { APPLY_PATCH_DESCRIPTION, applyPatchHunks, parsePatch } from "./patch.js";
5
- import { renderExecResult, runExecCommand, runWriteStdin } from "./exec.js";
6
+ import { renderExecResult, runExecCommand, runWriteStdin, supportsLegacyShellOptions } from "./exec.js";
6
7
  import { hostedWebSearchStream, installHostedWebSearch, remoteCompactStream, repairLegacyPiAiContextOverflow, } from "./remote.js";
7
8
  import { registerCodexActivityProjection } from "./activity.js";
8
9
  import { DEFAULT_CODEX_PERSONA, DEFAULT_CODEX_SYSTEM_PROMPT, DEFAULT_DSH_CORE_SOURCE_PROMPT, DEFAULT_DSH_CORE_WEB_PROMPT, resolveCodexSystemPrompt, } from "./prompt.js";
@@ -10,6 +11,8 @@ import { CODEX_SETTINGS_ENTRY, CODEX_SETTINGS_NAMESPACE, CODEX_SETTINGS_SCHEMA,
10
11
  import { codexCompactionMode } from "./compaction.js";
11
12
  import { CodexPresetEditor } from "./preset-editor.js";
12
13
  import { applyPromptSections, Config as PromptSectionsConfig } from "./prompt-sections.js";
14
+ import { readHostSettings } from "./host-settings.js";
15
+ import { codexToolEnabled, markCodexTool, hasPresetPromptOverride } from "./tool-capabilities.js";
13
16
  export { DEFAULT_CODEX_PERSONA, DEFAULT_CODEX_SYSTEM_PROMPT, DEFAULT_DSH_CORE_SOURCE_PROMPT, DEFAULT_DSH_CORE_WEB_PROMPT, } from "./prompt.js";
14
17
  export { CODEX_SETTINGS_NAMESPACE, CODEX_SETTINGS_SCHEMA } from "./settings.js";
15
18
  export const name = 'codex';
@@ -106,7 +109,7 @@ async function enrichConfiguredGptModels(ctx) {
106
109
  const settings = ctx.get('settings');
107
110
  if (settings === undefined)
108
111
  return;
109
- const current = settings.get(LLM_PI_AI_SETTINGS);
112
+ const current = readHostSettings(ctx, LLM_PI_AI_SETTINGS);
110
113
  if (current?.providers === undefined)
111
114
  return;
112
115
  const providers = {};
@@ -196,7 +199,7 @@ function installCodexSettings(ctx, systemPrompt, persona, harnessSourcePrompt, w
196
199
  attachSettings(settingsCtx.settings);
197
200
  });
198
201
  }
199
- return { current: () => withDefaults(source()) };
202
+ return { current: () => withDefaults(readHostSettings(ctx, CODEX_SETTINGS_NAMESPACE) ?? source()) };
200
203
  }
201
204
  /** Read the event snapshot across the pre- and post-0.1.2 DSH session APIs. */
202
205
  function sessionEvents(session) {
@@ -239,6 +242,10 @@ export function syncCodexContextWindow(session, contextWindow) {
239
242
  provider: config.provider,
240
243
  model: config.model,
241
244
  contextWindow,
245
+ // Capacity is only one field of the routed capability snapshot.
246
+ ...current?.provider === config.provider && current.model === config.model ? {
247
+ ...current.systemPromptUpdate === undefined ? {} : { systemPromptUpdate: current.systemPromptUpdate },
248
+ } : {},
242
249
  });
243
250
  }
244
251
  /** Keep the official context meter synchronized with a live Codex override. */
@@ -273,14 +280,15 @@ function installCodexContextProjection(ctx, current) {
273
280
  // Restored sessions may already contain their request/header seed, so no
274
281
  // session/event is emitted for the initial capacity. Catch them at the
275
282
  // store publication boundary as well.
276
- ctx.on('session/created', (session) => { sync(session); });
283
+ ctx.on('session/created', syncAfterPublication);
277
284
  // Use the resolved value carried by the consumer-facing event. This avoids
278
285
  // waiting for the settings source closure to refresh before synchronizing
279
286
  // already-open sessions.
280
- ctx.on('settings/updated', (ns, next) => {
281
- if (ns === CODEX_SETTINGS_NAMESPACE) {
287
+ // Removed from the current typed Event map, but still emitted by older settings providers.
288
+ const legacyEvents = ctx;
289
+ legacyEvents.on('settings/updated', (ns, next) => {
290
+ if (ns === CODEX_SETTINGS_NAMESPACE)
282
291
  syncAll(next.contextWindow);
283
- }
284
292
  });
285
293
  ctx.on('settings/document-updated', ns => {
286
294
  if (ns === CODEX_SETTINGS_NAMESPACE)
@@ -302,12 +310,13 @@ export function applyCodexRequestSettings(request, settings) {
302
310
  /** Put the agent persona first and omit the generic Harness identity opener. */
303
311
  export function normalizeCodexPromptAssembly(assembly) {
304
312
  const sections = assembly.sections.filter(section => section.name !== 'harness:identity');
305
- const persona = sections.find(section => section.name === 'deployment:persona');
313
+ const persona = sections.find(section => section.name === 'deployment:persona-prefix')
314
+ ?? sections.find(section => section.name === 'deployment:persona');
306
315
  if (persona === undefined)
307
316
  return { ...assembly, sections };
308
317
  return {
309
318
  ...assembly,
310
- sections: [persona, ...sections.filter(section => section.name !== 'deployment:persona')],
319
+ sections: [persona, ...sections.filter(section => section !== persona)],
311
320
  };
312
321
  }
313
322
  function sectionText(assembly, name) {
@@ -337,11 +346,13 @@ function interpolateCodexPrompt(text, variables) {
337
346
  function applyCodexPromptOverrides(assembly, settings) {
338
347
  const overrides = {
339
348
  'deployment:persona': settings.persona,
349
+ 'deployment:persona-prefix': settings.persona,
340
350
  'harness:source': settings.harnessSourcePrompt,
341
351
  'app:web-surface': settings.webSurfacePrompt,
342
352
  };
343
353
  const defaults = {
344
354
  'deployment:persona': DEFAULT_CODEX_PERSONA,
355
+ 'deployment:persona-prefix': DEFAULT_CODEX_PERSONA,
345
356
  'harness:source': DEFAULT_DSH_CORE_SOURCE_PROMPT,
346
357
  'app:web-surface': DEFAULT_DSH_CORE_WEB_PROMPT,
347
358
  };
@@ -371,10 +382,20 @@ export function applyCodexCapabilitySettings(assembly, settings) {
371
382
  for (const name of names)
372
383
  disabled.add(name);
373
384
  }
374
- const filtered = disabled.size === 0
385
+ // Legacy hosts expose tools here; current hosts own them in the tool registry
386
+ // and pass only presentation fields. Registration conditions below handle that path.
387
+ const tools = assembly.tools;
388
+ const filtered = disabled.size === 0 || tools === undefined
375
389
  ? assembly
376
- : { ...assembly, tools: assembly.tools.filter(tool => !disabled.has(tool.name)) };
377
- const withOverrides = applyCodexPromptOverrides(filtered, settings);
390
+ : { ...assembly, tools: tools.filter(tool => !disabled.has(tool.name)) };
391
+ return applyCodexPresentationSettings(filtered, settings);
392
+ }
393
+ /** Current SDK declarations remain registry-owned; preferences affect presentation only. */
394
+ function applyCodexPresentationSettings(assembly, settings, protectedNames) {
395
+ const promptSettings = { ...settings };
396
+ if (protectedNames?.has('deployment:persona-prefix'))
397
+ delete promptSettings.persona;
398
+ const withOverrides = applyCodexPromptOverrides(assembly, promptSettings);
378
399
  return settings.promptEnabled ? normalizeCodexPromptAssembly(withOverrides) : withOverrides;
379
400
  }
380
401
  /** Build the complete plugin-owned prompt, preserving an intentional empty value. */
@@ -385,19 +406,23 @@ const EXEC_COMMAND_DESCRIPTION = 'Runs a shell command. By default it uses pipes
385
406
  const WRITE_STDIN_DESCRIPTION = 'Polls output from an existing unified exec session. Non-empty chars can be sent only to a session created with tty=true; pipe-backed sessions accept empty chars for polling only.';
386
407
  const UPDATE_PLAN_DESCRIPTION = 'Updates the task plan.\nProvide an optional explanation and a list of plan items, each with a step and status.\nAt most one step can be in_progress at a time.';
387
408
  const PLAN_STATUSES = ['pending', 'in_progress', 'completed'];
388
- function assertCapabilityEnabled(current, setting, toolName) {
389
- if (!current()[setting])
409
+ function assertCapabilityEnabled(ctx, current, toolName, agent, metadata, authority) {
410
+ if (!codexToolEnabled(ctx, agent, toolName, metadata, current, authority)) {
390
411
  throw new Error(`${toolName}: disabled in Codex Harness plugin settings`);
412
+ }
391
413
  }
392
- function sessionCwd(exec) {
393
- return exec.agent?.session.header.cwd;
414
+ function sessionCwd(ctx, exec) {
415
+ if (exec.agent === undefined)
416
+ return undefined;
417
+ const directories = ctx.get('workingDirectory');
418
+ return directories?.get(exec.agent.session) ?? exec.agent.session.header.cwd;
394
419
  }
395
420
  function resolvePolicy(ctx, exec) {
396
421
  const policy = ctx.get('sandboxPolicy');
397
422
  return policy?.resolve(exec.agent === undefined ? {} : { session: exec.agent.session });
398
423
  }
399
424
  async function resolveTarget(ctx, path, exec) {
400
- const cwd = sessionCwd(exec);
425
+ const cwd = sessionCwd(ctx, exec);
401
426
  return ctx.fs.resolve(path, cwd === undefined ? { signal: exec.signal } : { cwd, signal: exec.signal });
402
427
  }
403
428
  async function observedTarget(ctx, target, exec) {
@@ -416,11 +441,13 @@ async function writePatchedFile(ctx, target, content, fallback, exec, policy) {
416
441
  return outcome.operation === 'create' ? 'created' : 'updated';
417
442
  }
418
443
  async function deletePatchedFile(ctx, target, version, exec, policy) {
419
- const remove = ctx.fs.remove;
444
+ const fs = ctx.fs;
445
+ const remove = fs.deleteFile ?? fs.remove;
420
446
  if (typeof remove !== 'function') {
421
447
  throw new Error('apply_patch: the configured dsh filesystem does not support file deletion');
422
448
  }
423
- await remove.call(ctx.fs, target, { version }, exec.signal, policy);
449
+ const expected = await ctx.waterfall('fs/delete-intent', target, exec, () => ({ version }));
450
+ await remove.call(ctx.fs, target, expected, exec.signal, policy);
424
451
  ctx.emit('fs/observed', target, { kind: 'absent' }, exec);
425
452
  }
426
453
  async function applyOnePatch(ctx, file, exec, policy) {
@@ -488,19 +515,54 @@ function planTodos(args) {
488
515
  throw new Error('update_plan: at most one step may be in_progress');
489
516
  return todos;
490
517
  }
518
+ /** Release every registration once, even when one release fails. */
519
+ function composeToolDisposers(disposers) {
520
+ return () => {
521
+ const errors = [];
522
+ for (const dispose of disposers.splice(0).reverse()) {
523
+ try {
524
+ dispose();
525
+ }
526
+ catch (error) {
527
+ errors.push(error);
528
+ }
529
+ }
530
+ if (errors.length > 0)
531
+ throw new AggregateError(errors, 'Could not unregister Codex tools');
532
+ };
533
+ }
491
534
  function registerExecTools(ctx, config) {
492
- ctx.tools.register(defineTool({
535
+ const tools = ctx.get('tools');
536
+ if (tools === undefined)
537
+ throw new Error('Codex execution tools require ctx.tools');
538
+ const shell = ctx.get('shell');
539
+ if (shell === undefined)
540
+ throw new Error('Codex execution tools require ctx.shell');
541
+ const confines = shell.sandboxMode !== undefined;
542
+ if (confines && ctx.get('sandboxPolicy') === undefined)
543
+ throw new Error('Codex execution tools: a sandboxing shell requires ctx.sandboxPolicy');
544
+ const legacyShellOptions = supportsLegacyShellOptions(ctx);
545
+ const metadata = { capability: 'terminalToolsEnabled', presetEnabled: config.presetEnabled !== false,
546
+ ...(config.presetOverridesLegacy ? { presetOverridesLegacy: true } : {}) };
547
+ const unregisterExec = tools.register(markCodexTool(defineTool({
493
548
  name: 'exec_command',
494
- description: EXEC_COMMAND_DESCRIPTION,
549
+ description: legacyShellOptions ? EXEC_COMMAND_DESCRIPTION
550
+ : EXEC_COMMAND_DESCRIPTION.replace('Runs a shell command.', 'Runs a command in the host-configured shell.'),
495
551
  parameters: {
496
552
  cmd: { type: 'string', required: true, description: 'Shell command to execute.' },
497
553
  workdir: { type: 'string', description: 'Working directory for the command. Defaults to the turn cwd.' },
498
- tty: { type: 'boolean', description: 'True allocates a PTY for the command; false or omitted uses plain pipes.' },
554
+ tty: { type: 'boolean', 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.' },
499
555
  run_in_background: { type: 'boolean', description: 'Run as a DSH background job and return its job id immediately; collect output with job_output and stop it with job_kill. Only supported for pipe-backed commands.' },
500
556
  yield_time_ms: { type: 'number', description: 'Wait before yielding output. Defaults to 10000 ms; effective range is 250-30000 ms.' },
501
557
  max_output_tokens: { type: 'number', description: 'Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy.' },
502
- shell: { type: 'string', description: "Shell binary to launch. Defaults to the user's default shell." },
503
- login: { type: 'boolean', description: 'True runs the shell with -l/-i semantics; false disables them. Defaults to true.' },
558
+ ...confines ? {
559
+ sandbox_permissions: { type: 'string', enum: [...ESCALATION_TARGETS], description: sandboxPermissionsDescription('command') },
560
+ justification: { type: 'string', 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.' },
561
+ } : {},
562
+ ...legacyShellOptions ? {
563
+ shell: { type: 'string', description: "Shell binary to launch. Defaults to the user's default shell." },
564
+ login: { type: 'boolean', description: 'True runs the shell with -l/-i semantics; false disables them. Defaults to true.' },
565
+ } : {},
504
566
  },
505
567
  output: {
506
568
  schema: {
@@ -519,7 +581,7 @@ function registerExecTools(ctx, config) {
519
581
  render: (_args, value) => [{ type: 'text', text: renderExecResult(value) }],
520
582
  },
521
583
  async execute(args, exec) {
522
- assertCapabilityEnabled(config.currentSettings, 'terminalToolsEnabled', 'exec_command');
584
+ assertCapabilityEnabled(ctx, config.currentSettings, 'exec_command', exec.agent, metadata, config.authority);
523
585
  return runExecCommand(ctx, args, exec, config);
524
586
  },
525
587
  presentCall: args => ({
@@ -527,39 +589,48 @@ function registerExecTools(ctx, config) {
527
589
  title: args.cmd,
528
590
  ...args.workdir === undefined ? {} : { cwd: args.workdir },
529
591
  }),
530
- }));
531
- ctx.tools.register(defineTool({
532
- name: 'write_stdin',
533
- description: WRITE_STDIN_DESCRIPTION,
534
- parameters: {
535
- session_id: { type: 'number', required: true, description: 'Identifier of the running unified exec session.' },
536
- chars: { type: 'string', 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.' },
537
- yield_time_ms: { type: 'number', 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.' },
538
- max_output_tokens: { type: 'number', description: 'Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy.' },
539
- },
540
- output: {
541
- schema: {
542
- type: 'object',
543
- additionalProperties: false,
544
- properties: {
545
- chunk_id: { type: 'string' },
546
- wall_time_seconds: { type: 'number', required: true },
547
- exit_code: { type: 'number' },
548
- session_id: { type: 'number' },
549
- original_token_count: { type: 'number' },
550
- output: { type: 'string', required: true },
592
+ }), metadata), { when: context => codexToolEnabled(ctx, context?.agent, 'exec_command', metadata, config.currentSettings, config.authority) });
593
+ try {
594
+ const unregisterStdin = tools.register(markCodexTool(defineTool({
595
+ name: 'write_stdin',
596
+ description: WRITE_STDIN_DESCRIPTION,
597
+ parameters: {
598
+ session_id: { type: 'number', required: true, description: 'Identifier of the running unified exec session.' },
599
+ chars: { type: 'string', 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.' },
600
+ yield_time_ms: { type: 'number', 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.' },
601
+ max_output_tokens: { type: 'number', description: 'Output token budget. Defaults to 10000 tokens; larger requests may be capped by policy.' },
602
+ },
603
+ output: {
604
+ schema: {
605
+ type: 'object',
606
+ additionalProperties: false,
607
+ properties: {
608
+ chunk_id: { type: 'string' },
609
+ wall_time_seconds: { type: 'number', required: true },
610
+ exit_code: { type: 'number' },
611
+ session_id: { type: 'number' },
612
+ original_token_count: { type: 'number' },
613
+ output: { type: 'string', required: true },
614
+ },
551
615
  },
616
+ render: (_args, value) => [{ type: 'text', text: renderExecResult(value) }],
552
617
  },
553
- render: (_args, value) => [{ type: 'text', text: renderExecResult(value) }],
554
- },
555
- async execute(args, exec) {
556
- assertCapabilityEnabled(config.currentSettings, 'terminalToolsEnabled', 'write_stdin');
557
- return runWriteStdin(ctx, args, exec, config);
558
- },
559
- }));
618
+ async execute(args, exec) {
619
+ assertCapabilityEnabled(ctx, config.currentSettings, 'write_stdin', exec.agent, metadata, config.authority);
620
+ return runWriteStdin(ctx, args, exec, config);
621
+ },
622
+ }), metadata), { when: context => codexToolEnabled(ctx, context?.agent, 'write_stdin', metadata, config.currentSettings, config.authority) });
623
+ return composeToolDisposers([unregisterExec, unregisterStdin]);
624
+ }
625
+ catch (error) {
626
+ unregisterExec();
627
+ throw error;
628
+ }
560
629
  }
561
- function registerPatchTool(ctx, currentSettings) {
562
- ctx.tools.register(defineTool({
630
+ function registerPatchTool(ctx, currentSettings, presetEnabled = true, presetOverridesLegacy = false) {
631
+ const metadata = { capability: 'patchToolEnabled', presetEnabled,
632
+ ...(presetOverridesLegacy ? { presetOverridesLegacy: true } : {}) };
633
+ ctx.tools.register(markCodexTool(defineTool({
563
634
  name: 'apply_patch',
564
635
  description: APPLY_PATCH_DESCRIPTION,
565
636
  parameters: {
@@ -588,7 +659,7 @@ function registerPatchTool(ctx, currentSettings) {
588
659
  render: (_args, value) => [{ type: 'text', text: patchSummary(value) }],
589
660
  },
590
661
  async execute(args, exec) {
591
- assertCapabilityEnabled(currentSettings, 'patchToolEnabled', 'apply_patch');
662
+ assertCapabilityEnabled(ctx, currentSettings, 'apply_patch', exec.agent, metadata);
592
663
  const files = parsePatch(args.input);
593
664
  const policy = resolvePolicy(ctx, exec);
594
665
  const applied = [];
@@ -604,10 +675,15 @@ function registerPatchTool(ctx, currentSettings) {
604
675
  rawInput: args.input,
605
676
  };
606
677
  },
607
- }));
608
- }
609
- function registerPlanTool(ctx, currentSettings) {
610
- ctx.tools.register(defineTool({
678
+ }), metadata), { when: context => codexToolEnabled(ctx, context?.agent, 'apply_patch', metadata, currentSettings) });
679
+ }
680
+ function registerPlanTool(ctx, currentSettings, presetEnabled = true, authority, presetOverridesLegacy = false) {
681
+ const tools = ctx.get('tools');
682
+ if (tools === undefined)
683
+ throw new Error('Codex plan tools require ctx.tools');
684
+ const metadata = { capability: 'planToolEnabled', presetEnabled,
685
+ ...(presetOverridesLegacy ? { presetOverridesLegacy: true } : {}) };
686
+ return tools.register(markCodexTool(defineTool({
611
687
  name: 'update_plan',
612
688
  description: UPDATE_PLAN_DESCRIPTION,
613
689
  parameters: {
@@ -631,14 +707,44 @@ function registerPlanTool(ctx, currentSettings) {
631
707
  render: () => [{ type: 'text', text: 'Plan updated' }],
632
708
  },
633
709
  execute(args, exec) {
634
- assertCapabilityEnabled(currentSettings, 'planToolEnabled', 'update_plan');
710
+ assertCapabilityEnabled(ctx, currentSettings, 'update_plan', exec.agent, metadata, authority);
635
711
  const agent = exec.agent;
636
712
  if (agent === undefined)
637
713
  throw new Error('update_plan requires an owning agent session');
638
714
  agent.session.append('todo/write', { todos: planTodos(args) });
639
715
  return Promise.resolve({});
640
716
  },
641
- }));
717
+ }), metadata), { when: context => codexToolEnabled(ctx, context?.agent, 'update_plan', metadata, currentSettings, authority) });
718
+ }
719
+ /**
720
+ * Register selected Codex tools through the existing pipeline, without file tools or prompt hooks.
721
+ * Compiled adapters receive authority once; the disposer supports an additional owner.
722
+ */
723
+ export function registerCodexExecAndPlan(ctx, options = {}) {
724
+ const currentSettings = () => ({
725
+ ...CODEX_SETTINGS_ENTRY,
726
+ ...readHostSettings(ctx, CODEX_SETTINGS_NAMESPACE),
727
+ });
728
+ const disposers = [];
729
+ const dispose = composeToolDisposers(disposers);
730
+ try {
731
+ if (options.terminal !== false)
732
+ disposers.push(registerExecTools(ctx, {
733
+ defaultYieldTimeMs: options.defaultYieldTimeMs ?? 10_000,
734
+ pollYieldTimeMs: options.pollYieldTimeMs ?? 5_000,
735
+ writeYieldTimeMs: options.writeYieldTimeMs ?? 250,
736
+ maxOutputBytes: options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
737
+ currentSettings,
738
+ ...(options.capabilityAuthority?.terminalToolsEnabled === undefined ? {} : { authority: options.capabilityAuthority.terminalToolsEnabled }),
739
+ }));
740
+ if (options.plan !== false)
741
+ disposers.push(registerPlanTool(ctx, currentSettings, true, options.capabilityAuthority?.planToolEnabled));
742
+ return dispose;
743
+ }
744
+ catch (error) {
745
+ dispose();
746
+ throw error;
747
+ }
642
748
  }
643
749
  /** Explicit preset instructions win without changing shared tools or permissions. */
644
750
  export function withPresetPrompt(settings, presetPrompt) {
@@ -646,7 +752,6 @@ export function withPresetPrompt(settings, presetPrompt) {
646
752
  }
647
753
  /** Mount the Codex prompt/tool layer inside one fixed agent preset. */
648
754
  export function apply(ctx, config = {}) {
649
- installPresetEditor(ctx);
650
755
  const resolved = {
651
756
  globalEnhancements: config.globalEnhancements ?? true,
652
757
  codexCore: config.codexCore ?? true,
@@ -679,8 +784,12 @@ export function apply(ctx, config = {}) {
679
784
  ...(config.remoteCompactionEnabled === undefined ? {} : { remoteCompactionEnabled: config.remoteCompactionEnabled }),
680
785
  };
681
786
  } };
682
- const execConfig = { ...resolved, currentSettings: codexSettings.current };
787
+ const execConfig = { ...resolved, currentSettings: codexSettings.current,
788
+ presetEnabled: config.terminalToolsEnabled !== false,
789
+ presetOverridesLegacy: config.terminalToolsEnabled !== undefined };
683
790
  if (resolved.globalEnhancements) {
791
+ // Native presets reject host services in their isolated composition.
792
+ installPresetEditor(ctx);
684
793
  // The generic pi-ai plugin remains the owner of provider routes. This
685
794
  // layer adds only request metadata and remote-first transport behavior.
686
795
  watchConfiguredGptModels(ctx);
@@ -712,7 +821,7 @@ export function apply(ctx, config = {}) {
712
821
  }
713
822
  if (options.purpose === undefined && isGptModel(options.model)) {
714
823
  return repairLegacyPiAiContextOverflow(hostedWebSearchStream(next, {
715
- serviceTier: options.serviceTier,
824
+ serviceTier: options.serviceTier ?? (settings.fast ? 'priority' : undefined),
716
825
  hostedWebSearch: resolved.hostedWebSearch && settings.hostedWebSearchEnabled,
717
826
  customApplyPatch: settings.patchToolEnabled,
718
827
  }), options.model, contextWindow);
@@ -721,7 +830,11 @@ export function apply(ctx, config = {}) {
721
830
  }));
722
831
  }
723
832
  if (resolved.codexCore) {
724
- ctx.on('system-prompt/assemble', async (_assembly, _context, next) => applyPromptSections(applyCodexCapabilitySettings(await next(), codexSettings.current()), config.presetSections ?? {}));
833
+ ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
834
+ const protectedNames = new Set(['deployment:persona-prefix', 'deployment:persona-suffix', 'codex:base']
835
+ .filter(name => hasPresetPromptOverride(ctx, context, name)));
836
+ return applyPromptSections(applyCodexPresentationSettings(await next(), codexSettings.current(), protectedNames), config.presetSections ?? {}, protectedNames);
837
+ });
725
838
  ctx.systemPrompt.section({
726
839
  name: 'codex:base',
727
840
  order: 10,
@@ -730,8 +843,8 @@ export function apply(ctx, config = {}) {
730
843
  : '',
731
844
  });
732
845
  registerExecTools(ctx, execConfig);
733
- registerPatchTool(ctx, codexSettings.current);
734
- registerPlanTool(ctx, codexSettings.current);
846
+ registerPatchTool(ctx, codexSettings.current, config.patchToolEnabled !== false, config.patchToolEnabled !== undefined);
847
+ registerPlanTool(ctx, codexSettings.current, config.planToolEnabled !== false, undefined, config.planToolEnabled !== undefined);
735
848
  }
736
849
  }
737
850
  export default { name, inject, Config, apply };
@@ -5,6 +5,7 @@ import { homedir } from 'node:os';
5
5
  import { dirname, join, resolve } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { CODEX_SETTINGS_ENTRY, CODEX_SETTINGS_NAMESPACE, CODEX_SETTINGS_SCHEMA, } from "./settings.js";
8
+ import { desktopCodexPreset } from "./desktop-preset.js";
8
9
  const PRESET_FILES = ['agent.cordis.yml', 'preset.yml'];
9
10
  const MANAGED_SIGNATURE_FILE = '.dsh-codex-harness-managed';
10
11
  const BUNDLED_PRESET_ID = 'codex-collaboration';
@@ -42,7 +43,7 @@ function dshHomePath(...segments) {
42
43
  }
43
44
  /** Bundle plugin name for the preset installer. */
44
45
  export const name = 'codex-preset-installer';
45
- export const inject = ['settings'];
46
+ export const inject = ['settings', 'agentPresets'];
46
47
  function presetSignature(directory) {
47
48
  if (PRESET_FILES.some(file => !existsSync(join(directory, file))))
48
49
  return undefined;
@@ -133,8 +134,16 @@ export function retireLegacyCodexPreset(targetDir = dshHomePath('.agent-presets'
133
134
  }
134
135
  /** Install the preset during profile boot without changing the host tool catalog. */
135
136
  export function apply(ctx) {
137
+ const registry = ctx.agentPresets;
138
+ if (typeof registry?.register === 'function') {
139
+ // Desktop owns live in-memory revisions. The declaring fiber must own the
140
+ // async disposer, including disposal while registration is still mounting.
141
+ ctx.effect(() => registry.register(desktopCodexPreset(SOURCE_PRESET_DIR)), 'codex.preset');
142
+ return;
143
+ }
136
144
  try {
137
- ctx.settings.register(CODEX_SETTINGS_NAMESPACE, CODEX_SETTINGS_SCHEMA, { base: CODEX_SETTINGS_ENTRY });
145
+ const settings = ctx.settings;
146
+ settings.register(CODEX_SETTINGS_NAMESPACE, CODEX_SETTINGS_SCHEMA, { base: CODEX_SETTINGS_ENTRY });
138
147
  installCodexPreset();
139
148
  retireLegacyCodexPreset();
140
149
  }
@@ -0,0 +1,11 @@
1
+ /** Profile-backed live preferences on DSH 0.2; legacy hosts keep settings.yaml. */
2
+ import { Service, type Context } from '@deepseek-ai/cordis';
3
+ import { type CodexSettings } from './settings.ts';
4
+ export declare const Config: import("@deepseek-ai/schemastery").default<NoInfer<CodexSettings>, NoInfer<CodexSettings>, "volatile-defined">;
5
+ export default class CodexPreferences extends Service {
6
+ private readonly value;
7
+ static Config: import("@deepseek-ai/schemastery").default<NoInfer<CodexSettings>, NoInfer<CodexSettings>, "volatile-defined">;
8
+ constructor(ctx: Context, value: ReturnType<typeof Config>);
9
+ current(): CodexSettings;
10
+ }
11
+ //# sourceMappingURL=preferences.d.ts.map
@@ -0,0 +1,16 @@
1
+ /** Profile-backed live preferences on DSH 0.2; legacy hosts keep settings.yaml. */
2
+ import { Service } from '@deepseek-ai/cordis';
3
+ import { CODEX_SETTINGS_ENTRY, CODEX_SETTINGS_SCHEMA } from "./settings.js";
4
+ export const Config = CODEX_SETTINGS_SCHEMA.default(CODEX_SETTINGS_ENTRY).volatile();
5
+ export default class CodexPreferences extends Service {
6
+ value;
7
+ static Config = Config;
8
+ constructor(ctx, value) {
9
+ super(ctx, 'codexPreferences');
10
+ this.value = value;
11
+ }
12
+ current() {
13
+ return this.value.get() ?? CODEX_SETTINGS_ENTRY;
14
+ }
15
+ }
16
+ //# sourceMappingURL=preferences.js.map
@@ -17,12 +17,14 @@ declare const _default: {
17
17
  mode: "strict";
18
18
  typeSymbol: string;
19
19
  schema: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
20
+ create: () => z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
20
21
  };
21
22
  }[];
22
23
  result: {
23
24
  mode: "strict";
24
25
  typeSymbol: string;
25
26
  schema: z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
27
+ create: () => z.ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>;
26
28
  };
27
29
  }[];
28
30
  };
@@ -1,4 +1,6 @@
1
1
  import { z } from 'zod';
2
+ import { presetToolCatalogSchema } from "./preset-tool-catalog-schema.js";
3
+ import { presetPromptCatalogSchema } from "./preset-prompt-catalog-schema.js";
2
4
  const promptSections = z.array(z.object({ id: z.string(), label: z.string(), text: z.string().max(1_000_000), editable: z.boolean(), suppressed: z.boolean().optional() })).max(200);
3
5
  const fields = {
4
6
  name: z.string().max(200), description: z.string().max(4000),
@@ -21,14 +23,16 @@ function descriptor(method, parameter, input, output) {
21
23
  id, service: 'codexPresetEditor', namespace: 'codexPresetEditor', method,
22
24
  invocation: { kind: 'direct' },
23
25
  parameters: parameter ? [{ name: parameter, wire: parameter, source: 'json',
24
- codec: { mode: 'strict', typeSymbol: `${id}:${parameter}`, schema: input } }] : [],
25
- result: { mode: 'strict', typeSymbol: `${id}:result`, schema: output },
26
+ codec: { mode: 'strict', typeSymbol: `${id}:${parameter}`, schema: input, create: () => input } }] : [],
27
+ result: { mode: 'strict', typeSymbol: `${id}:result`, schema: output, create: () => output },
26
28
  };
27
29
  }
28
30
  export default {
29
31
  package: '@shuind/dsh-codex-harness',
30
32
  descriptors: [
31
33
  descriptor('catalog', undefined, z.unknown(), catalog),
34
+ descriptor('tools', 'id', z.string().min(1).max(256), presetToolCatalogSchema),
35
+ descriptor('prompts', 'id', z.string().min(1).max(256), presetPromptCatalogSchema),
32
36
  descriptor('read', 'id', z.string(), document),
33
37
  descriptor('update', 'rawInput', z.object({ ...fields, id: z.string(), revision: z.string().optional(), composition: z.string().max(1_000_000).optional(), enableCodex: z.boolean().optional(), promptSections: promptSections.optional(), codexOptions: codexOptionsPatch.optional() }), document),
34
38
  descriptor('create', 'rawInput', z.object({ ...fields, sourceId: z.string(), enableCodex: z.boolean().optional(), composition: z.string().max(1_000_000).optional(), promptSections: promptSections.optional(), codexOptions: codexOptionsPatch.optional() }), document),
@@ -1,13 +1,15 @@
1
1
  import type { Context } from '@deepseek-ai/cordis';
2
2
  import { TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
3
3
  import type { CodexSettings } from './settings.ts';
4
+ import type { PresetToolCatalog } from './tool-policy-contract.ts';
5
+ import type { PresetPromptCatalog } from './preset-prompt-contract.ts';
4
6
  import type { CodexPresetOptions, PresetCatalog, PresetCreateInput, PresetEditorInput, PresetEditorDocument, PresetPromptSection } from './preset-contract.ts';
5
7
  export type { PresetEditorInput, PresetEditorDocument } from './preset-contract.ts';
6
8
  export declare const DEFAULT_CODEX_PRESET_OPTIONS: CodexPresetOptions;
7
9
  export interface ResolvedPresetForEditor {
8
10
  id: string;
9
- trust: 'system' | 'user';
10
- path: string;
11
+ trust?: 'system' | 'user';
12
+ path?: string;
11
13
  broken?: string;
12
14
  name?: string;
13
15
  description?: string;
@@ -22,19 +24,19 @@ export interface AgentPresetsForEditor {
22
24
  name?: string;
23
25
  description?: string;
24
26
  }>;
25
- remoteExportList(): Promise<{
27
+ remoteExportList?(): Promise<{
26
28
  presets: Array<{
27
29
  id: string;
28
30
  name?: string;
29
31
  description?: string;
30
- trust: 'system' | 'user';
32
+ trust?: 'system' | 'user';
31
33
  isDefault: boolean;
32
34
  broken?: string;
33
35
  }>;
34
- authorable: boolean;
36
+ authorable?: boolean;
35
37
  }>;
36
- copy(from: string, id: string, name?: string): Promise<void>;
37
- remove(id: string): Promise<void>;
38
+ copy?(from: string, id: string, name?: string): Promise<void>;
39
+ remove?(id: string): Promise<void>;
38
40
  readonly roots?: readonly {
39
41
  path: string;
40
42
  trust: 'system' | 'user';
@@ -56,10 +58,13 @@ export declare function patchPresetMetadata(content: string, name: string, descr
56
58
  export declare class CodexPresetEditor extends TypertRemoteService {
57
59
  static inject: string[];
58
60
  private readonly agentPresets;
61
+ private readonly toolContext;
59
62
  private sharedSettings?;
60
63
  private indexed?;
61
64
  constructor(ctx: Context, _config?: undefined);
62
65
  catalog(): Promise<PresetCatalog>;
66
+ tools(id: string): Promise<PresetToolCatalog>;
67
+ prompts(id: string): Promise<PresetPromptCatalog>;
63
68
  read(id: string): Promise<PresetEditorDocument>;
64
69
  create(rawInput: PresetCreateInput): Promise<PresetEditorDocument>;
65
70
  update(rawInput: PresetEditorInput): Promise<PresetEditorDocument>;