primitive-admin 1.1.0-alpha.84 → 1.1.0-alpha.86

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 (132) hide show
  1. package/README.md +77 -1
  2. package/assets/skill/skills/primitive-platform/SKILL.md +8 -0
  3. package/dist/src/commands/admins.js +29 -32
  4. package/dist/src/commands/admins.js.map +1 -1
  5. package/dist/src/commands/analytics.js +15 -2
  6. package/dist/src/commands/analytics.js.map +1 -1
  7. package/dist/src/commands/apps.js +12 -5
  8. package/dist/src/commands/apps.js.map +1 -1
  9. package/dist/src/commands/blob-buckets.js +2 -1
  10. package/dist/src/commands/blob-buckets.js.map +1 -1
  11. package/dist/src/commands/catalog.js +26 -10
  12. package/dist/src/commands/catalog.js.map +1 -1
  13. package/dist/src/commands/collection-type-configs.js +2 -1
  14. package/dist/src/commands/collection-type-configs.js.map +1 -1
  15. package/dist/src/commands/collections.js +675 -19
  16. package/dist/src/commands/collections.js.map +1 -1
  17. package/dist/src/commands/connections.js +8 -9
  18. package/dist/src/commands/connections.js.map +1 -1
  19. package/dist/src/commands/cron-triggers.js +2 -1
  20. package/dist/src/commands/cron-triggers.js.map +1 -1
  21. package/dist/src/commands/database-type-configs.js +4 -3
  22. package/dist/src/commands/database-type-configs.js.map +1 -1
  23. package/dist/src/commands/databases.js +27 -10
  24. package/dist/src/commands/databases.js.map +1 -1
  25. package/dist/src/commands/documents.d.ts +20 -0
  26. package/dist/src/commands/documents.js +236 -28
  27. package/dist/src/commands/documents.js.map +1 -1
  28. package/dist/src/commands/email-templates.js +2 -1
  29. package/dist/src/commands/email-templates.js.map +1 -1
  30. package/dist/src/commands/env.js +11 -1
  31. package/dist/src/commands/env.js.map +1 -1
  32. package/dist/src/commands/feature-flags.js +2 -1
  33. package/dist/src/commands/feature-flags.js.map +1 -1
  34. package/dist/src/commands/functions.js +58 -6
  35. package/dist/src/commands/functions.js.map +1 -1
  36. package/dist/src/commands/group-type-configs.js +2 -1
  37. package/dist/src/commands/group-type-configs.js.map +1 -1
  38. package/dist/src/commands/groups.js +29 -8
  39. package/dist/src/commands/groups.js.map +1 -1
  40. package/dist/src/commands/guides.js +17 -11
  41. package/dist/src/commands/guides.js.map +1 -1
  42. package/dist/src/commands/integrations.js +30 -9
  43. package/dist/src/commands/integrations.js.map +1 -1
  44. package/dist/src/commands/locks.js +2 -1
  45. package/dist/src/commands/locks.js.map +1 -1
  46. package/dist/src/commands/metadata-category-configs.js +2 -1
  47. package/dist/src/commands/metadata-category-configs.js.map +1 -1
  48. package/dist/src/commands/metadata.js +8 -1
  49. package/dist/src/commands/metadata.js.map +1 -1
  50. package/dist/src/commands/prompts.js +28 -11
  51. package/dist/src/commands/prompts.js.map +1 -1
  52. package/dist/src/commands/rule-sets.js +2 -1
  53. package/dist/src/commands/rule-sets.js.map +1 -1
  54. package/dist/src/commands/scripts.js +15 -6
  55. package/dist/src/commands/scripts.js.map +1 -1
  56. package/dist/src/commands/secrets.js +2 -1
  57. package/dist/src/commands/secrets.js.map +1 -1
  58. package/dist/src/commands/sessions.js +10 -9
  59. package/dist/src/commands/sessions.js.map +1 -1
  60. package/dist/src/commands/sync.d.ts +125 -29
  61. package/dist/src/commands/sync.js +865 -88
  62. package/dist/src/commands/sync.js.map +1 -1
  63. package/dist/src/commands/tokens.js +2 -1
  64. package/dist/src/commands/tokens.js.map +1 -1
  65. package/dist/src/commands/users.js +19 -10
  66. package/dist/src/commands/users.js.map +1 -1
  67. package/dist/src/commands/vars.js +2 -1
  68. package/dist/src/commands/vars.js.map +1 -1
  69. package/dist/src/commands/waitlist.js +2 -1
  70. package/dist/src/commands/waitlist.js.map +1 -1
  71. package/dist/src/commands/webhooks.js +17 -10
  72. package/dist/src/commands/webhooks.js.map +1 -1
  73. package/dist/src/commands/workflows.js +36 -18
  74. package/dist/src/commands/workflows.js.map +1 -1
  75. package/dist/src/lib/api-client.d.ts +176 -8
  76. package/dist/src/lib/api-client.js +205 -68
  77. package/dist/src/lib/api-client.js.map +1 -1
  78. package/dist/src/lib/collection-export.d.ts +184 -0
  79. package/dist/src/lib/collection-export.js +252 -0
  80. package/dist/src/lib/collection-export.js.map +1 -0
  81. package/dist/src/lib/config-object-descriptor.js +44 -8
  82. package/dist/src/lib/config-object-descriptor.js.map +1 -1
  83. package/dist/src/lib/config-payload.d.ts +8 -1
  84. package/dist/src/lib/config-payload.js +49 -4
  85. package/dist/src/lib/config-payload.js.map +1 -1
  86. package/dist/src/lib/config-surface.d.ts +2 -1
  87. package/dist/src/lib/config-surface.js +54 -3
  88. package/dist/src/lib/config-surface.js.map +1 -1
  89. package/dist/src/lib/deprecation.d.ts +22 -0
  90. package/dist/src/lib/deprecation.js +43 -0
  91. package/dist/src/lib/deprecation.js.map +1 -0
  92. package/dist/src/lib/function-db-types.d.ts +14 -3
  93. package/dist/src/lib/function-db-types.js +55 -11
  94. package/dist/src/lib/function-db-types.js.map +1 -1
  95. package/dist/src/lib/function-trigger-listing.d.ts +27 -0
  96. package/dist/src/lib/function-trigger-listing.js +70 -0
  97. package/dist/src/lib/function-trigger-listing.js.map +1 -0
  98. package/dist/src/lib/generated-config-surfaces.d.ts +715 -4
  99. package/dist/src/lib/generated-config-surfaces.js +2424 -226
  100. package/dist/src/lib/generated-config-surfaces.js.map +1 -1
  101. package/dist/src/lib/generated-sdk-types.d.ts +1 -1
  102. package/dist/src/lib/generated-sdk-types.js +1 -1
  103. package/dist/src/lib/generated-sdk-types.js.map +1 -1
  104. package/dist/src/lib/list-options.d.ts +68 -0
  105. package/dist/src/lib/list-options.js +89 -0
  106. package/dist/src/lib/list-options.js.map +1 -0
  107. package/dist/src/lib/log-inspection.d.ts +34 -1
  108. package/dist/src/lib/log-inspection.js +28 -0
  109. package/dist/src/lib/log-inspection.js.map +1 -1
  110. package/dist/src/lib/paginate.d.ts +15 -0
  111. package/dist/src/lib/paginate.js +17 -0
  112. package/dist/src/lib/paginate.js.map +1 -1
  113. package/dist/src/lib/prompt-cost-format.d.ts +11 -0
  114. package/dist/src/lib/prompt-cost-format.js +41 -0
  115. package/dist/src/lib/prompt-cost-format.js.map +1 -0
  116. package/dist/src/lib/prompt-schema-codegen.d.ts +53 -0
  117. package/dist/src/lib/prompt-schema-codegen.js +253 -3
  118. package/dist/src/lib/prompt-schema-codegen.js.map +1 -1
  119. package/dist/src/lib/swift-codegen/agentGenerator.d.ts +42 -0
  120. package/dist/src/lib/swift-codegen/agentGenerator.js +118 -0
  121. package/dist/src/lib/swift-codegen/agentGenerator.js.map +1 -0
  122. package/dist/src/lib/swift-codegen/banners.d.ts +6 -0
  123. package/dist/src/lib/swift-codegen/banners.js +6 -0
  124. package/dist/src/lib/swift-codegen/banners.js.map +1 -1
  125. package/dist/src/lib/swift-codegen/dbGenerator.js +11 -3
  126. package/dist/src/lib/swift-codegen/dbGenerator.js.map +1 -1
  127. package/dist/src/lib/swift-codegen/functionGenerator.d.ts +7 -0
  128. package/dist/src/lib/swift-codegen/functionGenerator.js +41 -3
  129. package/dist/src/lib/swift-codegen/functionGenerator.js.map +1 -1
  130. package/dist/src/lib/swift-codegen/generator.js +8 -2
  131. package/dist/src/lib/swift-codegen/generator.js.map +1 -1
  132. package/package.json +2 -2
@@ -32,9 +32,20 @@ import { buildWorkflowPayloadFromToml, parseWorkflowExpressionsToml, } from "../
32
32
  // payload builder so the diff normalizer and the wire cannot disagree.
33
33
  import { WORKFLOW_MODEL_DEFAULTS } from "../lib/workflow-defaults.js";
34
34
  // #2644 — the one definition per configuration object, vendored from the server.
35
- import { BLOB_BUCKET_TABLE, COLLECTION_TYPE_CONFIG_TABLE, CRON_TRIGGER_TABLE, DATABASE_TYPE_TABLE, EMAIL_TEMPLATE_TABLE, GROUP_TYPE_CONFIG_TABLE, INTEGRATION_TABLE, METADATA_CATEGORY_CONFIG_TABLE, PROMPT_CONFIG_TABLE, PROMPT_TABLE, RULE_SET_TABLE, SERVER_FUNCTION_TABLE, TEST_CASE_SURFACE, TEST_CASE_TABLE, WEBHOOK_TABLE, WORKFLOW_TABLE, configDeclaredTypeErrors, fieldServerDefault, findMisshapenTables, findUnknownDocumentKeys, findUnknownServerKeys, findUnknownTomlKeys, misshapenTableMessage, retiredConfigKey, spellsDecimalNumber, unrecognizedPullKeysMessage, unrecognizedPushKeysMessage, unrecognizedPushTablesMessage, warnUnrecognizedServerKeys, } from "../lib/config-surface.js";
35
+ import { BLOB_BUCKET_TABLE, COLLECTION_TYPE_CONFIG_TABLE, CRON_TRIGGER_TABLE, DATABASE_TYPE_TABLE, EMAIL_TEMPLATE_TABLE, GROUP_TYPE_CONFIG_TABLE, INTEGRATION_TABLE, METADATA_CATEGORY_CONFIG_TABLE, PROMPT_CONFIG_TABLE, PROMPT_TABLE, RULE_SET_TABLE, SERVER_FUNCTION_TABLE, TEST_CASE_SURFACE, TEST_CASE_TABLE, WEBHOOK_TABLE, WORKFLOW_TABLE, configDeclaredTypeErrors, fieldServerDefault, findMisshapenTables, findUnknownDocumentKeys, findUnknownGroupedTomlKeys, findUnknownServerKeys, findUnknownTomlKeys, misshapenTableMessage, retiredConfigKey, spellsDecimalNumber, unrecognizedPullKeysMessage, unrecognizedPushKeysMessage, unrecognizedPushTablesMessage, warnUnrecognizedServerKeys, } from "../lib/config-surface.js";
36
36
  import { buildPayloadFromToml, projectEntityToPayload, projectRecordToToml, tomlOwned, } from "../lib/config-payload.js";
37
- import { CONFIG_SURFACES, isEmptyForEmit, } from "../lib/generated-config-surfaces.js";
37
+ import { CONFIG_SURFACES, isEmptyForEmit, tomlGroupsOf, } from "../lib/generated-config-surfaces.js";
38
+ // #3626 — the prompt KIND rule, vendored with the definitions so the CLI's
39
+ // preflight refuses exactly what the admin routes refuse.
40
+ import { hoistDeprecatedChatKeys, promptKindOf, resolvePromptKind, } from "../lib/generated-config-surfaces.js";
41
+ // #3798 — the `[prompt.agent]` declaration rule, vendored the same way.
42
+ import { agentDeclarationFunctionKeys, agentTestCaseRefusal, resolveAgentDeclaration, } from "../lib/generated-config-surfaces.js";
43
+ // #3799 — the meaning-preserving schema translation, vendored the same way, so
44
+ // the preflight refuses exactly the schemas the admin routes refuse.
45
+ import { agentSchemaTranslationRefusals } from "../lib/generated-config-surfaces.js";
46
+ // #3801 — the strict-output rule, vendored the same way, so the preflight
47
+ // refuses exactly the strict configs the admin routes refuse.
48
+ import { resolvePromptStrictOutput } from "../lib/generated-config-surfaces.js";
38
49
  // #3179 — the function's two halves: the header payloads and the envelope
39
50
  // `config push` sends, and the bytes `config pull` writes back.
40
51
  import { applyFunctionPull, buildFunctionConfigPush, createDocumentSchemaDropWarner, documentSchemaRetentionFailure, buildFunctionCreatePayload, buildFunctionUpdatePayload, functionDiffEntity, functionTomlIgnoredKeyWarnings, functionTomlPreflightErrors, planDocumentSchemaPull, planFunctionPull, serializeFunction, } from "../lib/function-sync.js";
@@ -713,6 +724,20 @@ export function validateVarsFile(parsedVars, options = {}) {
713
724
  * edit — reported as a conflict instead. `force` skips the conflict guard,
714
725
  * matching `config push --force` for every other entity.
715
726
  *
727
+ * A var only the SERVER moved is the other half of the same comparison, and it
728
+ * is reported rather than skipped (issue #3714). Its local value still equals
729
+ * the baseline, so there is nothing to push and no conflict — but the skip that
730
+ * follows from "local is unchanged" used to be taken before the snapshot was
731
+ * consulted at all, so the push said nothing about a var edited in the Admin
732
+ * Console and counted it among the skipped-unchanged. The `drifted[]` keys are
733
+ * what every other synced type reaches through `classifyPushChange` →
734
+ * `server-drifted`: the caller prints `DRIFT var: <key>` under "Server drift —
735
+ * not pushed", writes nothing, and leaves the exit code alone. A baseline key
736
+ * the snapshot no longer holds at all is the same one-sided move (the server
737
+ * deleted the row; the local file stands still) and is reported the same way.
738
+ * `--force` is the resolution that keeps the local value, `config pull` the one
739
+ * that takes the server's.
740
+ *
716
741
  * Pure and side-effect-free (the caller owns the API calls and sync-state
717
742
  * updates) so the guard is unit-testable without a live server. Assumes
718
743
  * `parsedVars` has already passed `validateVarsFile` (values are strings). The
@@ -726,6 +751,7 @@ export function planVarsPush(parsedVars, baseline, remoteVars, options = {}) {
726
751
  const remoteByKey = new Map(remoteVars.map((r) => [r.key, r]));
727
752
  const upserts = [];
728
753
  const conflicts = [];
754
+ const drifted = [];
729
755
  const deletions = [];
730
756
  let skippedCount = 0;
731
757
  const localKeys = new Set();
@@ -733,9 +759,32 @@ export function planVarsPush(parsedVars, baseline, remoteVars, options = {}) {
733
759
  localKeys.add(key);
734
760
  const valueHash = hashVarValue(value);
735
761
  const existing = baseline?.[key];
736
- // Unchanged since last sync — skip (unless forced), mirroring the
737
- // content-hash skip the other file-backed entities use.
762
+ // Unchanged since last sync — nothing to push (unless forced), mirroring
763
+ // the content-hash skip the other file-backed entities use. But "the local
764
+ // file did not move" is only half the comparison: ask the snapshot whether
765
+ // the SERVER moved before calling the pair unchanged (issue #3714). One
766
+ // side having moved is drift, which is reported and not written; only a
767
+ // pair that still agrees is a skipped-unchanged file.
738
768
  if (!options.force && existing && existing.contentHash === valueHash) {
769
+ const remote = remoteByKey.get(key);
770
+ if (!remote) {
771
+ // The row is gone from an authoritative snapshot (the caller fails the
772
+ // push closed when the fetch fails, and the `--force` fallback that
773
+ // leaves it empty never reaches here): the server deleted what we last
774
+ // synced while the file stood still. `--force` recreates it from the
775
+ // local value; `config pull` drops the line.
776
+ drifted.push({ key, serverModifiedAt: "deleted" });
777
+ continue;
778
+ }
779
+ if (typeof remote.value === "string" &&
780
+ hashVarValue(remote.value) !== existing.contentHash) {
781
+ drifted.push({ key, serverModifiedAt: remote.updatedAt || "unknown" });
782
+ continue;
783
+ }
784
+ // Either both sides still hold the last-synced value, or the snapshot
785
+ // carries no readable value for the key and nothing establishes a move.
786
+ // Nothing is written on this path either way, so the only question is
787
+ // what to report, and an unprovable drift is not one to claim.
739
788
  skippedCount++;
740
789
  continue;
741
790
  }
@@ -823,7 +872,7 @@ export function planVarsPush(parsedVars, baseline, remoteVars, options = {}) {
823
872
  }
824
873
  deletions.push(key);
825
874
  }
826
- return { upserts, deletions, conflicts, skippedCount };
875
+ return { upserts, deletions, conflicts, drifted, skippedCount };
827
876
  }
828
877
  /**
829
878
  * Compute the number of config vars the server would hold after a push plan
@@ -1627,22 +1676,20 @@ export function buildBlobBucketUpdatePayload(bucket) {
1627
1676
  */
1628
1677
  const PROMPT_CONFIG_DEFAULT_STATUS = fieldServerDefault(PROMPT_CONFIG_TABLE, "status");
1629
1678
  /**
1630
- * The status a freshly CREATED prompt config still owes the file, or null
1631
- * (#3201).
1679
+ * #3201's post-create status patch is RETIRED — #3799 (DSO-3799-005).
1632
1680
  *
1633
- * `status` is update-only — `POST /prompts` and `POST /prompts/:id/configs`
1634
- * both assign `active` whatever the body says — so an authored
1635
- * `status = "archived"` was silently dropped on every create path: a pulled
1636
- * tree pushed from a clean clone into a fresh environment brought every
1637
- * retired config back into service. Read through the push payload builder, so
1638
- * a file that omits the key asks for the default and needs no request.
1681
+ * `status` was update-only, so `POST /prompts` and `POST /prompts/:id/configs`
1682
+ * both assigned `active` whatever the body said, and an authored
1683
+ * `status = "archived"` needed a follow-up PATCH ordered after the activation of
1684
+ * the entry the file marks live. Both create paths honor the key now
1685
+ * (`writableOn: BOTH`, validated by one rule on all three paths), so the entry
1686
+ * lands retired on its own create: the same end state, two fewer calls per
1687
+ * retired config, and no window in which the server holds a status the file
1688
+ * never asked for. That window is what made a pulled tree unpushable into a
1689
+ * fresh environment once an agent's schemas are checked against each
1690
+ * non-archived config's provider — the check fired on the transient active
1691
+ * state.
1639
1692
  */
1640
- export function createdConfigStatusPatch(tomlConfig) {
1641
- const { status } = buildPromptConfigPayload(tomlConfig, { mode: "update" });
1642
- return typeof status === "string" && status !== PROMPT_CONFIG_DEFAULT_STATUS
1643
- ? { status }
1644
- : null;
1645
- }
1646
1693
  /**
1647
1694
  * Which `[[configs]]` entry a prompt file marks as live (issue #2645).
1648
1695
  *
@@ -1750,6 +1797,11 @@ export function serializePrompt(prompt, logger) {
1750
1797
  ...projectRecordToToml(PROMPT_TABLE, prompt, {
1751
1798
  inputSchema: jsonField(promptSubject),
1752
1799
  outputSchema: jsonField(promptSubject),
1800
+ // #3798 — the agent declaration goes out as `[prompt.agent]` tables
1801
+ // (JSON-string fallback for a `null` TOML cannot spell), exactly as
1802
+ // stored: the server keeps it as authored, so what pull writes is
1803
+ // what the author pushed.
1804
+ agent: jsonField(promptSubject),
1753
1805
  }),
1754
1806
  },
1755
1807
  configs: (prompt.configs || []).map((config) => ({
@@ -1771,7 +1823,17 @@ export function serializePrompt(prompt, logger) {
1771
1823
  topP: (record) => (record.topP != null ? Number(record.topP) : undefined),
1772
1824
  outputSchema: jsonField(`Prompt '${prompt?.promptKey}' config '${config?.configName}'`),
1773
1825
  providerConfig: jsonField(`Prompt '${prompt?.promptKey}' config '${config?.configName}'`),
1774
- }),
1826
+ // #3626, CR3626-002 — the decisions declaration is a `json` field and
1827
+ // goes out the same way its siblings do. Written straight through, a
1828
+ // stored question carrying a `null` anywhere lost that member on pull
1829
+ // (smol-toml has no null), and a `null` inside a LIST threw, taking
1830
+ // `config pull` and `config diff` down with it. The JSON-string
1831
+ // fallback keeps the declaration whole either way.
1832
+ questions: jsonField(`Prompt '${prompt?.promptKey}' config '${config?.configName}'`),
1833
+ },
1834
+ // #3798 — the model settings chat and agent share are written under the
1835
+ // block the prompt's kind names: `[configs.agent]` for an agent.
1836
+ { tomlGroup: promptKindOf(prompt) }),
1775
1837
  // #2645 — the live config has to be identifiable in the repo. Emitted
1776
1838
  // only on the active entry (`undefined` elsewhere so the key is omitted),
1777
1839
  // which keeps the marker unambiguous by construction.
@@ -1843,11 +1905,43 @@ export function buildPromptPushPayload(key, tomlData, { mode = "update" } = {})
1843
1905
  // dropped and leaving a stale rule live. On create it is omitted so
1844
1906
  // the push-adopt path (#1006) can still reach the server's 409.
1845
1907
  accessRule: (value) => (create ? value : (value ?? null)),
1908
+ // #3798 — the agent declaration, as authored: the server stores it
1909
+ // unchanged, so the value sent is the value pull writes back. On
1910
+ // update a deleted block CLEARS it — for an agent only: a chat or
1911
+ // decisions file carries no block to delete, and omitting the key
1912
+ // keeps its body what it was before this field existed.
1913
+ agent: (value) => create || value !== undefined
1914
+ ? value
1915
+ : promptKindOf(prompt) === "agent"
1916
+ ? null
1917
+ : undefined,
1918
+ // #3626, CR3626-004 — the kind NORMALIZED, exactly as the resolver
1919
+ // that validates it reads it. `kind = " chat "` and `kind = ""` both
1920
+ // mean `chat` to `resolvePromptKind`, so the server stores `chat` and
1921
+ // the comparison — which projects `[prompt]` in create mode precisely
1922
+ // so a changed kind is visible (SO3626-008) — would otherwise read the
1923
+ // authored spelling against the stored one and call a freshly created
1924
+ // prompt an attempted kind change, refused as immutable on every later
1925
+ // push including `--force`. An UNKNOWN kind is passed through as
1926
+ // written: it is a refusal (preflight, then the create handler), and it
1927
+ // has to name what the file says.
1928
+ kind: (value) => {
1929
+ if (value === undefined || value === null)
1930
+ return "chat";
1931
+ if (typeof value !== "string")
1932
+ return value;
1933
+ const text = value.trim();
1934
+ return text === "" ? "chat" : text;
1935
+ },
1846
1936
  },
1847
1937
  }),
1848
1938
  };
1849
1939
  if (create)
1850
1940
  payload.promptKey = key;
1941
+ // #3798 — a prompt that declares no agent block sends no `agent` key at all,
1942
+ // so a chat or decisions body is byte for byte what it was.
1943
+ if (payload.agent === undefined)
1944
+ delete payload.agent;
1851
1945
  return payload;
1852
1946
  }
1853
1947
  /**
@@ -1877,11 +1971,25 @@ export function buildPromptCreatePayload(key, tomlData) {
1877
1971
  for (const owned of ["configName", ...SEEDED_CONFIG_DEFERRED]) {
1878
1972
  delete seed[owned];
1879
1973
  }
1974
+ const prompt = buildPromptPushPayload(key, tomlData, { mode: "create" });
1975
+ // #3626, SO3626-001 — the placeholder is a CHAT fallback. A decisions prompt
1976
+ // has no template at all (its input is a `state` value plus its questions),
1977
+ // and injecting one would store a chat key the block rule then refuses on
1978
+ // every later update. #3798 — nor has an agent: the model sees each message
1979
+ // as sent.
1980
+ if (promptKindOf(prompt) !== "chat") {
1981
+ const body = { ...prompt, ...seed };
1982
+ for (const field of Object.keys(body)) {
1983
+ if (body[field] === undefined)
1984
+ delete body[field];
1985
+ }
1986
+ return body;
1987
+ }
1880
1988
  return {
1881
- ...buildPromptPushPayload(key, tomlData, { mode: "create" }),
1989
+ ...prompt,
1882
1990
  ...seed,
1883
- // The server requires a template; keep the historical placeholder so a
1884
- // prompt authored without one still creates.
1991
+ // The server requires a template for a chat config; keep the historical
1992
+ // placeholder so a prompt authored without one still creates.
1885
1993
  userPromptTemplate: seed.userPromptTemplate || "{{ input }}",
1886
1994
  };
1887
1995
  }
@@ -1913,21 +2021,25 @@ const SEEDED_CONFIG_DEFERRED = ["outputSchema", "description"];
1913
2021
  * response rather than assumed, so a handler that one day honors the name
1914
2022
  * produces no needless PATCH.
1915
2023
  *
1916
- * #3201 — the entry's `status` is deferred the OTHER way and is deliberately
1917
- * not here. The create points the prompt's `activeConfigId` at this seeded
1918
- * config, so retiring it in this early patch would archive the config the
1919
- * prompt is serving from and leave it there until the marked entry is created
1920
- * and activated — a window a failed create or activation freezes. It is
1921
- * applied after activation instead (`createdConfigStatusPatch`).
2024
+ * #3201 — the entry's `status` was deferred the OTHER way, to a patch after the
2025
+ * activation, because the create pointed the prompt's `activeConfigId` at a
2026
+ * config it had forced live. #3799 (DSO-3799-005) — the create carries the
2027
+ * entry's `status` itself now, so there is no deferral either way and this patch
2028
+ * is the two fields `POST /prompts` cannot express, nothing more.
1922
2029
  */
1923
2030
  export function seededOnlyPromptConfigFields(firstConfig, seededConfigName = "default") {
1924
2031
  const full = buildPromptConfigPayload(firstConfig || {}, { mode: "update" });
1925
2032
  const patch = {};
1926
2033
  for (const field of SEEDED_CONFIG_DEFERRED) {
1927
2034
  const value = full[field];
1928
- // A value the entry does not carry is left alone: the seeded config has
1929
- // none either, so there is nothing to clear.
1930
- if (value === undefined || value === null)
2035
+ // #3626 — an omitted value CLEARS. The create handler does not merely skip
2036
+ // `description`, it writes the hard-coded "Default configuration", so
2037
+ // leaving it alone left every newly-pushed prompt reporting `Modified`
2038
+ // forever against a description its file never asked for: push's own
2039
+ // "the file is the whole truth" rule (#1567), broken by the one field the
2040
+ // create body cannot carry. `outputSchema` is unaffected — create never
2041
+ // sets the seeded config's, so the null is a no-op there.
2042
+ if (value === undefined)
1931
2043
  continue;
1932
2044
  patch[field] = value;
1933
2045
  }
@@ -1958,10 +2070,24 @@ export function buildPromptConfigPayload(tomlConfig, { mode = "update" } = {}) {
1958
2070
  * differ from the one the server has always received.
1959
2071
  */
1960
2072
  const tomlOwned = (value) => (create ? value : (value ?? null));
1961
- return buildPayloadFromToml(PROMPT_CONFIG_TABLE, tomlConfig, {
2073
+ // #3626 §4 — the nine chat keys moved under `[configs.chat]`, and the flat
2074
+ // spelling is accepted as DEPRECATED. Hoisting here rather than at each call
2075
+ // site means push, `config diff` and the create-seed builder all read a file
2076
+ // the same way, so an unmigrated file and its pulled rewrite compare Synced.
2077
+ // A key set BOTH ways is refused in preflight
2078
+ // (`promptDeprecatedChatKeyErrors`); the hoist leaves the grouped value
2079
+ // standing so nothing here has to guess.
2080
+ const entry = hoistDeprecatedChatKeys(tomlConfig).entry;
2081
+ return buildPayloadFromToml(PROMPT_CONFIG_TABLE, entry, {
1962
2082
  mode,
1963
2083
  values: {
1964
2084
  provider: (value) => (create ? value || "openrouter" : value),
2085
+ // #3799 (DSO-3799-005) — carried on CREATE when the entry names one, and
2086
+ // omitted otherwise, so the create body for a file that says nothing
2087
+ // about status is what the server has always received (principle 5). On
2088
+ // update it still sends the declared default for an absent key, which is
2089
+ // what lets a deleted line converge (#2880 DSO-002).
2090
+ status: (value) => create ? value : (value ?? PROMPT_CONFIG_DEFAULT_STATUS),
1965
2091
  model: (value) => create ? value || "google/gemini-2.0-flash-001" : value,
1966
2092
  description: tomlOwned,
1967
2093
  systemPrompt: tomlOwned,
@@ -1978,6 +2104,13 @@ export function buildPromptConfigPayload(tomlConfig, { mode = "update" } = {}) {
1978
2104
  // the merged config refused as "both set".
1979
2105
  reasoningEffort: tomlOwned,
1980
2106
  reasoningBudget: tomlOwned,
2107
+ // #3801 — deleting `strictOutput = true` has to turn strict output off
2108
+ // server-side, or the file stops describing the request that is sent.
2109
+ strictOutput: tomlOwned,
2110
+ // #3626, SO3626-002 — the decisions declaration is TOML-owned on the
2111
+ // same terms: deleting `[configs.decisions]` has to clear `questions`
2112
+ // server-side, or the file stops describing what the model is asked.
2113
+ questions: tomlOwned,
1981
2114
  },
1982
2115
  });
1983
2116
  }
@@ -2053,11 +2186,19 @@ export function configUnknownKeyError(filePath, tomlData, table) {
2053
2186
  : []
2054
2187
  : [at];
2055
2188
  const unknown = new Set();
2189
+ // #3626 — a key inside a declared `[configs.<group>]` block that no field
2190
+ // declares under it, and a group value that is not a table at all. Reported
2191
+ // with the group in the path (`configs.chat.nope`) so the author is told
2192
+ // where the CLI looked.
2193
+ const groupedUnknown = new Set();
2056
2194
  for (const entry of entries) {
2057
2195
  for (const key of findUnknownTomlKeys(entry, table))
2058
2196
  unknown.add(key);
2197
+ for (const key of findUnknownGroupedTomlKeys(entry, table)) {
2198
+ groupedUnknown.add(key);
2199
+ }
2059
2200
  }
2060
- if (unknown.size === 0)
2201
+ if (unknown.size === 0 && groupedUnknown.size === 0)
2061
2202
  return null;
2062
2203
  // #2645/#2803 — a key this CLI removed on purpose gets the guidance stated
2063
2204
  // once beside the definitions (`src/config-surface/retired-keys.ts`), not the
@@ -2074,8 +2215,33 @@ export function configUnknownKeyError(filePath, tomlData, table) {
2074
2215
  for (const key of retiredHere) {
2075
2216
  messages.push(`${filePath}: ${prefix}.${key} — ${retiredConfigKey(prefix, key).toml}`);
2076
2217
  }
2077
- if (trulyUnknown.length > 0) {
2078
- messages.push(unrecognizedPushKeysMessage(filePath, table.tomlPath, trulyUnknown));
2218
+ // #3626, SO3626-013 — a key the definition DOES declare, written at the
2219
+ // table root when it is authored under a group. Before grouping,
2220
+ // `acceptedTomlKeys` took every field key at the root, so a flat `questions`
2221
+ // passed this check and was then dropped in silence by the payload builder.
2222
+ // It is an unknown key now, and the message says where it belongs rather
2223
+ // than sending the author to the generic "check the spelling" hint.
2224
+ const misplaced = trulyUnknown
2225
+ .map((key) => ({
2226
+ key,
2227
+ groups: tomlGroupsOf(table.fields.find((f) => f.tomlKey === key && f.tomlGroup) ??
2228
+ {}),
2229
+ }))
2230
+ .filter((entry) => entry.groups.length > 0);
2231
+ for (const { key, groups } of misplaced) {
2232
+ // #3798 — a key two blocks share names both; the prompt's kind picks one.
2233
+ messages.push(`${filePath}: ${prefix}[0].${key} is not a [[${prefix}]] key; ` +
2234
+ `write it under ${groups.map((g) => `[${prefix}.${g}]`).join(" or ")}`);
2235
+ }
2236
+ const misplacedKeys = new Set(misplaced.map((m) => m.key));
2237
+ const stillUnknown = trulyUnknown.filter((k) => !misplacedKeys.has(k));
2238
+ if (stillUnknown.length > 0) {
2239
+ messages.push(unrecognizedPushKeysMessage(filePath, table.tomlPath, stillUnknown));
2240
+ }
2241
+ if (groupedUnknown.size > 0) {
2242
+ messages.push(unrecognizedPushKeysMessage(filePath, table.tomlPath, [
2243
+ ...groupedUnknown,
2244
+ ].sort()));
2079
2245
  }
2080
2246
  return messages.join("\n");
2081
2247
  }
@@ -2507,6 +2673,59 @@ export async function runConfigPushPreflight(input) {
2507
2673
  preflightValidationErrors.push(` ${message}`);
2508
2674
  }
2509
2675
  }
2676
+ // #3626 §4 — one advisory line per prompt file still written in the flat
2677
+ // chat spelling, beside the `celContextAccess` notice above. The push
2678
+ // continues and the keys are applied; `config pull` rewrites the file, so a
2679
+ // single pull-then-push clears the notice. Printed even under `--dry-run`,
2680
+ // which never reaches the apply — the notice is about the FILE.
2681
+ const preflightPromptsDir = join(configDir, "prompts");
2682
+ // #3798 — the functions an agent's references are checked against, read
2683
+ // once and only when a selected prompt is an agent that names one.
2684
+ let agentFunctions = null;
2685
+ if (existsSync(preflightPromptsDir)) {
2686
+ for (const file of selectFiles("prompt", preflightPromptsDir, readdirSync(preflightPromptsDir).filter((f) => f.endsWith(".toml")))) {
2687
+ const filePath = join(preflightPromptsDir, file);
2688
+ let tomlData;
2689
+ try {
2690
+ tomlData = parseTomlFile(filePath);
2691
+ }
2692
+ catch {
2693
+ // A file that does not parse is reported by the collector above.
2694
+ continue;
2695
+ }
2696
+ const notice = promptFlatChatKeyWarning(filePath, tomlData);
2697
+ if (notice)
2698
+ warn(` ${notice}`);
2699
+ // #3798 — an agent's tool, turn-context and history functions must
2700
+ // exist, and a tool's must declare both schemas, before anything is
2701
+ // applied. Bounded by `--only` like the rest of this loop.
2702
+ if (promptKindOf(tomlData?.prompt) === "agent" &&
2703
+ agentDeclarationFunctionKeys(tomlData?.prompt?.agent).length > 0) {
2704
+ if (!agentFunctions) {
2705
+ let live = null;
2706
+ try {
2707
+ live = (await client.listFunctions(resolvedAppId)).items;
2708
+ }
2709
+ catch {
2710
+ live = null;
2711
+ }
2712
+ agentFunctions = agentFunctionFactsForPush({
2713
+ configDir,
2714
+ pushSelection,
2715
+ live,
2716
+ });
2717
+ }
2718
+ for (const message of promptAgentFunctionErrors(filePath, tomlData, agentFunctions)) {
2719
+ preflightValidationErrors.push(` ${message}`);
2720
+ }
2721
+ }
2722
+ }
2723
+ }
2724
+ // #3798 — a test case on an agent is refused by the admin routes; say so
2725
+ // here, before any other file is applied.
2726
+ for (const message of promptAgentSidecarErrors(configDir)) {
2727
+ preflightValidationErrors.push(` ${message}`);
2728
+ }
2510
2729
  // The `<key>.tests/*.toml` sidecars, which sit beside the block they
2511
2730
  // test rather than in a type directory of their own. Same posture,
2512
2731
  // reached through the registry's `test-case` surface — and through the
@@ -2546,6 +2765,429 @@ export async function runConfigPushPreflight(input) {
2546
2765
  * whose spelling is not the declared type. A file that does not parse is left
2547
2766
  * to the per-type loop that reads it, which names the parse error itself.
2548
2767
  */
2768
+ /**
2769
+ * The blocks one `[[configs]]` entry carries that its prompt's kind does not
2770
+ * name — #3798. An agent's entry may carry only `[configs.agent]`; a chat or
2771
+ * decisions entry may not carry it. `movedFlat` are the deprecated flat chat
2772
+ * keys the hoist moved under `chat`, named as the author wrote them.
2773
+ *
2774
+ * Only the blocks the other arms of `resolvePromptKind` cannot see are checked
2775
+ * here: a decisions block on a chat entry, and chat keys on a decisions entry,
2776
+ * stay the resolver's refusals with their #3626 wording.
2777
+ */
2778
+ function promptEntryBlockErrors(kind, entry, movedFlat) {
2779
+ const has = (block) => entry != null && typeof entry === "object" && entry[block] !== undefined;
2780
+ const errors = [];
2781
+ if (kind === "agent") {
2782
+ if (movedFlat.length > 0) {
2783
+ errors.push(`sets ${movedFlat.join(", ")} flat — the deprecated [configs.chat] ` +
2784
+ 'spelling — but prompt kind is "agent", so it may carry only a ' +
2785
+ "[configs.agent] block; write them under [configs.agent]");
2786
+ }
2787
+ for (const block of ["chat", "decisions"]) {
2788
+ if (!has(block))
2789
+ continue;
2790
+ errors.push(`carries a [configs.${block}] block, but prompt kind is "agent", so ` +
2791
+ "it may carry only a [configs.agent] block (systemPrompt, " +
2792
+ "temperature, topP, maxTokens, reasoningEffort, reasoningBudget)");
2793
+ }
2794
+ return errors;
2795
+ }
2796
+ if (has("agent")) {
2797
+ errors.push(`carries a [configs.agent] block, but prompt kind is "${kind}", so it ` +
2798
+ `may carry only a [configs.${kind}] block. An agent is its own ` +
2799
+ 'prompt: create it under a new key with kind = "agent"');
2800
+ }
2801
+ return errors;
2802
+ }
2803
+ /**
2804
+ * A prompt file's KIND errors — #3626, decidable from the file alone.
2805
+ *
2806
+ * Three refusals, all of them the same rule seen from different angles: a key
2807
+ * set both flat and under `[configs.chat]` (the hoist will not guess), a
2808
+ * `[[configs]]` entry carrying the block of the OTHER kind, and a malformed
2809
+ * decisions declaration. The last two come from `resolvePromptKind`, the same
2810
+ * vendored function the admin routes validate with, so the CLI's refusal and
2811
+ * the server's cannot disagree — and this one lands in the preflight, before
2812
+ * the first mutating call.
2813
+ */
2814
+ /**
2815
+ * The `[[configs]]` entries of a prompt file as the agent rules read them —
2816
+ * #3799: which provider each named configuration runs on, and whether the file
2817
+ * retires it.
2818
+ *
2819
+ * An archived entry is skipped by the translation rule (a config the server does
2820
+ * not run cannot make the declaration untranslatable), which is what lets a
2821
+ * pulled tree keep a retired config on a provider the current schemas could not
2822
+ * reach. `status` is read through the same default the surface declares, so an
2823
+ * entry that omits the key is live.
2824
+ */
2825
+ function promptFileConfigFacts(entries) {
2826
+ return (entries || []).map((entry, index) => ({
2827
+ configName: String(entry?.name ?? `configs[${index}]`),
2828
+ provider: String(entry?.provider ?? ""),
2829
+ status: String(entry?.status ?? PROMPT_CONFIG_DEFAULT_STATUS),
2830
+ }));
2831
+ }
2832
+ export function promptKindFileErrors(filePath, tomlData) {
2833
+ const entries = Array.isArray(tomlData?.configs) ? tomlData.configs : [];
2834
+ const errors = [];
2835
+ const fileKind = promptKindOf(tomlData?.prompt);
2836
+ // #3798 — the `[prompt.agent]` declaration's file-decidable half: its shape,
2837
+ // and `[prompt].outputSchema` on an agent. The function half needs app state
2838
+ // and runs in the push preflight (`promptAgentFunctionErrors`).
2839
+ const declaration = resolveAgentDeclaration({
2840
+ kind: tomlData?.prompt?.kind,
2841
+ agent: tomlData?.prompt?.agent,
2842
+ outputSchema: tomlData?.prompt?.outputSchema,
2843
+ });
2844
+ if (declaration.ok === false) {
2845
+ for (const refusal of declaration.refusals) {
2846
+ errors.push(`${filePath}: ${refusal.message}`);
2847
+ }
2848
+ }
2849
+ else if (fileKind === "agent") {
2850
+ // #3799 — the schemas a CLIENT tool and an event declare are in the file,
2851
+ // so whether each provider the file configures can carry them without
2852
+ // losing meaning is file-decidable too: `config diff` reports the same row
2853
+ // as `config push`. A server tool's schemas are its FUNCTION's and need app
2854
+ // state, so they are checked in the push preflight
2855
+ // (`promptAgentFunctionErrors`). Only after the shape refusals above, so a
2856
+ // malformed declaration is not also reported as untranslatable.
2857
+ for (const refusal of agentSchemaTranslationRefusals({
2858
+ declaration: tomlData?.prompt?.agent,
2859
+ configs: promptFileConfigFacts(entries),
2860
+ })) {
2861
+ errors.push(`${filePath}: ${refusal.message}`);
2862
+ }
2863
+ }
2864
+ for (const [index, entry] of entries.entries()) {
2865
+ const hoisted = hoistDeprecatedChatKeys(entry);
2866
+ for (const key of hoisted.conflicts) {
2867
+ errors.push(`${filePath}: configs[${index}].${key} is set both flat and under ` +
2868
+ `[configs.chat]; keep the [configs.chat] spelling`);
2869
+ }
2870
+ // #3798 — the block rule for three kinds, stated per entry: an entry may
2871
+ // carry only the block its prompt's kind names. An agent's `[configs.agent]`
2872
+ // holds keys chat also holds, so a stray block would otherwise be read (or
2873
+ // ignored) in silence by the payload builder.
2874
+ const blockErrors = promptEntryBlockErrors(fileKind, entry, hoisted.moved).map((message) => `${filePath}: configs[${index}] ${message}`);
2875
+ if (blockErrors.length > 0) {
2876
+ errors.push(...blockErrors);
2877
+ continue;
2878
+ }
2879
+ if (fileKind === "agent") {
2880
+ const agent = hoisted.entry.agent ?? {};
2881
+ const resolution = resolvePromptKind({
2882
+ kind: "agent",
2883
+ provider: hoisted.entry.provider,
2884
+ model: hoisted.entry.model,
2885
+ config: {
2886
+ systemPrompt: agent.systemPrompt,
2887
+ temperature: agent.temperature,
2888
+ topP: agent.topP,
2889
+ maxTokens: agent.maxTokens,
2890
+ reasoningEffort: agent.reasoningEffort,
2891
+ reasoningBudget: agent.reasoningBudget,
2892
+ // #3801 — a chat key: named, so the refusal says which key an agent
2893
+ // does not take (§D1: an agent has no output schema).
2894
+ strictOutput: agent.strictOutput,
2895
+ },
2896
+ });
2897
+ if (resolution.ok === false) {
2898
+ errors.push(`${filePath}: configs[${index}] — ${resolution.error}`);
2899
+ }
2900
+ continue;
2901
+ }
2902
+ const chat = hoisted.entry.chat ?? {};
2903
+ const decisions = hoisted.entry.decisions ?? {};
2904
+ // #3626 — the FIRST entry of a chat prompt carries the create seed's
2905
+ // placeholder. `buildPromptCreatePayload` sends `{{ input }}` when the
2906
+ // file names no template, which is how a prompt authored without one has
2907
+ // always created; refusing it here would break a file that pushed before
2908
+ // the kind existed. An entry that really names none on the UPDATE path is
2909
+ // still refused, by the server, with this same message.
2910
+ //
2911
+ // CR3626-005 — the fallback is `||`, not `??`, because that is what
2912
+ // `buildPromptCreatePayload` applies (`seed.userPromptTemplate ||
2913
+ // "{{ input }}"`). `config create prompt` scaffolds an EMPTY
2914
+ // `userPromptTemplate`, so reading absence more narrowly than the builder
2915
+ // does refused the file this CLI had just written, for a value the create
2916
+ // would have replaced with the placeholder anyway.
2917
+ const seedsTemplate = index === 0 && fileKind === "chat";
2918
+ const userPromptTemplate = seedsTemplate
2919
+ ? chat.userPromptTemplate || "{{ input }}"
2920
+ : chat.userPromptTemplate;
2921
+ const resolution = resolvePromptKind({
2922
+ kind: tomlData?.prompt?.kind,
2923
+ provider: hoisted.entry.provider,
2924
+ model: hoisted.entry.model,
2925
+ config: {
2926
+ systemPrompt: chat.systemPrompt,
2927
+ userPromptTemplate,
2928
+ temperature: chat.temperature,
2929
+ topP: chat.topP,
2930
+ maxTokens: chat.maxTokens,
2931
+ outputFormat: chat.outputFormat,
2932
+ outputSchema: chat.outputSchema,
2933
+ reasoningEffort: chat.reasoningEffort,
2934
+ reasoningBudget: chat.reasoningBudget,
2935
+ strictOutput: chat.strictOutput,
2936
+ questions: decisions.questions,
2937
+ },
2938
+ });
2939
+ if (resolution.ok === false) {
2940
+ errors.push(`${filePath}: configs[${index}] — ${resolution.error}`);
2941
+ continue;
2942
+ }
2943
+ // #3801 — strict output, file-decidable: the entry's own keys, the file's
2944
+ // `[prompt].outputSchema` and the entry's status (an archived entry is not
2945
+ // held to the prompt schema, DSO-3801-002). The route runs the same rule
2946
+ // against what the server holds.
2947
+ if (resolution.kind === "chat") {
2948
+ const strict = resolvePromptStrictOutput({
2949
+ provider: hoisted.entry.provider,
2950
+ strictOutput: chat.strictOutput,
2951
+ outputFormat: chat.outputFormat,
2952
+ configOutputSchema: chat.outputSchema,
2953
+ promptOutputSchema: tomlData?.prompt?.outputSchema,
2954
+ status: hoisted.entry.status ?? PROMPT_CONFIG_DEFAULT_STATUS,
2955
+ });
2956
+ if (strict.ok === false) {
2957
+ errors.push(`${filePath}: configs[${index}] — ${strict.error} (${strict.code})`);
2958
+ }
2959
+ }
2960
+ }
2961
+ return errors;
2962
+ }
2963
+ /** A schema slot counts as declared when it holds anything but nothing. */
2964
+ function declaresSchema(value) {
2965
+ if (value === undefined || value === null)
2966
+ return false;
2967
+ return !(typeof value === "string" && value.trim() === "");
2968
+ }
2969
+ /**
2970
+ * The functions an agent's references are checked against at push — #3798,
2971
+ * DSO-3798-002.
2972
+ *
2973
+ * `config push` applies prompts, then (for agents) the server functions leg,
2974
+ * so a reference may be satisfied by a function that is live already or by one
2975
+ * this push creates. What the push BELIEVES is therefore the live listing
2976
+ * overlaid by the function files this push SELECTS (`--only`, every file when
2977
+ * unscoped): a selected file's schemas are what the server will hold after the
2978
+ * push, so it wins over the live row. An UNSELECTED file is not read at all —
2979
+ * its edits will not be applied, and a function only it declares will not
2980
+ * exist afterwards.
2981
+ *
2982
+ * `live` is `null` when the listing could not be fetched: the selected files
2983
+ * still count, and `liveListed` lets the refusal say why every other reference
2984
+ * could not be confirmed. A live row that is archived is a tombstone, not a
2985
+ * function; an inactive one is accepted (the turn engine re-checks
2986
+ * availability on every call).
2987
+ */
2988
+ export function agentFunctionFactsForPush(input) {
2989
+ const facts = {};
2990
+ for (const row of input.live ?? []) {
2991
+ const key = String(row?.functionKey ?? "");
2992
+ if (!key || row?.status === "archived")
2993
+ continue;
2994
+ facts[key] = {
2995
+ hasInputSchema: declaresSchema(row.inputSchema),
2996
+ hasOutputSchema: declaresSchema(row.outputSchema),
2997
+ // #3799 — the schemas themselves, as stored (a JSON string from the API,
2998
+ // an object from a tree file), so a server tool's two schemas can be
2999
+ // translated for each of the agent's providers.
3000
+ inputSchema: row.inputSchema,
3001
+ outputSchema: row.outputSchema,
3002
+ };
3003
+ }
3004
+ const functionsDir = join(input.configDir, "functions");
3005
+ if (existsSync(functionsDir)) {
3006
+ for (const file of filterFilesBySelection(input.pushSelection, "function", functionsDir, readdirSync(functionsDir).filter(isFunctionDeclarationFile))) {
3007
+ let table;
3008
+ try {
3009
+ table = parseTomlFile(join(functionsDir, file))?.function ?? {};
3010
+ }
3011
+ catch {
3012
+ // Reported by the function preflight with its own message.
3013
+ continue;
3014
+ }
3015
+ const key = table.key || basename(file, ".toml");
3016
+ facts[key] = {
3017
+ hasInputSchema: declaresSchema(table.inputSchema),
3018
+ hasOutputSchema: declaresSchema(table.outputSchema),
3019
+ // #3799 — a SELECTED file's schemas are what the server will hold after
3020
+ // this push, so they are what the translation is checked against.
3021
+ inputSchema: table.inputSchema,
3022
+ outputSchema: table.outputSchema,
3023
+ };
3024
+ }
3025
+ }
3026
+ return { facts, liveListed: input.live !== null };
3027
+ }
3028
+ /**
3029
+ * The function half of an agent's declaration — #3798: every tool, turn
3030
+ * context and history function that the functions this push believes
3031
+ * (`agentFunctionFactsForPush`) do not have, and every tool function lacking an
3032
+ * input or output schema. The same `resolveAgentDeclaration` the admin routes
3033
+ * run; only its function refusals are reported here, because the collector
3034
+ * (`promptKindFileErrors`) already reported the file-decidable ones.
3035
+ */
3036
+ export function promptAgentFunctionErrors(filePath, tomlData, known) {
3037
+ if (promptKindOf(tomlData?.prompt) !== "agent")
3038
+ return [];
3039
+ const result = resolveAgentDeclaration({
3040
+ kind: "agent",
3041
+ agent: tomlData?.prompt?.agent,
3042
+ functions: known.facts,
3043
+ });
3044
+ const errors = result.ok === false
3045
+ ? result.refusals
3046
+ .filter((refusal) => refusal.code === "AGENT_TOOL_FUNCTION_MISSING" ||
3047
+ refusal.code === "AGENT_TOOL_FUNCTION_SCHEMA_MISSING")
3048
+ .map((refusal) => refusal.code === "AGENT_TOOL_FUNCTION_MISSING" && !known.liveListed
3049
+ ? `${filePath}: ${refusal.message} (the app's live functions could ` +
3050
+ "not be listed, so only the function files this push applies were " +
3051
+ "checked)"
3052
+ : `${filePath}: ${refusal.message}`)
3053
+ : [];
3054
+ // #3799 — a SERVER tool's schemas are its function's, so translating them
3055
+ // needs the facts this push believes (the live listing overlaid by the
3056
+ // function files it selects, DSO-3798-002). The client-tool and event half is
3057
+ // file-decidable and reported by `promptKindFileErrors`, which `config diff`
3058
+ // runs too; passing the facts here means only the server-tool refusals are
3059
+ // new, because that collector already saw the rest.
3060
+ const entries = Array.isArray(tomlData?.configs) ? tomlData.configs : [];
3061
+ const configs = promptFileConfigFacts(entries);
3062
+ const fileDecidable = new Set(agentSchemaTranslationRefusals({
3063
+ declaration: tomlData?.prompt?.agent,
3064
+ configs,
3065
+ }).map((refusal) => refusal.message));
3066
+ for (const refusal of agentSchemaTranslationRefusals({
3067
+ declaration: tomlData?.prompt?.agent,
3068
+ functions: known.facts,
3069
+ configs,
3070
+ })) {
3071
+ if (fileDecidable.has(refusal.message))
3072
+ continue;
3073
+ errors.push(`${filePath}: ${refusal.message}`);
3074
+ }
3075
+ return errors;
3076
+ }
3077
+ /**
3078
+ * The order `config push` applies prompt files in — #3798. An agent names
3079
+ * server functions that must exist when it is created, and the push applies
3080
+ * prompts before functions, so agent files go AFTER the server-functions leg;
3081
+ * every other file keeps its place. A file that does not parse stays first, so
3082
+ * the leg reports it where it always has.
3083
+ */
3084
+ export function partitionPromptFilesForPush(promptsDir, files) {
3085
+ const beforeFunctions = [];
3086
+ const afterFunctions = [];
3087
+ for (const file of files) {
3088
+ let kind = "chat";
3089
+ try {
3090
+ kind = promptKindOf(parseTomlFile(join(promptsDir, file))?.prompt);
3091
+ }
3092
+ catch {
3093
+ beforeFunctions.push(file);
3094
+ continue;
3095
+ }
3096
+ (kind === "agent" ? afterFunctions : beforeFunctions).push(file);
3097
+ }
3098
+ return { beforeFunctions, afterFunctions };
3099
+ }
3100
+ /**
3101
+ * Every `prompts/<key>.tests/*.toml` sidecar whose prompt is an agent — #3798
3102
+ * (§D1: prompt test cases are refused for the kind in v1). The admin test-case
3103
+ * routes refuse the same case with `AGENT_TEST_CASE_NOT_SUPPORTED`; this says
3104
+ * so before anything is applied.
3105
+ */
3106
+ export function promptAgentSidecarErrors(configDir) {
3107
+ const promptsDir = join(configDir, "prompts");
3108
+ const errors = [];
3109
+ for (const filePath of testCaseTomlFiles(configDir)) {
3110
+ const parent = basename(join(filePath, ".."));
3111
+ if (!filePath.startsWith(promptsDir) || !parent.endsWith(".tests"))
3112
+ continue;
3113
+ const key = parent.slice(0, -".tests".length);
3114
+ const owner = join(promptsDir, `${key}.toml`);
3115
+ if (!existsSync(owner))
3116
+ continue;
3117
+ let tomlData;
3118
+ try {
3119
+ tomlData = parseTomlFile(owner);
3120
+ }
3121
+ catch {
3122
+ continue;
3123
+ }
3124
+ if (promptKindOf(tomlData?.prompt) !== "agent")
3125
+ continue;
3126
+ const promptKey = tomlData?.prompt?.key || key;
3127
+ errors.push(`${filePath.slice(configDir.length + 1)}: ` +
3128
+ agentTestCaseRefusal(promptKey, "subject").message);
3129
+ }
3130
+ return errors;
3131
+ }
3132
+ /**
3133
+ * The immutable-`kind` refusal for a prompt update the comparison gate did not
3134
+ * decide — #3626, CR3626-001.
3135
+ *
3136
+ * `kind` is create-only (D3626-008), and the gate refuses a change to it on
3137
+ * every path that compares the two sides. Two update paths do not compare: a
3138
+ * prompt whose DETAIL read failed falls back to the manifest byte-hash gate,
3139
+ * which `--force` writes straight through, and a prompt ADOPTED after a
3140
+ * create's 409 is re-issued as an update without a comparison at all. Both
3141
+ * would otherwise PATCH the file's schemas, access rule and metadata onto a
3142
+ * row of the other kind, and only then have its configs refused against the
3143
+ * kind the update cannot change.
3144
+ *
3145
+ * Returns the gate's own outcome shape, so `recordDeclined` prints the same
3146
+ * two values and the same remedy — create the prompt under a new key.
3147
+ *
3148
+ * `null` when the kinds agree and when the server's kind is simply not KNOWN:
3149
+ * a push that could not read live state at all has nothing to compare, and
3150
+ * that path's contract (`decideDegradedPush`, #2880) is already "decline
3151
+ * unless the operator forces it", stated for every field at once.
3152
+ */
3153
+ export function promptKindImmutableOutcome(storedKind, localDoc) {
3154
+ if (!storedKind)
3155
+ return null;
3156
+ const localKind = promptKindOf(localDoc?.prompt);
3157
+ if (localKind === storedKind)
3158
+ return null;
3159
+ return {
3160
+ action: "immutable",
3161
+ // The hashes are the gate's evidence for WHICH side moved, and this
3162
+ // refusal does not depend on that: the field cannot be written either way.
3163
+ localHash: "",
3164
+ remoteHash: "",
3165
+ fields: [{ field: "kind", local: localKind, server: storedKind }],
3166
+ immutableFields: ["kind"],
3167
+ };
3168
+ }
3169
+ /**
3170
+ * The one deprecation notice a prompt file using the FLAT chat spelling earns
3171
+ * — #3626 §4, beside the `celContextAccess` notice's precedent.
3172
+ *
3173
+ * Advisory: the push continues and the keys are applied. `null` when the file
3174
+ * is already written in the grouped spelling, so a migrated tree is silent.
3175
+ */
3176
+ export function promptFlatChatKeyWarning(filePath, tomlData) {
3177
+ const entries = Array.isArray(tomlData?.configs) ? tomlData.configs : [];
3178
+ const moved = new Set();
3179
+ for (const entry of entries) {
3180
+ for (const key of hoistDeprecatedChatKeys(entry).moved)
3181
+ moved.add(key);
3182
+ }
3183
+ if (moved.size === 0)
3184
+ return null;
3185
+ const named = [...moved].sort().join(", ");
3186
+ return (`${filePath}: ${named} ${moved.size === 1 ? "is" : "are"} written flat ` +
3187
+ "under [[configs]]; this spelling is deprecated — move them under " +
3188
+ "[configs.chat] (`config pull` rewrites the file). Rejecting the flat " +
3189
+ "spelling is tracked in #3642.");
3190
+ }
2549
3191
  export function collectConfigFileValidationErrors(configDir) {
2550
3192
  const found = [];
2551
3193
  for (const { dir, surface, tables } of unknownKeyPreflightTargets()) {
@@ -2581,6 +3223,12 @@ export function collectConfigFileValidationErrors(configDir) {
2581
3223
  for (const table of surface.tables) {
2582
3224
  messages.push(...configDeclaredTypeErrors(filePath, tomlData, table));
2583
3225
  }
3226
+ // #3626 — the prompt kind's own file-decidable refusals, run by the same
3227
+ // collector so `config push` and `config diff` cannot disagree about
3228
+ // which prompt files are pushable.
3229
+ if (surface.label === "prompt") {
3230
+ messages.push(...promptKindFileErrors(filePath, tomlData));
3231
+ }
2584
3232
  if (messages.length === 0)
2585
3233
  continue;
2586
3234
  found.push({
@@ -4055,7 +4703,17 @@ const CONFIG_DIFF_SPECS = {
4055
4703
  // (`[prompt].key`) is still read here, because it is what `displayName`
4056
4704
  // falls back to. Diff injects the resolved key into a file that omits it,
4057
4705
  // exactly as push derives it from the file name.
4058
- parse: (doc) => buildPromptPushPayload(doc?.prompt?.key ?? "", doc),
4706
+ //
4707
+ // #3626, SO3626-008 — projected in CREATE mode. `kind` is `writableOn:
4708
+ // ["create"]`, and `buildPayloadFromToml` drops a field not writable in the
4709
+ // mode, so an update-mode projection would leave a CHANGED kind out of the
4710
+ // compared surface entirely: `findImmutableFieldDiffs` would never see it,
4711
+ // diff would call the file Synced, and push would start applying the
4712
+ // prompt's other changes before the server refused a config against the
4713
+ // unchanged kind. The blob-bucket comparator projects in create mode for
4714
+ // exactly this reason (`ttlTier`, below). PATCH payloads still omit `kind`
4715
+ // — this is the comparison's projection, not push's.
4716
+ parse: (doc) => buildPromptPushPayload(doc?.prompt?.key ?? "", doc, { mode: "create" }),
4059
4717
  serialize: (record) => serializePrompt(record),
4060
4718
  // Read from the DOCUMENT, not the parsed entity: `[[configs]]` is a sibling
4061
4719
  // table of `[prompt]`, and the prompt's own push payload does not carry it
@@ -8908,6 +9566,9 @@ What a push guarantees (two stages):
8908
9566
  upserts: varPlan.upserts.filter((u) => wanted.has(u.key)),
8909
9567
  deletions: varPlan.deletions.filter((k) => wanted.has(k)),
8910
9568
  conflicts: varPlan.conflicts.filter((c) => wanted.has(c.key)),
9569
+ // A drifted var nobody selected is not this push's business to
9570
+ // report, the same way its writes are not this push's to make.
9571
+ drifted: varPlan.drifted.filter((d) => wanted.has(d.key)),
8911
9572
  skippedCount: 0,
8912
9573
  };
8913
9574
  }
@@ -9200,6 +9861,13 @@ What a push guarantees (two stages):
9200
9861
  localModifiedAt: c.localModifiedAt,
9201
9862
  });
9202
9863
  }
9864
+ // …and var drift into the shared drift accumulator (#3714), so a var
9865
+ // only the server moved prints the `DRIFT var: KEY` row every other
9866
+ // type prints for that shape. It is not a failure: nothing was
9867
+ // written and neither the exit code nor the pushed count moves.
9868
+ for (const d of varPlan.drifted) {
9869
+ drifted.push({ type: "var", key: d.key });
9870
+ }
9203
9871
  // Delete removed keys BEFORE upserting new ones (issue #1423 review
9204
9872
  // pass 3). At the server's 100-var cap, a replacement (remove one key,
9205
9873
  // add another) is a valid final state, but upserting the new key first
@@ -10480,8 +11148,14 @@ What a push guarantees (two stages):
10480
11148
  }
10481
11149
  // Process prompts
10482
11150
  const promptsDir = join(configDir, "prompts");
10483
- if (existsSync(promptsDir)) {
10484
- const files = selectFiles("prompt", promptsDir, readdirSync(promptsDir).filter((f) => f.endsWith(".toml")));
11151
+ // #3798 — the prompt leg as one function, called twice. `config push`
11152
+ // applies prompts BEFORE server functions, and an agent's tools name
11153
+ // functions the server must hold when the agent is created, so a tree
11154
+ // that pushes an agent together with its tool functions would be
11155
+ // refused on its first push. Chat and decisions files keep their place;
11156
+ // agent files are applied after the server-functions leg below
11157
+ // (`deferredAgentPromptFiles`). Nothing inside the leg changed.
11158
+ const pushPromptFiles = async (files) => {
10485
11159
  // #2869 — prompts join the live-state reconcile (#2731 B3). #2748
10486
11160
  // gave the type diff's comparator and left push on the manifest byte
10487
11161
  // hash, so the two commands answered "changed?" from different
@@ -10502,13 +11176,26 @@ What a push guarantees (two stages):
10502
11176
  // manifest byte-hash gate with the type named, like every other
10503
11177
  // converted type.
10504
11178
  const livePromptIds = new Map();
11179
+ // #3626, CR3626-001 — the KIND the server holds for each prompt,
11180
+ // taken from the same list. `kind` is immutable after create
11181
+ // (D3626-008), and the comparison gate refuses a change to it — but
11182
+ // only on the paths that reach that gate. This map is what the other
11183
+ // two read: a prompt whose DETAIL read failed (degraded to the
11184
+ // byte-hash gate, which `--force` writes through) and a prompt
11185
+ // adopted by key after a 409 (which re-issues the file as an UPDATE
11186
+ // without ever comparing). Both would otherwise PATCH the prompt's
11187
+ // schemas, access rule and metadata onto a row of the other kind
11188
+ // before a config was refused against the kind that did not change.
11189
+ const livePromptKinds = new Map();
10505
11190
  let promptsLiveOk = true;
10506
11191
  if (files.length > 0) {
10507
11192
  try {
10508
11193
  const listed = await fetchAll((p) => client.listPrompts(resolvedAppId, p));
10509
11194
  for (const p of listed) {
10510
- if (p?.promptKey)
10511
- livePromptIds.set(p.promptKey, p.promptId);
11195
+ if (!p?.promptKey)
11196
+ continue;
11197
+ livePromptIds.set(p.promptKey, p.promptId);
11198
+ livePromptKinds.set(p.promptKey, promptKindOf(p));
10512
11199
  }
10513
11200
  }
10514
11201
  catch (err) {
@@ -10671,6 +11358,79 @@ What a push guarantees (two stages):
10671
11358
  // (mirrors `applyWorkflowUpdate`). The adopt branch seeds the
10672
11359
  // sync-state entity record before calling this so the stamp lands.
10673
11360
  const applyPromptUpdate = async (promptId, expectedModifiedAt) => {
11361
+ // #3799 (CSO-3799-005) — an agent's declaration is checked against
11362
+ // every config the server holds non-archived, so a file that
11363
+ // retires a config AND declares a schema that config's provider
11364
+ // cannot carry must retire it first: sent the other way round,
11365
+ // the prompt PATCH is refused for a config the file has already
11366
+ // archived, and no re-run changes the order. Only the entries
11367
+ // the file archives and the server does not yet — every other
11368
+ // config update still follows the prompt, and decisions prompts
11369
+ // keep their sequence. A config PATCH does not move the
11370
+ // prompt's `modifiedAt`, so the concurrency guard below still
11371
+ // holds.
11372
+ //
11373
+ // #3801 (DSO-3801-001) — the same staging, with a second admission
11374
+ // rule. The admin API refuses clearing a CHAT prompt's
11375
+ // `[prompt].outputSchema` while a config it holds non-archived is
11376
+ // strict, so a file that clears the schema AND turns strict output
11377
+ // off (or retires the config) would be refused on every push if the
11378
+ // prompt went first. Those config updates go ahead of the prompt
11379
+ // PATCH, with the payload they would have been sent anyway. The
11380
+ // read this needs is the one the name→id mapping below makes,
11381
+ // moved ahead of the PATCH, so the request count does not grow.
11382
+ const stagedFirst = new Set();
11383
+ const fileKind = promptKindOf(tomlData?.prompt);
11384
+ const retiring = configs.filter((c) => c?.name &&
11385
+ String(c?.status ?? "").trim().toLowerCase() === "archived");
11386
+ const stagesRetiringAgent = fileKind === "agent" && retiring.length > 0;
11387
+ const clearsPromptSchema = fileKind === "chat" &&
11388
+ !declaresSchema(tomlData?.prompt?.outputSchema);
11389
+ const current = stagesRetiringAgent || clearsPromptSchema
11390
+ ? await client.getPrompt(resolvedAppId, promptId)
11391
+ : null;
11392
+ const liveServerConfig = (name) => {
11393
+ const found = (current?.configs ?? []).find((c) => c.configName === name);
11394
+ return found && String(found.status ?? "active") !== "archived"
11395
+ ? found
11396
+ : null;
11397
+ };
11398
+ const staged = [];
11399
+ if (stagesRetiringAgent) {
11400
+ for (const tomlConfig of retiring) {
11401
+ const serverConfig = liveServerConfig(tomlConfig.name);
11402
+ if (serverConfig)
11403
+ staged.push({ tomlConfig, serverConfig });
11404
+ }
11405
+ }
11406
+ if (clearsPromptSchema && declaresSchema(current?.outputSchema)) {
11407
+ for (const tomlConfig of configs) {
11408
+ if (!tomlConfig?.name)
11409
+ continue;
11410
+ const serverConfig = liveServerConfig(tomlConfig.name);
11411
+ if (!serverConfig || serverConfig.strictOutput !== true)
11412
+ continue;
11413
+ const chat = hoistDeprecatedChatKeys(tomlConfig).entry.chat ?? {};
11414
+ const retired = String(tomlConfig?.status ?? "").trim().toLowerCase() ===
11415
+ "archived";
11416
+ // An entry that stays strict AND live is refused in preflight
11417
+ // (no schema to send); it is never staged.
11418
+ if (chat.strictOutput === true && !retired)
11419
+ continue;
11420
+ staged.push({ tomlConfig, serverConfig });
11421
+ }
11422
+ }
11423
+ for (const { tomlConfig, serverConfig } of staged) {
11424
+ if (stagedFirst.has(tomlConfig.name))
11425
+ continue;
11426
+ try {
11427
+ await client.updatePromptConfig(resolvedAppId, promptId, serverConfig.configId, buildPromptConfigPayload(tomlConfig, { mode: "update" }));
11428
+ }
11429
+ catch (err) {
11430
+ throw wrapPromptConfigError(err, "update", key, tomlConfig.name);
11431
+ }
11432
+ stagedFirst.add(tomlConfig.name);
11433
+ }
10674
11434
  const updated = await client.updatePrompt(resolvedAppId, promptId, buildPromptPushPayload(key, tomlData, { mode: "update" }), expectedModifiedAt);
10675
11435
  info(` Updated prompt: ${key}`);
10676
11436
  // Record the `modifiedAt` this PATCH just caused, so a later
@@ -10693,7 +11453,10 @@ What a push guarantees (two stages):
10693
11453
  try {
10694
11454
  // Fetch full prompt to get config name→ID mappings
10695
11455
  // (updatePrompt response doesn't include configs)
10696
- const fullPrompt = await client.getPrompt(resolvedAppId, promptId);
11456
+ // #3801 — the read made ahead of the prompt PATCH when the
11457
+ // staging needed it (neither the PATCH nor a staged config
11458
+ // update moves a config's id or the activation).
11459
+ const fullPrompt = current ?? (await client.getPrompt(resolvedAppId, promptId));
10697
11460
  if (fullPrompt?.configs) {
10698
11461
  for (const config of fullPrompt.configs) {
10699
11462
  promptConfigNameToId.set(`${key}#${config.configName}`, config.configId);
@@ -10707,6 +11470,10 @@ What a push guarantees (two stages):
10707
11470
  continue;
10708
11471
  const serverConfig = fullPrompt.configs.find((c) => c.configName === configName);
10709
11472
  if (serverConfig) {
11473
+ // Staged ahead of the prompt PATCH, with this same
11474
+ // payload (#3799 CSO-3799-005, #3801 DSO-3801-001).
11475
+ if (stagedFirst.has(configName))
11476
+ continue;
10710
11477
  // Update existing config
10711
11478
  try {
10712
11479
  await client.updatePromptConfig(resolvedAppId, promptId, serverConfig.configId, buildPromptConfigPayload(tomlConfig, { mode: "update" }));
@@ -10727,18 +11494,9 @@ What a push guarantees (two stages):
10727
11494
  }
10728
11495
  if (newConfig?.configId) {
10729
11496
  promptConfigNameToId.set(`${key}#${configName}`, newConfig.configId);
10730
- // #3201 — the create assigned `active`; a file that
10731
- // retired this entry says so in the only mode the
10732
- // server accepts the key in.
10733
- const statusPatch = createdConfigStatusPatch(tomlConfig);
10734
- if (statusPatch) {
10735
- try {
10736
- await client.updatePromptConfig(resolvedAppId, promptId, newConfig.configId, statusPatch);
10737
- }
10738
- catch (err) {
10739
- throw wrapPromptConfigError(err, "update", key, configName);
10740
- }
10741
- }
11497
+ // #3799 — the create body carried the entry's own
11498
+ // `status`, so there is no follow-up patch (#3201's is
11499
+ // retired).
10742
11500
  }
10743
11501
  }
10744
11502
  }
@@ -10831,6 +11589,18 @@ What a push guarantees (two stages):
10831
11589
  }
10832
11590
  };
10833
11591
  if (existingId) {
11592
+ // #3626, CR3626-001 — the kind, before anything is written. The
11593
+ // comparison gate above already refuses a changed `kind`, but it
11594
+ // only ran when the DETAIL read succeeded; a prompt degraded to
11595
+ // the byte-hash gate reaches this line with `--force` and no
11596
+ // comparison at all. The list's kind is enough to answer it, and
11597
+ // answering it here keeps the promise the gate makes: a kind
11598
+ // change is declined before the first mutating call.
11599
+ const degradedKindDecline = promptKindImmutableOutcome(livePrompt ? promptKindOf(livePrompt) : livePromptKinds.get(key), tomlData);
11600
+ if (degradedKindDecline) {
11601
+ recordDeclined("prompt", key, degradedKindDecline, existingEntry?.modifiedAt);
11602
+ continue;
11603
+ }
10834
11604
  // Update existing prompt
10835
11605
  changes.push({ type: "prompt", action: "update", key });
10836
11606
  promptKeyToId.set(key, existingId);
@@ -10923,6 +11693,19 @@ What a push guarantees (two stages):
10923
11693
  });
10924
11694
  adopted = true;
10925
11695
  const adoptedId = existing.promptId;
11696
+ // #3626, CR3626-001 — the adopted prompt's KIND, before the
11697
+ // re-issue writes anything. This path never reaches the
11698
+ // comparison gate (the create is what failed), so without
11699
+ // this an orphaned chat prompt would take a decisions file's
11700
+ // schemas, access rule and metadata by PATCH and only then
11701
+ // refuse its configs against the kind the update cannot
11702
+ // change. The lookup already read the record, so the answer
11703
+ // costs nothing.
11704
+ const adoptKindDecline = promptKindImmutableOutcome(promptKindOf(existing), tomlData);
11705
+ if (adoptKindDecline) {
11706
+ recordDeclined("prompt", key, adoptKindDecline);
11707
+ continue;
11708
+ }
10926
11709
  // Seed the sync-state entity record so the shared update body
10927
11710
  // can stamp modifiedAt/contentHash into it (sync state has no
10928
11711
  // entry for an orphaned prompt), and track the key→ID map.
@@ -11047,21 +11830,11 @@ What a push guarantees (two stages):
11047
11830
  throw wrapPromptConfigError(err, "create", key, extraName);
11048
11831
  }
11049
11832
  if (extraCreated?.configId) {
11050
- const configName = extraName;
11051
- promptConfigNameToId.set(`${key}#${configName}`, extraCreated.configId);
11052
- // #3201 — as on the update path: the create ignored
11053
- // the entry's `status`, so a retired one is applied
11054
- // here or the fresh environment runs a config the
11055
- // file retired.
11056
- const statusPatch = createdConfigStatusPatch(extraConfig);
11057
- if (statusPatch) {
11058
- try {
11059
- await client.updatePromptConfig(resolvedAppId, created.promptId, extraCreated.configId, statusPatch);
11060
- }
11061
- catch (err) {
11062
- throw wrapPromptConfigError(err, "update", key, configName);
11063
- }
11064
- }
11833
+ promptConfigNameToId.set(`${key}#${extraName}`, extraCreated.configId);
11834
+ // #3799 — as on the update path: the create carried the
11835
+ // entry's `status`, so a retired entry is retired when
11836
+ // it is created and the fresh environment never runs a
11837
+ // config the file retired.
11065
11838
  }
11066
11839
  }
11067
11840
  info(` Created ${configs.length - 1} additional config(s) for prompt: ${key}`);
@@ -11093,25 +11866,17 @@ What a push guarantees (two stages):
11093
11866
  activated = true;
11094
11867
  }
11095
11868
  }
11096
- // #3201 — the seeded config's own `status`, applied LAST for
11097
- // the same reason activation runs after the extra creates:
11098
- // the create points `activeConfigId` at this config, so a
11099
- // file that retires it is asking for a state that only makes
11100
- // sense once the entry it marks active exists and is live.
11101
- // Retiring it earlier would leave the prompt serving from an
11102
- // archived config for the length of the remaining calls, and
11103
- // permanently if one of them failed.
11104
- const seededStatusPatch = seededConfigId
11105
- ? createdConfigStatusPatch(firstConfig || {})
11106
- : null;
11107
- if (created?.promptId && seededConfigId && seededStatusPatch) {
11108
- try {
11109
- await client.updatePromptConfig(resolvedAppId, created.promptId, seededConfigId, seededStatusPatch);
11110
- }
11111
- catch (err) {
11112
- throw wrapPromptConfigError(err, "update", key, firstConfigPatch?.configName || seededConfig?.configName);
11113
- }
11114
- }
11869
+ // #3799 (DSO-3799-005) — the seeded config's `status` is in
11870
+ // the create body (`POST /prompts` honors it now), so #3201's
11871
+ // trailing patch is gone. Activation still runs after every
11872
+ // create (#2645), so the marked entry is what the prompt ends
11873
+ // up serving; when the FIRST entry is the retired one, the
11874
+ // seeded config the prompt points at is created archived and
11875
+ // the activation moves the pointer off it. A push that dies
11876
+ // between the two leaves a prompt pointing at an archived
11877
+ // config — recovered by re-running the push, and the price of
11878
+ // never creating a config in a state the file did not ask for
11879
+ // (which is what an agent's schema check fires on).
11115
11880
  // Stamp sync state ONLY after all create work (base prompt +
11116
11881
  // every extra config) succeeded. If an extra-config create
11117
11882
  // above threw, we never reach here, so the file hash is not
@@ -11147,6 +11912,13 @@ What a push guarantees (two stages):
11147
11912
  }
11148
11913
  }
11149
11914
  }
11915
+ };
11916
+ let deferredAgentPromptFiles = [];
11917
+ if (existsSync(promptsDir)) {
11918
+ const files = selectFiles("prompt", promptsDir, readdirSync(promptsDir).filter((f) => f.endsWith(".toml")));
11919
+ const ordered = partitionPromptFilesForPush(promptsDir, files);
11920
+ deferredAgentPromptFiles = ordered.afterFunctions;
11921
+ await pushPromptFiles(ordered.beforeFunctions);
11150
11922
  }
11151
11923
  // Process transforms (Rhai scripts) — issue #892, slice 7 of #783.
11152
11924
  //
@@ -13619,6 +14391,11 @@ What a push guarantees (two stages):
13619
14391
  }
13620
14392
  }
13621
14393
  }
14394
+ // #3798 — the agent prompts, now that every function they name that
14395
+ // this push applies is on the server (see `pushPromptFiles`).
14396
+ if (deferredAgentPromptFiles.length > 0) {
14397
+ await pushPromptFiles(deferredAgentPromptFiles);
14398
+ }
13622
14399
  // Process group type configs
13623
14400
  const groupTypeConfigsDir = join(configDir, "group-type-configs");
13624
14401
  if (existsSync(groupTypeConfigsDir)) {