@shuind/dsh-codex-harness 0.2.15 → 0.2.17

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.
package/lib/index.js CHANGED
@@ -1,13 +1,16 @@
1
1
  import z from "@deepseek-ai/schemastery";
2
2
  import { defineTool } from "@deepseek-ai/dsh-tools";
3
- import { randomBytes, randomUUID } from "node:crypto";
4
- import { join, resolve } from "node:path";
3
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
4
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
5
5
  import { credentialRef } from "@deepseek-ai/dsh-credentials";
6
6
  import { AsyncLocalStorage } from "node:async_hooks";
7
7
  import { mkdirSync, writeFileSync } from "node:fs";
8
8
  import { homedir } from "node:os";
9
9
  import { z as z$1 } from "zod";
10
10
  import BasicCompactionEngine from "@deepseek-ai/dsh-compaction-basic";
11
+ import { readFile, realpath, stat, unlink } from "node:fs/promises";
12
+ import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
13
+ import { Scalar, YAMLMap, isMap, isScalar, isSeq, parseDocument } from "yaml";
11
14
  //#region lib/types/patch.js
12
15
  /** Parser and line-oriented applicator for Codex's `apply_patch` language. */
13
16
  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.";
@@ -1379,6 +1382,582 @@ function withDurableContextCapacity(llm, ctx, activeSession) {
1379
1382
  }
1380
1383
  });
1381
1384
  //#endregion
1385
+ //#region lib/types/preset-editor.js
1386
+ let atomicWriteModule;
1387
+ function loadAtomicWrite() {
1388
+ return atomicWriteModule ??= import("@deepseek-ai/dsh-atomic-write");
1389
+ }
1390
+ const PRESET_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
1391
+ const DEFAULT_CODEX_PRESET_OPTIONS = {
1392
+ promptEnabled: true,
1393
+ terminalToolsEnabled: true,
1394
+ patchToolEnabled: true,
1395
+ planToolEnabled: true,
1396
+ hostedWebSearchEnabled: true,
1397
+ remoteCompactionEnabled: true
1398
+ };
1399
+ const CODEX_OPTION_KEYS = Object.keys(DEFAULT_CODEX_PRESET_OPTIONS);
1400
+ /** Parse tags as syntax only; never execute !!js or resolve aliases into objects. */
1401
+ function yaml(content) {
1402
+ const doc = parseDocument(content, {
1403
+ strict: true,
1404
+ uniqueKeys: true
1405
+ });
1406
+ if (doc.errors.length) throw new Error("invalid-preset-yaml");
1407
+ return doc;
1408
+ }
1409
+ function harnessConfig(content) {
1410
+ const doc = yaml(content);
1411
+ if (!isSeq(doc.contents)) throw new Error("unsupported-preset");
1412
+ const rows = doc.contents.items.filter((row) => isMap(row) && row.get("name") === "@shuind/dsh-codex-harness" && row.get("disabled") !== true);
1413
+ if (rows.length !== 1) throw new Error("unsupported-preset");
1414
+ const row = rows[0];
1415
+ let config = row.get("config", true);
1416
+ if (config === void 0) {
1417
+ config = new YAMLMap();
1418
+ row.set("config", config);
1419
+ }
1420
+ if (!isMap(config) || config.get("codexCore") === false) throw new Error("unsupported-preset");
1421
+ return {
1422
+ doc,
1423
+ config
1424
+ };
1425
+ }
1426
+ function explicitPrompt(content) {
1427
+ const { config } = harnessConfig(content);
1428
+ const node = config.get("presetPrompt", true) ?? config.get("systemPrompt", true);
1429
+ if (node === void 0) return void 0;
1430
+ if (!isScalar(node) || typeof node.value !== "string" || node.tag) throw new Error("unsupported-prompt-expression");
1431
+ return node.value;
1432
+ }
1433
+ const SECTION_PLUGIN = "@shuind/dsh-codex-harness/prompt-sections";
1434
+ function promptFile(node) {
1435
+ if (!node.tag || typeof node.value !== "string") return void 0;
1436
+ return node.value.match(/^process\.getBuiltinModule\(['"]node:fs['"]\)\.readFileSync\(new URL\(['"]([^'"]+)['"],\s*baseUrl\),\s*['"]utf8['"]\)$/)?.[1];
1437
+ }
1438
+ /** Read the actual literal prompt fields, including nested groups, without evaluating YAML tags. */
1439
+ function promptFields(doc) {
1440
+ const fields = [];
1441
+ function visit(sequence, parents = []) {
1442
+ if (!isSeq(sequence)) return;
1443
+ for (const row of sequence.items) {
1444
+ if (!isMap(row) || row.get("disabled") === true) continue;
1445
+ const path = [...parents, String(row.get("id"))];
1446
+ const config = row.get("config", true);
1447
+ if (isSeq(config)) {
1448
+ visit(config, path);
1449
+ continue;
1450
+ }
1451
+ if (!isMap(config)) continue;
1452
+ const plugin = String(row.get("name"));
1453
+ if (plugin === "@deepseek-ai/dsh-plan-mode") continue;
1454
+ const keys = plugin === "@deepseek-ai/dsh-persona" ? [
1455
+ "prefix",
1456
+ "text",
1457
+ "suffix"
1458
+ ] : plugin === "@shuind/dsh-codex-harness" || plugin === SECTION_PLUGIN ? [] : [
1459
+ "prefix",
1460
+ "suffix",
1461
+ "text",
1462
+ "section",
1463
+ "prompt",
1464
+ "systemPrompt",
1465
+ "instructions"
1466
+ ];
1467
+ for (const key of keys) {
1468
+ const node = config.get(key, true);
1469
+ if (!isScalar(node)) continue;
1470
+ fields.push({
1471
+ id: JSON.stringify([...path, key]),
1472
+ label: plugin === "@deepseek-ai/dsh-persona" ? key === "suffix" ? "Persona · suffix" : "Persona" : `${path.join(" / ")} · ${key}`,
1473
+ node,
1474
+ row: config,
1475
+ key
1476
+ });
1477
+ }
1478
+ }
1479
+ }
1480
+ visit(doc.contents);
1481
+ return fields;
1482
+ }
1483
+ function sectionConfig(content) {
1484
+ if (supportsCodex(content)) {
1485
+ const value = harnessConfig(content).config.get("presetSections", true);
1486
+ return isMap(value) ? value : void 0;
1487
+ }
1488
+ const doc = yaml(content);
1489
+ if (!isSeq(doc.contents)) return void 0;
1490
+ const row = doc.contents.items.find((row) => isMap(row) && row.get("name") === SECTION_PLUGIN);
1491
+ const config = isMap(row) ? row.get("config", true) : void 0;
1492
+ return isMap(config) ? config : void 0;
1493
+ }
1494
+ /** Some presets intentionally shadow host prompt sections with empty entries. */
1495
+ function suppressesHostSections(content) {
1496
+ const doc = yaml(content);
1497
+ let suppressed = false;
1498
+ function visit(sequence) {
1499
+ if (!isSeq(sequence)) return;
1500
+ for (const row of sequence.items) {
1501
+ if (!isMap(row)) continue;
1502
+ const id = String(row.get("id") ?? "");
1503
+ const plugin = String(row.get("name") ?? "");
1504
+ if (id === "story-prompt-clean-slate" || plugin === "./tools/prompt/clean-slate.mjs" || /(?:^|[\\/])clean-slate\.mjs$/u.test(plugin)) {
1505
+ suppressed = true;
1506
+ return;
1507
+ }
1508
+ const config = row.get("config", true);
1509
+ if (isSeq(config)) visit(config);
1510
+ if (suppressed) return;
1511
+ }
1512
+ }
1513
+ visit(doc.contents);
1514
+ return suppressed;
1515
+ }
1516
+ function readPromptSections(content, shared = {}) {
1517
+ const codex = supportsCodex(content);
1518
+ const overrides = sectionConfig(content);
1519
+ const fields = promptFields(yaml(content));
1520
+ const sections = fields.map(({ id, label, node }) => ({
1521
+ id,
1522
+ label,
1523
+ text: String(node.value ?? ""),
1524
+ editable: !node.tag && typeof node.value === "string"
1525
+ }));
1526
+ const persona = sections.find((section) => section.label === "Persona");
1527
+ const personaOverride = !overrides?.has("persona") && codex ? shared.persona : void 0;
1528
+ if (persona && typeof personaOverride === "string" && personaOverride !== DEFAULT_CODEX_PERSONA) persona.text = personaOverride;
1529
+ const hasHostSections = !fields.some((field) => field.label.startsWith("Persona") && field.row.get("complete") === true) && !suppressesHostSections(content);
1530
+ if (hasHostSections) sections.splice(persona ? 1 : 0, 0, {
1531
+ id: "harness:source",
1532
+ label: "DSH Core 源码说明",
1533
+ text: String(overrides?.get("harnessSourcePrompt") ?? (codex ? shared.harnessSourcePrompt : void 0) ?? DEFAULT_DSH_CORE_SOURCE_PROMPT),
1534
+ editable: true
1535
+ }, {
1536
+ id: "app:web-surface",
1537
+ label: "DSH Core Web 说明",
1538
+ text: String(overrides?.get("webSurfacePrompt") ?? (codex ? shared.webSurfacePrompt : void 0) ?? DEFAULT_DSH_CORE_WEB_PROMPT),
1539
+ editable: true
1540
+ });
1541
+ if (codex) {
1542
+ const index = persona ? hasHostSections ? 3 : 1 : hasHostSections ? 2 : 0;
1543
+ sections.splice(index, 0, {
1544
+ id: "codex:base",
1545
+ label: "Codex 操作提示词",
1546
+ text: explicitPrompt(content) ?? shared.systemPrompt ?? DEFAULT_CODEX_SYSTEM_PROMPT,
1547
+ editable: true
1548
+ });
1549
+ }
1550
+ return sections;
1551
+ }
1552
+ /** Patch the contributing fields, not a disconnected secondary prompt. */
1553
+ function patchPromptSections(content, sections) {
1554
+ const doc = yaml(content);
1555
+ const fields = promptFields(doc);
1556
+ const known = new Map(readPromptSections(content).map((section) => [section.id, section]));
1557
+ const overrides = {};
1558
+ const seen = /* @__PURE__ */ new Set();
1559
+ for (const section of sections) {
1560
+ const field = fields.find((field) => field.id === section.id);
1561
+ if (seen.has(section.id) || !known.get(section.id)?.editable && !(field && promptFile(field.node)) || typeof section.text !== "string" || section.text.length > 1e6) throw new Error("invalid-prompt-section");
1562
+ seen.add(section.id);
1563
+ if (field) {
1564
+ const node = new Scalar(section.text);
1565
+ node.type = Scalar.BLOCK_LITERAL;
1566
+ field.row.set(field.key, node);
1567
+ continue;
1568
+ }
1569
+ if (!supportsCodex(content) && known.get(section.id)?.text === section.text) continue;
1570
+ if (section.id === "harness:source") overrides.harnessSourcePrompt = section.text;
1571
+ if (section.id === "app:web-surface") overrides.webSurfacePrompt = section.text;
1572
+ }
1573
+ const personaFields = fields.filter((field) => known.get(field.id)?.label.startsWith("Persona"));
1574
+ if (supportsCodex(content) && personaFields.length) overrides.persona = personaFields.map((field) => sections.find((section) => section.id === field.id)?.text ?? String(field.node.value)).join("\n\n");
1575
+ let result = doc.toString({ lineWidth: 0 });
1576
+ if (supportsCodex(result)) {
1577
+ const { doc: next, config } = harnessConfig(result);
1578
+ const previous = config.get("presetSections", true);
1579
+ const merged = isMap(previous) ? previous : new YAMLMap();
1580
+ for (const [key, value] of Object.entries(overrides)) merged.set(key, value);
1581
+ config.set("presetSections", merged);
1582
+ result = next.toString({ lineWidth: 0 });
1583
+ const operating = sections.find((section) => section.id === "codex:base");
1584
+ if (operating) result = patchPresetComposition(result, operating.text);
1585
+ } else if (Object.keys(overrides).length) {
1586
+ const next = yaml(result);
1587
+ if (!isSeq(next.contents)) throw new Error("invalid-preset-yaml");
1588
+ let row = next.contents.items.find((row) => isMap(row) && row.get("name") === SECTION_PLUGIN);
1589
+ if (!isMap(row)) {
1590
+ const created = new YAMLMap();
1591
+ created.set("id", `prompt-sections-${randomUUID().slice(0, 8)}`);
1592
+ created.set("name", SECTION_PLUGIN);
1593
+ next.add(created);
1594
+ row = created;
1595
+ }
1596
+ const map = row;
1597
+ let config = map.get("config", true);
1598
+ if (!isMap(config)) {
1599
+ config = new YAMLMap();
1600
+ map.set("config", config);
1601
+ }
1602
+ for (const [key, value] of Object.entries(overrides)) config.set(key, value);
1603
+ result = next.toString({ lineWidth: 0 });
1604
+ }
1605
+ return result;
1606
+ }
1607
+ function readCodexPresetOptions(content) {
1608
+ try {
1609
+ const { config } = harnessConfig(content);
1610
+ const options = { ...DEFAULT_CODEX_PRESET_OPTIONS };
1611
+ for (const key of CODEX_OPTION_KEYS) {
1612
+ const value = config.get(key);
1613
+ if (typeof value === "boolean") options[key] = value;
1614
+ }
1615
+ return options;
1616
+ } catch {
1617
+ return { ...DEFAULT_CODEX_PRESET_OPTIONS };
1618
+ }
1619
+ }
1620
+ function supportsCodex(content) {
1621
+ try {
1622
+ harnessConfig(content);
1623
+ return true;
1624
+ } catch {
1625
+ return false;
1626
+ }
1627
+ }
1628
+ /** Structural validation only: executable tags stay inert until DSH mounts a selected preset. */
1629
+ function validateComposition(content) {
1630
+ if (content.length > 1e6) throw new Error("invalid-preset-yaml");
1631
+ const doc = yaml(content);
1632
+ if (!isSeq(doc.contents) || !doc.contents.items.length) throw new Error("invalid-preset-yaml");
1633
+ const ids = /* @__PURE__ */ new Set();
1634
+ for (const entry of doc.contents.items) {
1635
+ if (!isMap(entry)) throw new Error("invalid-preset-yaml");
1636
+ const row = entry;
1637
+ if (typeof row.get("name") !== "string") throw new Error("invalid-preset-yaml");
1638
+ const id = row.get("id");
1639
+ if (typeof id !== "string" || ids.has(id)) throw new Error("invalid-preset-yaml");
1640
+ ids.add(id);
1641
+ }
1642
+ }
1643
+ function enhanceComposition(content) {
1644
+ validateComposition(content);
1645
+ if (supportsCodex(content)) return content;
1646
+ const doc = yaml(content);
1647
+ if (!isSeq(doc.contents)) throw new Error("invalid-preset-yaml");
1648
+ if (doc.contents.items.some((row) => isMap(row) && row.get("name") === "@shuind/dsh-codex-harness")) throw new Error("ambiguous-harness-row");
1649
+ for (const row of doc.contents.items) {
1650
+ if (!isMap(row) || row.get("name") !== "@deepseek-ai/dsh-persona") continue;
1651
+ const persona = row.get("config", true);
1652
+ if (isMap(persona) && persona.get("complete") === true) persona.set("complete", false);
1653
+ }
1654
+ doc.add(doc.createNode({
1655
+ id: `codex-harness-${randomUUID().slice(0, 8)}`,
1656
+ name: "@shuind/dsh-codex-harness",
1657
+ config: {
1658
+ globalEnhancements: false,
1659
+ codexCore: true
1660
+ }
1661
+ }));
1662
+ return doc.toString({ lineWidth: 0 });
1663
+ }
1664
+ function patchPresetComposition(content, prompt, inherit = false) {
1665
+ const { doc, config } = harnessConfig(content);
1666
+ config.delete("systemPrompt");
1667
+ if (inherit) config.delete("presetPrompt");
1668
+ else {
1669
+ const node = new Scalar(prompt);
1670
+ node.type = prompt.includes("\n") ? Scalar.BLOCK_LITERAL : Scalar.QUOTE_DOUBLE;
1671
+ config.set("presetPrompt", node);
1672
+ }
1673
+ return doc.toString({ lineWidth: 0 });
1674
+ }
1675
+ /** Store user-facing Codex capability switches in the Harness row. */
1676
+ function patchCodexPresetOptions(content, options) {
1677
+ const { doc, config } = harnessConfig(content);
1678
+ for (const key of CODEX_OPTION_KEYS) {
1679
+ const value = options[key];
1680
+ if (value !== void 0) config.set(key, value);
1681
+ }
1682
+ return doc.toString({ lineWidth: 0 });
1683
+ }
1684
+ function patchPresetMetadata(content, name, description) {
1685
+ const doc = yaml(content);
1686
+ if (doc.contents !== null && !isMap(doc.contents)) throw new Error("invalid-preset-metadata");
1687
+ for (const [key, value] of Object.entries({
1688
+ name,
1689
+ description
1690
+ })) {
1691
+ const node = new Scalar(value);
1692
+ node.type = Scalar.QUOTE_DOUBLE;
1693
+ doc.set(key, node);
1694
+ }
1695
+ return doc.toString({ lineWidth: 0 });
1696
+ }
1697
+ function validate(input) {
1698
+ if (typeof input.name !== "string" || !input.name.trim() || /[\r\n]/.test(input.name) || input.name.length > 200) throw new Error("invalid-preset-name");
1699
+ if (typeof input.description !== "string" || input.description.length > 4e3) throw new Error("invalid-preset-description");
1700
+ if (typeof input.systemPrompt !== "string" || input.systemPrompt.length > 1e6) throw new Error("invalid-preset-prompt");
1701
+ return {
1702
+ ...input,
1703
+ name: input.name.trim()
1704
+ };
1705
+ }
1706
+ function revision(composition, metadata) {
1707
+ return createHash("sha256").update(composition).update("\0").update(metadata ?? "").digest("hex");
1708
+ }
1709
+ async function optionalFile(path) {
1710
+ try {
1711
+ return await readFile(path, "utf8");
1712
+ } catch (error) {
1713
+ if (error.code === "ENOENT") return void 0;
1714
+ throw error;
1715
+ }
1716
+ }
1717
+ async function mode(path) {
1718
+ try {
1719
+ return (await stat(path)).mode & 511;
1720
+ } catch {
1721
+ return 384;
1722
+ }
1723
+ }
1724
+ async function assertWithinRoot(path, roots) {
1725
+ if (!roots?.length) throw new Error("preset-root-unavailable");
1726
+ const target = await realpath(path);
1727
+ for (const root of roots) {
1728
+ if (root.trust !== "user") continue;
1729
+ const home = process.env.DSH_HOME ?? process.env.USERPROFILE ?? process.env.HOME ?? "";
1730
+ const expanded = root.path.replace(/^~(?=[\\/]|$)/, home);
1731
+ try {
1732
+ const rel = relative(await realpath(resolve(expanded)), target);
1733
+ if (!isAbsolute(rel) && rel !== ".." && !rel.startsWith("../") && !rel.startsWith("..\\")) return;
1734
+ } catch {}
1735
+ }
1736
+ throw new Error("preset-outside-user-root");
1737
+ }
1738
+ var CodexPresetEditor = class extends TypertRemoteService {
1739
+ static inject = ["agentPresets", "settings"];
1740
+ agentPresets;
1741
+ sharedSettings;
1742
+ indexed;
1743
+ constructor(ctx, _config) {
1744
+ super(ctx, "codexPresetEditor");
1745
+ this.agentPresets = ctx.get("agentPresets");
1746
+ const settings = ctx.get("settings");
1747
+ this.sharedSettings = () => settings?.get("codex") ?? {};
1748
+ }
1749
+ async catalog() {
1750
+ if (this.agentPresets.list) {
1751
+ const rows = await this.agentPresets.list();
1752
+ this.indexed = new Map(rows.map((row) => [row.id, row]));
1753
+ return {
1754
+ presets: rows.filter((row) => row.broken === void 0).map((row) => ({
1755
+ id: row.id,
1756
+ name: row.name || row.id,
1757
+ description: row.description ?? "",
1758
+ editable: row.trust === "user",
1759
+ isDefault: row.id === this.agentPresets.defaultId
1760
+ })),
1761
+ authorable: this.agentPresets.authorable ?? false,
1762
+ excludedCount: rows.filter((row) => row.broken !== void 0).length
1763
+ };
1764
+ }
1765
+ const roster = await this.agentPresets.remoteExportList();
1766
+ const presets = roster.presets.filter((row) => row.broken === void 0).map((row) => ({
1767
+ id: row.id,
1768
+ name: row.name || row.id,
1769
+ description: row.description ?? "",
1770
+ editable: row.trust === "user",
1771
+ isDefault: row.isDefault
1772
+ }));
1773
+ return {
1774
+ presets,
1775
+ authorable: roster.authorable,
1776
+ excludedCount: roster.presets.length - presets.length
1777
+ };
1778
+ }
1779
+ async read(id) {
1780
+ const preset = this.indexed?.get(id) ?? await this.preset(id);
1781
+ if (preset.broken !== void 0) throw new Error("invalid-preset");
1782
+ const [composition, metadata] = await Promise.all([readFile(preset.path, "utf8"), optionalFile(resolve(dirname(preset.path), "preset.yml"))]);
1783
+ const meta = metadata ? yaml(metadata) : void 0;
1784
+ validateComposition(composition);
1785
+ const codex = supportsCodex(composition);
1786
+ const prompt = codex ? explicitPrompt(composition) : void 0;
1787
+ const shared = this.sharedSettings?.() ?? {};
1788
+ const promptSections = readPromptSections(composition, shared);
1789
+ for (const field of promptFields(yaml(composition))) {
1790
+ const reference = promptFile(field.node);
1791
+ if (!reference) continue;
1792
+ const section = promptSections.find((section) => section.id === field.id);
1793
+ try {
1794
+ const root = await realpath(dirname(preset.path));
1795
+ const target = await realpath(resolve(root, reference));
1796
+ const rel = relative(root, target);
1797
+ if (isAbsolute(rel) || rel === ".." || rel.startsWith("../") || rel.startsWith("..\\")) continue;
1798
+ if ((await stat(target)).size > 1e6) continue;
1799
+ section.text = await readFile(target, "utf8");
1800
+ section.editable = true;
1801
+ } catch {}
1802
+ }
1803
+ return {
1804
+ id,
1805
+ name: String(meta?.get("name") ?? id),
1806
+ description: String(meta?.get("description") ?? ""),
1807
+ systemPrompt: prompt ?? shared.systemPrompt ?? DEFAULT_CODEX_SYSTEM_PROMPT,
1808
+ inheritPrompt: prompt === void 0,
1809
+ revision: revision(composition, metadata),
1810
+ editable: preset.trust === "user",
1811
+ codex,
1812
+ codexOptions: readCodexPresetOptions(composition),
1813
+ composition,
1814
+ promptSections
1815
+ };
1816
+ }
1817
+ async create(rawInput) {
1818
+ const input = validate(rawInput);
1819
+ await this.preset(input.sourceId);
1820
+ const id = `codex-${randomUUID().slice(0, 12)}`;
1821
+ await this.agentPresets.copy(input.sourceId, id, input.name);
1822
+ try {
1823
+ const copy = await this.read(id);
1824
+ const base = input.composition ?? copy.composition;
1825
+ let next = input.enableCodex ? enhanceComposition(base) : base;
1826
+ if (supportsCodex(next)) {
1827
+ next = patchPresetComposition(next, input.systemPrompt, input.inheritPrompt);
1828
+ next = patchCodexPresetOptions(next, input.codexOptions ?? {});
1829
+ }
1830
+ return await this.update({
1831
+ ...input,
1832
+ id,
1833
+ revision: copy.revision,
1834
+ composition: next
1835
+ });
1836
+ } catch (error) {
1837
+ await this.agentPresets.remove(id);
1838
+ throw error;
1839
+ }
1840
+ }
1841
+ async update(rawInput) {
1842
+ const input = validate(rawInput);
1843
+ const preset = await this.preset(input.id);
1844
+ if (preset.trust !== "user") throw new Error("built-in presets cannot be edited here");
1845
+ const composition = resolve(preset.path);
1846
+ if (composition.split(/[\\/]/).at(-1) !== "agent.cordis.yml") throw new Error("invalid-preset-path");
1847
+ await assertWithinRoot(composition, this.agentPresets.roots);
1848
+ const metadata = resolve(dirname(composition), "preset.yml");
1849
+ if (await optionalFile(metadata) !== void 0) await assertWithinRoot(metadata, this.agentPresets.roots);
1850
+ const { withFileLock, writeFileAtomic } = await loadAtomicWrite();
1851
+ return withFileLock(composition, async () => {
1852
+ const oldComposition = await readFile(composition, "utf8");
1853
+ const oldMetadata = await optionalFile(metadata);
1854
+ if (input.revision !== void 0 && input.revision !== revision(oldComposition, oldMetadata)) throw new Error("preset-conflict");
1855
+ const editedComposition = input.composition !== void 0 ? input.composition : oldComposition;
1856
+ let nextComposition = input.enableCodex && !supportsCodex(editedComposition) ? enhanceComposition(editedComposition) : editedComposition;
1857
+ if (supportsCodex(nextComposition)) {
1858
+ nextComposition = patchPresetComposition(nextComposition, input.systemPrompt, input.inheritPrompt);
1859
+ if (input.codexOptions !== void 0) nextComposition = patchCodexPresetOptions(nextComposition, input.codexOptions);
1860
+ }
1861
+ if (input.promptSections) nextComposition = patchPromptSections(nextComposition, input.promptSections);
1862
+ validateComposition(nextComposition);
1863
+ const nextMetadata = patchPresetMetadata(oldMetadata ?? "", input.name, input.description);
1864
+ const compositionMode = await mode(composition);
1865
+ const metadataMode = await mode(metadata);
1866
+ await writeFileAtomic(resolve(dirname(composition), ".codex-editor-backup.json"), JSON.stringify({
1867
+ composition: oldComposition,
1868
+ metadata: oldMetadata ?? null
1869
+ }), {
1870
+ mode: 384,
1871
+ dirMode: 448
1872
+ });
1873
+ try {
1874
+ await writeFileAtomic(composition, nextComposition, {
1875
+ mode: compositionMode,
1876
+ dirMode: 448
1877
+ });
1878
+ await writeFileAtomic(metadata, nextMetadata, {
1879
+ mode: metadataMode,
1880
+ dirMode: 448
1881
+ });
1882
+ const result = await this.agentPresets.resolve(input.id);
1883
+ if (result.broken !== void 0) throw new Error("invalid-preset-after-save");
1884
+ this.indexed?.set(input.id, result);
1885
+ return await this.read(input.id);
1886
+ } catch (error) {
1887
+ await writeFileAtomic(composition, oldComposition, {
1888
+ mode: compositionMode,
1889
+ dirMode: 448
1890
+ });
1891
+ if (oldMetadata !== void 0) await writeFileAtomic(metadata, oldMetadata, {
1892
+ mode: metadataMode,
1893
+ dirMode: 448
1894
+ });
1895
+ else await unlink(metadata).catch((cause) => {
1896
+ if (cause.code !== "ENOENT") throw cause;
1897
+ });
1898
+ throw error;
1899
+ }
1900
+ }, { waitMs: 1e4 });
1901
+ }
1902
+ async preset(id) {
1903
+ if (!PRESET_ID.test(id)) throw new Error("invalid-preset-id");
1904
+ const preset = await this.agentPresets.resolve(id);
1905
+ if (preset.broken !== void 0) throw new Error("invalid-preset");
1906
+ this.indexed ??= /* @__PURE__ */ new Map();
1907
+ this.indexed.set(id, preset);
1908
+ return preset;
1909
+ }
1910
+ };
1911
+ function markRemoteMethod(methodName) {
1912
+ const descriptor = Object.getOwnPropertyDescriptor(CodexPresetEditor.prototype, methodName);
1913
+ const initializers = [];
1914
+ Remote(methodName)(descriptor.value, {
1915
+ kind: "method",
1916
+ name: methodName,
1917
+ static: false,
1918
+ private: false,
1919
+ addInitializer: (initializer) => {
1920
+ initializers.push(initializer);
1921
+ }
1922
+ });
1923
+ const receiver = Object.create(CodexPresetEditor.prototype);
1924
+ for (const initializer of initializers) initializer.call(receiver);
1925
+ }
1926
+ for (const method of [
1927
+ "read",
1928
+ "update",
1929
+ "catalog",
1930
+ "create"
1931
+ ]) markRemoteMethod(method);
1932
+ //#endregion
1933
+ //#region lib/types/prompt-sections.js
1934
+ const Config$1 = z.object({
1935
+ persona: z.string(),
1936
+ harnessSourcePrompt: z.string(),
1937
+ webSurfacePrompt: z.string()
1938
+ });
1939
+ /** Override only existing sections; dynamic runtime context and tool guidance remain host-owned. */
1940
+ function applyPromptSections(assembly, config) {
1941
+ const variables = { ...assembly.variables };
1942
+ variables.sourceRoot ??= assembly.sections.find((s) => s.name === "harness:source")?.text.match(/^The DeepSeek Harness implementation checkout is at (.+?)\. The checkout location/u)?.[1];
1943
+ 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];
1944
+ const values = {
1945
+ "deployment:persona": config.persona,
1946
+ "harness:source": config.harnessSourcePrompt,
1947
+ "app:web-surface": config.webSurfacePrompt
1948
+ };
1949
+ return {
1950
+ ...assembly,
1951
+ sections: assembly.sections.map((section) => {
1952
+ const text = values[section.name];
1953
+ return text === void 0 ? section : {
1954
+ ...section,
1955
+ text: text.replace(/\{\{([\w.-]+)\}\}/g, (whole, key) => variables[key] ?? whole)
1956
+ };
1957
+ })
1958
+ };
1959
+ }
1960
+ //#endregion
1382
1961
  //#region lib/types/index.js
1383
1962
  /** Codex-compatible prompt overlay and core tools for a dsh agent preset. */
1384
1963
  const name = "codex";
@@ -1392,6 +1971,19 @@ const inject = [
1392
1971
  "settings"
1393
1972
  ];
1394
1973
  const DEFAULT_MAX_OUTPUT_BYTES = 1048576;
1974
+ /** Add the preset editor when DSH's optional user-preset service is available. */
1975
+ function installPresetEditor(ctx) {
1976
+ ctx.inject(["agentPresets"], (presetCtx) => {
1977
+ (async () => {
1978
+ try {
1979
+ await presetCtx.plugin(CodexPresetEditor);
1980
+ } catch (error) {
1981
+ ctx.logger.warn("codex: preset editor is unavailable on this host");
1982
+ ctx.logger.warn(error);
1983
+ }
1984
+ })();
1985
+ });
1986
+ }
1395
1987
  /** Runtime configuration schema for the Codex tool bridge. */
1396
1988
  const Config = z.object({
1397
1989
  globalEnhancements: z.boolean().default(true),
@@ -1403,6 +1995,14 @@ const Config = z.object({
1403
1995
  hostedWebSearch: z.boolean().default(true),
1404
1996
  remoteCompact: z.boolean().default(true),
1405
1997
  systemPrompt: z.string().default(DEFAULT_CODEX_SYSTEM_PROMPT),
1998
+ presetPrompt: z.string(),
1999
+ presetSections: Config$1,
2000
+ promptEnabled: z.boolean(),
2001
+ terminalToolsEnabled: z.boolean(),
2002
+ patchToolEnabled: z.boolean(),
2003
+ planToolEnabled: z.boolean(),
2004
+ hostedWebSearchEnabled: z.boolean(),
2005
+ remoteCompactionEnabled: z.boolean(),
1406
2006
  persona: z.string().default(DEFAULT_CODEX_PERSONA),
1407
2007
  harnessSourcePrompt: z.string().default(DEFAULT_DSH_CORE_SOURCE_PROMPT),
1408
2008
  webSurfacePrompt: z.string().default(DEFAULT_DSH_CORE_WEB_PROMPT)
@@ -2069,8 +2669,16 @@ function registerPlanTool(ctx, currentSettings) {
2069
2669
  }
2070
2670
  }));
2071
2671
  }
2672
+ /** Explicit preset instructions win without changing shared tools or permissions. */
2673
+ function withPresetPrompt(settings, presetPrompt) {
2674
+ return presetPrompt === void 0 ? settings : {
2675
+ ...settings,
2676
+ systemPrompt: presetPrompt
2677
+ };
2678
+ }
2072
2679
  /** Mount the Codex prompt/tool layer inside one fixed agent preset. */
2073
2680
  function apply(ctx, config = {}) {
2681
+ installPresetEditor(ctx);
2074
2682
  const resolved = {
2075
2683
  globalEnhancements: config.globalEnhancements ?? true,
2076
2684
  codexCore: config.codexCore ?? true,
@@ -2086,7 +2694,18 @@ function apply(ctx, config = {}) {
2086
2694
  webSurfacePrompt: config.webSurfacePrompt ?? DEFAULT_DSH_CORE_WEB_PROMPT
2087
2695
  };
2088
2696
  if (resolved.codexCore && ctx.fs.sandboxMode !== void 0 && ctx.get("sandboxPolicy") === void 0) throw new Error("codex: a sandboxing filesystem requires ctx.sandboxPolicy");
2089
- const codexSettings = installCodexSettings(ctx, resolved.systemPrompt, resolved.persona, resolved.harnessSourcePrompt, resolved.webSurfacePrompt);
2697
+ const sharedSettings = installCodexSettings(ctx, resolved.systemPrompt, resolved.persona, resolved.harnessSourcePrompt, resolved.webSurfacePrompt);
2698
+ const codexSettings = { current: () => {
2699
+ return {
2700
+ ...withPresetPrompt(sharedSettings.current(), config.presetPrompt),
2701
+ ...config.promptEnabled === void 0 ? {} : { promptEnabled: config.promptEnabled },
2702
+ ...config.terminalToolsEnabled === void 0 ? {} : { terminalToolsEnabled: config.terminalToolsEnabled },
2703
+ ...config.patchToolEnabled === void 0 ? {} : { patchToolEnabled: config.patchToolEnabled },
2704
+ ...config.planToolEnabled === void 0 ? {} : { planToolEnabled: config.planToolEnabled },
2705
+ ...config.hostedWebSearchEnabled === void 0 ? {} : { hostedWebSearchEnabled: config.hostedWebSearchEnabled },
2706
+ ...config.remoteCompactionEnabled === void 0 ? {} : { remoteCompactionEnabled: config.remoteCompactionEnabled }
2707
+ };
2708
+ } };
2090
2709
  const execConfig = {
2091
2710
  ...resolved,
2092
2711
  currentSettings: codexSettings.current
@@ -2123,7 +2742,7 @@ function apply(ctx, config = {}) {
2123
2742
  }));
2124
2743
  }
2125
2744
  if (resolved.codexCore) {
2126
- ctx.on("system-prompt/assemble", async (_assembly, _context, next) => applyCodexCapabilitySettings(await next(), codexSettings.current()));
2745
+ ctx.on("system-prompt/assemble", async (_assembly, _context, next) => applyPromptSections(applyCodexCapabilitySettings(await next(), codexSettings.current()), config.presetSections ?? {}));
2127
2746
  ctx.systemPrompt.section({
2128
2747
  name: "codex:base",
2129
2748
  order: 10,
@@ -2141,4 +2760,4 @@ var types_default = {
2141
2760
  apply
2142
2761
  };
2143
2762
  //#endregion
2144
- 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 };
2763
+ 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 };