@jini-ai/agent-runtime 0.7.3-next.1 → 0.7.3-next.3

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 (170) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +38 -0
  3. package/dist/agent-protocol/acp/constants.d.ts +3 -0
  4. package/dist/agent-protocol/acp/constants.js +5 -0
  5. package/dist/agent-protocol/acp/models.d.ts +0 -10
  6. package/dist/agent-protocol/acp/models.js +6 -11
  7. package/dist/agent-protocol/acp/rpc.d.ts +5 -1
  8. package/dist/agent-protocol/acp/rpc.js +2 -1
  9. package/dist/agent-protocol/acp/session-permission.js +4 -3
  10. package/dist/agent-protocol/acp/session-results.d.ts +3 -3
  11. package/dist/agent-protocol/acp/session-results.js +22 -17
  12. package/dist/agent-protocol/acp/session-run.js +0 -8
  13. package/dist/agent-protocol/acp/session-types.d.ts +0 -1
  14. package/dist/agent-protocol/acp/session.js +3 -2
  15. package/dist/agent-protocol/acp/text-suppression.js +75 -71
  16. package/dist/agent-protocol/pi-rpc/events.d.ts +21 -4
  17. package/dist/agent-protocol/pi-rpc/events.js +8 -8
  18. package/dist/agent-protocol/pi-rpc/internal.d.ts +6 -2
  19. package/dist/agent-protocol/pi-rpc/internal.js +6 -4
  20. package/dist/agent-protocol/pi-rpc/session.js +4 -3
  21. package/dist/anthropic-live-models.js +0 -0
  22. package/dist/claude-code-models.d.ts +3 -1
  23. package/dist/claude-code-models.js +4 -4
  24. package/dist/cli-probe-cache.d.ts +33 -0
  25. package/dist/cli-probe-cache.js +59 -0
  26. package/dist/custom-instructions.d.ts +107 -0
  27. package/dist/custom-instructions.js +80 -0
  28. package/dist/defs/{aider.d.ts → aider/index.d.ts} +2 -1
  29. package/dist/defs/{aider.js → aider/index.js} +6 -3
  30. package/dist/defs/amr/executable-env.d.ts +2 -0
  31. package/dist/defs/amr/executable-env.js +2 -0
  32. package/dist/defs/amr/executable-resolution.d.ts +5 -1
  33. package/dist/defs/amr/executable-resolution.js +1 -1
  34. package/dist/defs/antigravity/index.d.ts +1 -0
  35. package/dist/defs/antigravity/index.js +3 -0
  36. package/dist/defs/antigravity/permissions.d.ts +26 -0
  37. package/dist/defs/antigravity/permissions.js +66 -0
  38. package/dist/defs/{auggie.d.ts → auggie/index.d.ts} +1 -1
  39. package/dist/defs/{auggie.js → auggie/index.js} +3 -3
  40. package/dist/defs/claude/config-dir.d.ts +62 -0
  41. package/dist/defs/claude/config-dir.js +133 -0
  42. package/dist/defs/claude/filesystem.d.ts +33 -0
  43. package/dist/defs/claude/filesystem.js +30 -0
  44. package/dist/defs/{claude.d.ts → claude/index.d.ts} +1 -1
  45. package/dist/defs/{claude.js → claude/index.js} +9 -9
  46. package/dist/defs/claude/mcp-config.d.ts +22 -0
  47. package/dist/defs/claude/mcp-config.js +29 -0
  48. package/dist/defs/claude/mcp-delivery.d.ts +57 -0
  49. package/dist/defs/claude/mcp-delivery.js +75 -0
  50. package/dist/defs/claude/mcp-json.d.ts +34 -0
  51. package/dist/defs/claude/mcp-json.js +38 -0
  52. package/dist/defs/claude/subagent-start.d.ts +12 -0
  53. package/dist/defs/claude/subagent-start.js +35 -0
  54. package/dist/defs/{cline.d.ts → cline/index.d.ts} +1 -1
  55. package/dist/defs/{cline.js → cline/index.js} +3 -3
  56. package/dist/defs/codex/contracts.d.ts +47 -0
  57. package/dist/defs/codex/contracts.js +6 -0
  58. package/dist/defs/codex/event-stream.d.ts +5 -1
  59. package/dist/defs/codex/event-stream.js +29 -24
  60. package/dist/defs/codex/home-config.d.ts +55 -0
  61. package/dist/defs/codex/home-config.js +224 -0
  62. package/dist/defs/codex/home-staging.d.ts +57 -0
  63. package/dist/defs/codex/home-staging.js +184 -0
  64. package/dist/defs/{codex.d.ts → codex/index.d.ts} +2 -2
  65. package/dist/defs/{codex.js → codex/index.js} +3 -3
  66. package/dist/defs/codex/isolation.d.ts +29 -0
  67. package/dist/defs/codex/isolation.js +69 -0
  68. package/dist/defs/codex/launch.d.ts +4 -1
  69. package/dist/defs/codex/launch.js +1 -1
  70. package/dist/defs/codex/mcp-delivery.d.ts +8 -0
  71. package/dist/defs/codex/mcp-delivery.js +5 -0
  72. package/dist/defs/{crush.d.ts → crush/index.d.ts} +1 -1
  73. package/dist/defs/{crush.js → crush/index.js} +3 -3
  74. package/dist/defs/cursor-agent/event-stream.d.ts +5 -1
  75. package/dist/defs/cursor-agent/event-stream.js +14 -7
  76. package/dist/defs/{cursor-agent.d.ts → cursor-agent/index.d.ts} +1 -1
  77. package/dist/defs/{cursor-agent.js → cursor-agent/index.js} +4 -4
  78. package/dist/defs/{deepseek.d.ts → deepseek/index.d.ts} +2 -1
  79. package/dist/defs/{deepseek.js → deepseek/index.js} +6 -3
  80. package/dist/defs/{devin.d.ts → devin/index.d.ts} +1 -1
  81. package/dist/defs/{devin.js → devin/index.js} +3 -3
  82. package/dist/defs/{droid.d.ts → droid/index.d.ts} +1 -1
  83. package/dist/defs/{droid.js → droid/index.js} +3 -3
  84. package/dist/defs/gemini/event-stream.d.ts +5 -1
  85. package/dist/defs/gemini/event-stream.js +15 -12
  86. package/dist/defs/gemini/tool-calls.d.ts +7 -0
  87. package/dist/defs/gemini/tool-calls.js +9 -0
  88. package/dist/defs/{goose.d.ts → goose/index.d.ts} +1 -1
  89. package/dist/defs/{goose.js → goose/index.js} +3 -3
  90. package/dist/defs/{grok-build.d.ts → grok-build/index.d.ts} +1 -1
  91. package/dist/defs/{grok-build.js → grok-build/index.js} +3 -3
  92. package/dist/defs/index.d.ts +28 -28
  93. package/dist/defs/index.js +28 -28
  94. package/dist/defs/{kilo.d.ts → kilo/index.d.ts} +1 -1
  95. package/dist/defs/{kilo.js → kilo/index.js} +3 -3
  96. package/dist/defs/kimi/event-stream.d.ts +4 -1
  97. package/dist/defs/kimi/event-stream.js +6 -5
  98. package/dist/defs/{kimi.d.ts → kimi/index.d.ts} +1 -1
  99. package/dist/defs/{kimi.js → kimi/index.js} +3 -3
  100. package/dist/defs/{kiro.d.ts → kiro/index.d.ts} +1 -1
  101. package/dist/defs/{kiro.js → kiro/index.js} +3 -3
  102. package/dist/defs/mimo/constants.d.ts +2 -0
  103. package/dist/defs/mimo/constants.js +2 -0
  104. package/dist/defs/{mimo.d.ts → mimo/index.d.ts} +1 -1
  105. package/dist/defs/{mimo.js → mimo/index.js} +3 -3
  106. package/dist/defs/opencode/constants.d.ts +2 -0
  107. package/dist/defs/opencode/constants.js +2 -0
  108. package/dist/defs/opencode/event-stream.d.ts +5 -1
  109. package/dist/defs/opencode/event-stream.js +13 -11
  110. package/dist/defs/{opencode.d.ts → opencode/index.d.ts} +2 -2
  111. package/dist/defs/{opencode.js → opencode/index.js} +5 -5
  112. package/dist/defs/opencode/mcp-config.d.ts +108 -0
  113. package/dist/defs/opencode/mcp-config.js +119 -0
  114. package/dist/defs/opencode/model-discovery.d.ts +3 -1
  115. package/dist/defs/opencode/model-discovery.js +1 -1
  116. package/dist/defs/opencode/tool-calls.d.ts +7 -0
  117. package/dist/defs/opencode/tool-calls.js +12 -0
  118. package/dist/defs/{opencode-acp.d.ts → opencode-acp/index.d.ts} +2 -2
  119. package/dist/defs/{opencode-acp.js → opencode-acp/index.js} +4 -4
  120. package/dist/defs/{pi.d.ts → pi/index.d.ts} +1 -1
  121. package/dist/defs/{pi.js → pi/index.js} +3 -3
  122. package/dist/defs/pi/model-discovery.d.ts +4 -1
  123. package/dist/defs/pi/model-discovery.js +1 -1
  124. package/dist/defs/{qoder.d.ts → qoder/index.d.ts} +1 -1
  125. package/dist/defs/{qoder.js → qoder/index.js} +3 -3
  126. package/dist/defs/{qwen.d.ts → qwen/index.d.ts} +1 -1
  127. package/dist/defs/{qwen.js → qwen/index.js} +3 -3
  128. package/dist/defs/{reasonix.d.ts → reasonix/index.d.ts} +1 -1
  129. package/dist/defs/{reasonix.js → reasonix/index.js} +3 -3
  130. package/dist/defs/{trae-cli.d.ts → trae-cli/index.d.ts} +1 -1
  131. package/dist/defs/{trae-cli.js → trae-cli/index.js} +3 -3
  132. package/dist/defs/{vibe.d.ts → vibe/index.d.ts} +1 -1
  133. package/dist/defs/{vibe.js → vibe/index.js} +3 -3
  134. package/dist/executables.js +1 -1
  135. package/dist/inventory/index.d.ts +61 -0
  136. package/dist/inventory/index.js +45 -0
  137. package/dist/json-event-stream-shared.d.ts +10 -2
  138. package/dist/json-event-stream-shared.js +21 -13
  139. package/dist/json-event-stream.js +6 -5
  140. package/dist/launch.js +1 -1
  141. package/dist/model-catalog-live-discovery.d.ts +103 -0
  142. package/dist/model-catalog-live-discovery.js +111 -0
  143. package/dist/model-discovery-adapters.d.ts +6 -1
  144. package/dist/model-discovery-adapters.js +4 -3
  145. package/dist/model-discovery-config.js +1 -1
  146. package/dist/native-permissions.d.ts +19 -0
  147. package/dist/native-permissions.js +22 -0
  148. package/dist/providers/connection-guard.js +98 -83
  149. package/dist/providers/connection-test.js +0 -5
  150. package/dist/providers/oauth-provider.d.ts +1 -23
  151. package/dist/providers/oauth-provider.js +1 -35
  152. package/dist/providers/tool-turn-types.d.ts +12 -9
  153. package/dist/providers/tool-turn.d.ts +63 -1
  154. package/dist/providers/tool-turn.js +66 -0
  155. package/dist/qoder-stream.js +66 -66
  156. package/dist/role-marker-guard.js +49 -30
  157. package/dist/runtime-def-binding.js +1 -1
  158. package/dist/runtime-port-bindings.d.ts +82 -0
  159. package/dist/runtime-port-bindings.js +4 -1
  160. package/dist/runtime-strategies.d.ts +100 -0
  161. package/dist/runtime-strategies.js +129 -0
  162. package/package.json +45 -11
  163. package/dist/defs/amp.d.ts +0 -2
  164. package/dist/defs/amp.js +0 -2
  165. package/dist/defs/amr.d.ts +0 -2
  166. package/dist/defs/amr.js +0 -2
  167. package/dist/defs/codebuddy.d.ts +0 -2
  168. package/dist/defs/codebuddy.js +0 -2
  169. package/dist/defs/hermes.d.ts +0 -2
  170. package/dist/defs/hermes.js +0 -2
@@ -6,5 +6,9 @@ export type CodexStreamState = {
6
6
  lastAgentMessageEndedWithNewline: boolean;
7
7
  };
8
8
  export declare function createCodexStreamState(): CodexStreamState;
9
- export declare function handleCodexEvent(obj: unknown, onEvent: StreamEventHandler, state: ParserState): boolean;
9
+ export declare function handleCodexEvent({ obj: value, onEvent, state }: {
10
+ obj: unknown;
11
+ onEvent: StreamEventHandler;
12
+ state: ParserState;
13
+ }, _optional?: Record<string, never>): boolean;
10
14
  //# sourceMappingURL=event-stream.d.ts.map
@@ -1,5 +1,5 @@
1
1
  import { sanitizeUntrustedText } from '@jini-ai/core/text';
2
- import { dispatchFrame, extractErrorMessage, isRecord, nonEmptyString, pickUsage, safeParseJson, stringifyContent, todoWriteInputFromItems, trimmedNonBlank } from '../../json-event-stream-shared.js';
2
+ import { dispatchFrame, extractErrorMessage, getRecord, isRecord, nonEmptyString, pickUsage, safeParseJson, stringifyContent, todoWriteInputFromItems, trimmedNonBlank } from '../../json-event-stream-shared.js';
3
3
  export function createCodexStreamState() {
4
4
  return { toolUses: new Set(), errorEmitted: false, previousEventWasAgentMessage: false, lastAgentMessageEndedWithNewline: false };
5
5
  }
@@ -7,27 +7,30 @@ function parseJsonObjectsFromContent(value) {
7
7
  // The caller requires CONNECTOR_TOOL_NOT_FOUND before parsing. Empty input also reaches the
8
8
  // existing [] fallback naturally, so no separate empty-string branch is needed.
9
9
  const trimmed = value.trim();
10
- const direct = safeParseJson({ value: trimmed });
11
- if (isRecord(direct))
10
+ const direct = getRecord({ value: safeParseJson({ value: trimmed }) });
11
+ if (direct)
12
12
  return [direct];
13
13
  const objects = [];
14
14
  for (const line of trimmed.split(/\r?\n/u)) {
15
- const parsedLine = safeParseJson({ value: line.trim() });
16
- if (isRecord(parsedLine))
15
+ const parsedLine = getRecord({ value: safeParseJson({ value: line.trim() }) });
16
+ if (parsedLine)
17
17
  objects.push(parsedLine);
18
18
  }
19
19
  return objects;
20
20
  }
21
+ function isRecordElement(value) {
22
+ return isRecord({ value });
23
+ }
21
24
  function extractConnectorApiError(value) {
22
- if (isRecord(value.error)) {
23
- if (typeof value.error.code === 'string')
24
- return value.error;
25
- if (isRecord(value.error.data) && isRecord(value.error.data.error)) {
26
- const wrappedError = value.error.data.error;
27
- if (typeof wrappedError.code === 'string')
28
- return wrappedError;
29
- }
30
- }
25
+ const error = getRecord({ value: value.error });
26
+ if (!error)
27
+ return null;
28
+ if (typeof error.code === 'string')
29
+ return error;
30
+ const data = getRecord({ value: error.data });
31
+ const wrappedError = getRecord({ value: data?.error });
32
+ if (typeof wrappedError?.code === 'string')
33
+ return wrappedError;
31
34
  return null;
32
35
  }
33
36
  function connectorToolSelectionErrorMessage(content) {
@@ -38,7 +41,7 @@ function connectorToolSelectionErrorMessage(content) {
38
41
  .find((parsedError) => parsedError?.code === 'CONNECTOR_TOOL_NOT_FOUND');
39
42
  if (!error)
40
43
  return null;
41
- const details = isRecord(error.details) ? error.details : {};
44
+ const details = getRecord({ value: error.details }) ?? {};
42
45
  const connectorId = nonEmptyString({ value: details.connectorId });
43
46
  const toolName = nonEmptyString({ value: details.toolName }) ?? 'the requested connector tool';
44
47
  const target = connectorId
@@ -189,7 +192,7 @@ function completeCodexFileChange(item, onEvent, state) {
189
192
  function emitCodexFileChange(item, onEvent) {
190
193
  const changes = Array.isArray(item.changes) ? item.changes : [];
191
194
  onEvent({ type: 'tool_use', id: item.id, name: 'apply_patch',
192
- input: { paths: changes.filter(isRecord).map(change => change.path).filter(path => typeof path === 'string') } });
195
+ input: { paths: changes.filter(isRecordElement).map(change => change.path).filter(path => typeof path === 'string') } });
193
196
  onEvent({ type: 'tool_result', toolUseId: item.id, content: 'File change reported by Codex.', isError: item.status === 'failed' });
194
197
  }
195
198
  function completeCodexCommand(item, onEvent, state) {
@@ -216,10 +219,10 @@ function completeCodexCommand(item, onEvent, state) {
216
219
  */
217
220
  function codexMcpFailureContent({ item }, _options = {}) {
218
221
  const error = trimmedNonBlank({ value: extractErrorMessage({ value: item.error, fallback: '' }) });
219
- const result = isRecord(item.result) ? item.result : {};
222
+ const result = getRecord({ value: item.result }) ?? {};
220
223
  const blocks = Array.isArray(result.content) ? result.content : [];
221
224
  // Keep text verbatim until sanitizing so JSON error envelopes retain codes and recovery hints.
222
- const text = blocks.filter(isRecord)
225
+ const text = blocks.filter(isRecordElement)
223
226
  .filter(block => block.type === 'text')
224
227
  .map(block => trimmedNonBlank({ value: block.text }))
225
228
  .filter(Boolean)
@@ -281,9 +284,9 @@ function handleCodexItemCompleted(item, onEvent, state) {
281
284
  */
282
285
  function codexItemFrame(handleItem) {
283
286
  return (obj, onEvent, state) => {
284
- if (!isRecord(obj.item))
287
+ const item = getRecord({ value: obj.item });
288
+ if (!item)
285
289
  return false;
286
- const item = obj.item;
287
290
  if (item.type === 'collab_tool_call' && hasStringId(item)) {
288
291
  return emitCodexCollabToolCall(item, obj.type === 'item.completed', onEvent, state);
289
292
  }
@@ -330,9 +333,10 @@ const CODEX_USAGE_FIELDS = [
330
333
  ['cached_input_tokens', 'cached_read_tokens'],
331
334
  ];
332
335
  function handleCodexTurnCompleted(obj, onEvent) {
333
- if (!isRecord(obj.usage))
336
+ const usage = getRecord({ value: obj.usage });
337
+ if (!usage)
334
338
  return false;
335
- onEvent({ type: 'usage', usage: pickUsage({ source: obj.usage, fields: CODEX_USAGE_FIELDS }) });
339
+ onEvent({ type: 'usage', usage: pickUsage({ source: usage, fields: CODEX_USAGE_FIELDS }) });
336
340
  return true;
337
341
  }
338
342
  const CODEX_FRAME_HANDLERS = new Map([
@@ -345,8 +349,9 @@ const CODEX_FRAME_HANDLERS = new Map([
345
349
  ['item.completed', codexItemFrame(handleCodexItemCompleted)],
346
350
  ['turn.completed', handleCodexTurnCompleted],
347
351
  ]);
348
- export function handleCodexEvent(obj, onEvent, state) {
349
- if (!isRecord(obj))
352
+ export function handleCodexEvent({ obj: value, onEvent, state }, _optional = {}) {
353
+ const obj = getRecord({ value });
354
+ if (!obj)
350
355
  return false;
351
356
  return dispatchFrame({ handlers: CODEX_FRAME_HANDLERS, obj, onEvent, state });
352
357
  }
@@ -0,0 +1,55 @@
1
+ import { type CodexBridgeEntry, type CodexHttpEndpoint, type CodexToolApprovalOwner } from './contracts.js';
2
+ /** A TOML key: bare when TOML allows it, quoted otherwise — host-supplied bridge env names are not guaranteed bare-safe. */
3
+ export declare function tomlKey({ key }: {
4
+ key: string;
5
+ }, _optional?: Record<string, never>): string;
6
+ /**
7
+ * Mechanism 5 of 5 — `'codex-toml'`'s serialization step. Builds the `[mcp_servers.jini]` TOML
8
+ * table (plus, when the entry carries any env vars, a separate `[mcp_servers.jini.env]` table)
9
+ * Codex's own config schema expects. An explicit HTTP endpoint instead writes `url` and
10
+ * literal `http_headers` through the same table replacement and escaping owners.
11
+ *
12
+ * Confirmed against a real installed Codex CLI (0.151.0), not assumed from docs: round-tripping
13
+ * `codex mcp add <name> --env K=V -- <cmd> <args>` against a scratch `CODEX_HOME` and reading back
14
+ * `config.toml` produced exactly this shape (`command`/`args` as TOML strings/array in the main
15
+ * table, env vars in a nested `.env` table) — see `archived provenance ledger` for the transcript.
16
+ * @param entry - A stdio bridge entry or an explicit run HTTP endpoint.
17
+ * @returns A TOML fragment with no leading/trailing blank-line padding — {@link buildCodexHomeConfigToml} owns spacing when combining it with existing content.
18
+ * @complexity O(n) in the number of argv/env entries.
19
+ * @overallScore 100/100
20
+ */
21
+ export declare function buildCodexMcpServerToml({ entry, toolApprovalOwner }: {
22
+ readonly entry: CodexBridgeEntry | CodexHttpEndpoint;
23
+ readonly toolApprovalOwner?: CodexToolApprovalOwner;
24
+ }, _options?: {}): string;
25
+ /**
26
+ * Builds the full `config.toml` a run's scratch `CODEX_HOME` gets: the real Codex home's own
27
+ * config, with any pre-existing `[mcp_servers.jini]` table removed (see
28
+ * {@link stripExistingJiniMcpServerTable}), then this run's own table appended.
29
+ *
30
+ * **Append-only by design, not a parse-and-merge, for everything but the jini table itself.**
31
+ * `mergeMcpJsonContent` (`mcp-json-file.ts`)/`mergeEnvContentMcpConfig` (`@jini-ai/agent-runtime`'s `defs/opencode/mcp-config.ts`) can safely parse-merge-reserialize because
32
+ * their formats have a JS-native parser (`JSON.parse`); re-serializing parsed TOML would drop
33
+ * comments and layout (see `buildCodexMcpServerToml`'s doc), and every other setting a real Codex
34
+ * install carries — model choice, sandbox policy, the trusted-project list, the operator's own
35
+ * other MCP servers — must survive a spawn byte-for-byte. Only the one table this driver itself
36
+ * owns (`jini` is this integration's own reserved server name — see {@link JINI_MCP_SERVER_KEY}) is
37
+ * removed by default, via the narrow line-oriented scan above, never a full TOML parse. Explicit
38
+ * per-run OFF choices additionally omit personal MCP tables or retain only those tables when
39
+ * user settings are off. Inline root MCP declarations fail closed when isolation is requested,
40
+ * and `isolation.ts` parses the result to refuse any server or trust entry this line scan could not see.
41
+ * @param existingRaw - The real Codex home's `config.toml` content, or `undefined` when it does not
42
+ * exist (a fresh Codex install — degrades to "start from just this run's block", matching
43
+ * {@link mergeMcpJsonContent}'s own "missing file" handling).
44
+ * @param entry - The shared bridge entry.
45
+ * @returns The full text to write to the scratch `CODEX_HOME`'s `config.toml`.
46
+ * @complexity O(n) in the existing config's length.
47
+ */
48
+ export declare function buildCodexHomeConfigToml({ existingRaw, entry, inheritUserMcp, inheritUserSettings, toolApprovalOwner }: {
49
+ readonly existingRaw: string | undefined;
50
+ readonly entry: CodexBridgeEntry | CodexHttpEndpoint;
51
+ readonly inheritUserMcp?: boolean;
52
+ readonly inheritUserSettings?: boolean;
53
+ readonly toolApprovalOwner?: CodexToolApprovalOwner;
54
+ }, _optional?: Record<string, never>): string;
55
+ //# sourceMappingURL=home-config.d.ts.map
@@ -0,0 +1,224 @@
1
+ import { JINI_MCP_SERVER_KEY } from './contracts.js';
2
+ import { CodexMcpIsolationError } from './isolation.js';
3
+ /**
4
+ * TOML basic-string escaping for the narrow value shapes {@link buildCodexMcpServerToml} emits (a
5
+ * command name, an argv token, an env var value — never multi-line or control-character-heavy
6
+ * text). Escapes exactly what TOML's basic-string grammar requires: backslash first (so it is not
7
+ * re-escaped by a later replacement), then the quote delimiter, then the three whitespace control
8
+ * characters a real command/argv/env value could plausibly contain.
9
+ *
10
+ * A hand-rolled minimal escaper rather than a TOML serializer — this mechanism never needs to
11
+ * *re-serialize* TOML (the real install's existing `config.toml` is appended after, never
12
+ * rewritten — see {@link buildCodexHomeConfigToml}), so a full TOML writer for one serialization
13
+ * shape would be substantially more surface than the problem needs. The isolation check
14
+ * (`isolation.ts`) parses layers with smol-toml, but only reads them.
15
+ * @param value - The raw string to embed inside TOML `"..."` delimiters.
16
+ * @returns The escaped text, WITHOUT the surrounding quotes — {@link tomlString} adds those.
17
+ * @complexity O(n) in the string's length.
18
+ */
19
+ function escapeTomlBasicString(value) {
20
+ return value
21
+ .replace(/\\/g, '\\\\')
22
+ .replace(/"/g, '\\"')
23
+ .replace(/\n/g, '\\n')
24
+ .replace(/\r/g, '\\r')
25
+ .replace(/\t/g, '\\t');
26
+ }
27
+ /** Wraps {@link escapeTomlBasicString}'s output in the TOML basic-string delimiters. */
28
+ function tomlString(value) {
29
+ return `"${escapeTomlBasicString(value)}"`;
30
+ }
31
+ /** A TOML key: bare when TOML allows it, quoted otherwise — host-supplied bridge env names are not guaranteed bare-safe. */
32
+ export function tomlKey({ key }, _optional = {}) {
33
+ return /^[A-Za-z0-9_-]+$/.test(key) ? key : tomlString(key);
34
+ }
35
+ /**
36
+ * Codex's per-tool deadline for the Jini bridge, in seconds: `@jini-ai/mcp`'s
37
+ * `DEFAULT_DELEGATED_TOOL_TIMEOUT_MS` (6 min, mirrored because this package does not depend on
38
+ * that one) plus 40 s. Codex's own default (60 s) is shorter than a delegated call parked on a
39
+ * human dialog, and when Codex abandons a call the dialog stayed answerable, so a late click ran
40
+ * an action the model had been told failed. Outlasting the bridge's deadline means the bridge
41
+ * times out first, drops its daemon request, and the daemon expires the dialog. Codex does not
42
+ * pass the parent env through to MCP servers, so the bridge under Codex always runs at its default.
43
+ */
44
+ const CODEX_TOOL_TIMEOUT_SEC = 6 * 60 + 40;
45
+ /**
46
+ * Mechanism 5 of 5 — `'codex-toml'`'s serialization step. Builds the `[mcp_servers.jini]` TOML
47
+ * table (plus, when the entry carries any env vars, a separate `[mcp_servers.jini.env]` table)
48
+ * Codex's own config schema expects. An explicit HTTP endpoint instead writes `url` and
49
+ * literal `http_headers` through the same table replacement and escaping owners.
50
+ *
51
+ * Confirmed against a real installed Codex CLI (0.151.0), not assumed from docs: round-tripping
52
+ * `codex mcp add <name> --env K=V -- <cmd> <args>` against a scratch `CODEX_HOME` and reading back
53
+ * `config.toml` produced exactly this shape (`command`/`args` as TOML strings/array in the main
54
+ * table, env vars in a nested `.env` table) — see `archived provenance ledger` for the transcript.
55
+ * @param entry - A stdio bridge entry or an explicit run HTTP endpoint.
56
+ * @returns A TOML fragment with no leading/trailing blank-line padding — {@link buildCodexHomeConfigToml} owns spacing when combining it with existing content.
57
+ * @complexity O(n) in the number of argv/env entries.
58
+ * @overallScore 100/100
59
+ */
60
+ export function buildCodexMcpServerToml({ entry, toolApprovalOwner }, _options = {}) {
61
+ const approval = toolApprovalOwner === 'host' ? 'default_tools_approval_mode = "approve"\n' : '';
62
+ if ('url' in entry)
63
+ return buildCodexHttpMcpServerToml({ endpoint: entry }, { approval });
64
+ const argsLiteral = entry.args.map(tomlString).join(', ');
65
+ const serverTable = `[mcp_servers.${JINI_MCP_SERVER_KEY}]\ncommand = ${tomlString(entry.command)}\nargs = [${argsLiteral}]\n` +
66
+ `tool_timeout_sec = ${CODEX_TOOL_TIMEOUT_SEC}\n${approval}`;
67
+ const envLines = Object.entries(entry.env)
68
+ .filter((pair) => typeof pair[1] === 'string')
69
+ .map(([key, value]) => `${tomlKey({ key })} = ${tomlString(value)}`);
70
+ if (envLines.length === 0)
71
+ return serverTable;
72
+ return `${serverTable}\n[mcp_servers.${JINI_MCP_SERVER_KEY}.env]\n${envLines.join('\n')}\n`;
73
+ }
74
+ /** Literal headers keep the run token out of argv and bearer environment variables.
75
+ * @returns One HTTP table using the existing timeout and TOML escaping owner.
76
+ * @complexity O(endpoint bytes), without I/O.
77
+ */
78
+ function buildCodexHttpMcpServerToml({ endpoint }, { approval = '' } = {}) {
79
+ return `[mcp_servers.${JINI_MCP_SERVER_KEY}]\nurl = ${tomlString(endpoint.url)}\n` +
80
+ `tool_timeout_sec = ${CODEX_TOOL_TIMEOUT_SEC}\n${approval}\n[mcp_servers.${JINI_MCP_SERVER_KEY}.http_headers]\n` +
81
+ `Authorization = ${tomlString(`Bearer ${endpoint.token}`)}\n`;
82
+ }
83
+ /**
84
+ * Splits a TOML table header's dotted key into its individual segments, honoring quoted parts
85
+ * (`"basic"` or `'literal'`) that may themselves contain a literal `.` — a bare `.` only
86
+ * separates segments outside of quotes. Each segment is trimmed and, if quoted, unwrapped.
87
+ *
88
+ * Not a full TOML parser: it does not resolve escape sequences (`\"`, `\u...`) inside basic
89
+ * strings. That is deliberately out of scope — see {@link stripExistingJiniMcpServerTable}'s doc
90
+ * for why it is safe to skip for this specific comparison.
91
+ * @param rawKey - The raw text between a table header's `[` and `]`.
92
+ * @returns The dotted key's segments, dequoted and trimmed.
93
+ * @complexity O(n) in the length of `rawKey`.
94
+ */
95
+ function splitTomlDottedKey(rawKey) {
96
+ const scan = { segments: [], current: '', quote: null };
97
+ for (const ch of rawKey) {
98
+ if (scan.quote === null)
99
+ scanBareTomlKeyChar(scan, ch);
100
+ else if (ch === scan.quote)
101
+ scan.quote = null;
102
+ else
103
+ scan.current += ch;
104
+ }
105
+ scan.segments.push(scan.current.trim());
106
+ return scan.segments;
107
+ }
108
+ /** One key character outside quotes: opens a quote, ends the open segment at a `.`, or extends it. */
109
+ function scanBareTomlKeyChar(scan, ch) {
110
+ if (ch === '"' || ch === "'")
111
+ scan.quote = ch;
112
+ else if (ch === '.') {
113
+ scan.segments.push(scan.current.trim());
114
+ scan.current = '';
115
+ }
116
+ else
117
+ scan.current += ch;
118
+ }
119
+ // An inline or dotted root `mcp_servers` declaration, which the table scanner below cannot rewrite.
120
+ const INLINE_MCP_SERVERS = /^\s*(?:mcp_servers|"mcp_servers"|'mcp_servers')\s*[.=]/;
121
+ // `[<key>]` optionally followed only by a `# comment`; `[[...]]` never matches (see below).
122
+ const TOML_TABLE_HEADER = /^\s*\[([^[\]]+)\]\s*(#.*)?$/;
123
+ /**
124
+ * Whether {@link stripExistingJiniMcpServerTable} drops the table named `key`: always the jini
125
+ * table and its subtables; with `allServers` every MCP table and every `projects` (trust) table,
126
+ * so Codex loads no project layer that could add a server; with `mcpOnly` every non-MCP table.
127
+ */
128
+ function dropsTomlTable(key, optional) {
129
+ const jiniTableKey = `mcp_servers.${JINI_MCP_SERVER_KEY}`;
130
+ if (key === jiniTableKey || key.startsWith(`${jiniTableKey}.`))
131
+ return true;
132
+ const isMcp = key === 'mcp_servers' || key.startsWith('mcp_servers.');
133
+ if (optional.allServers === true && (isMcp || key === 'projects' || key.startsWith('projects.')))
134
+ return true;
135
+ return optional.mcpOnly === true && !isMcp;
136
+ }
137
+ /**
138
+ * Removes any pre-existing `[mcp_servers.{@link JINI_MCP_SERVER_KEY}]` table — and its
139
+ * `[mcp_servers.{@link JINI_MCP_SERVER_KEY}.*]` subtables (e.g. `.env`) — from a real Codex
140
+ * `config.toml`'s raw text, so {@link buildCodexHomeConfigToml} can append this run's own table
141
+ * without producing the duplicate TOML key Codex's parser rejects at startup.
142
+ *
143
+ * Line-oriented, not a real TOML parser (matching {@link buildCodexMcpServerToml}'s own
144
+ * no-TOML-dependency constraint), but wide enough to survive a hand-edited config, which is the
145
+ * scenario this whole function exists for. A table header line is recognized when, after
146
+ * trimming, it is `[<key>]` optionally followed only by a `# comment` (TOML's own grammar allows
147
+ * nothing else there) — so it tolerates leading indentation, whitespace inside the brackets, a
148
+ * trailing line comment, and a dotted key written with quoted segments (`["mcp_servers"."jini"]`),
149
+ * via {@link splitTomlDottedKey}. Once such a header's key matches the jini table or one of its
150
+ * subtables, every following line is dropped until the next table header (of any name) or EOF.
151
+ * Every other table, key, comment-only, and blank line is passed through untouched.
152
+ *
153
+ * Deliberately unhandled, and why it is safe to leave that way:
154
+ * - **Escape sequences inside quoted key segments** (e.g. a segment containing `\"`) — neither
155
+ * `mcp_servers` nor {@link JINI_MCP_SERVER_KEY} ever needs escaping, and this driver's own
156
+ * writer ({@link buildCodexMcpServerToml}) never emits a quoted form at all, so no real
157
+ * `config.toml` this driver produced can exercise this gap; a hand-edit that goes out of its
158
+ * way to escape a character inside a key that is supposed to spell "jini" would fail to match
159
+ * and fall back to today's pre-fix behavior (append a duplicate) rather than silently doing
160
+ * something worse.
161
+ * - **`[[array-of-tables]]` syntax** — Codex's schema has no array-of-tables shape for
162
+ * `mcp_servers`, and the header regex's `[^[\]]+` capture cannot match a line starting with a
163
+ * second `[`, so `[[mcp_servers.jini]]` is not recognized as a header before or after this fix
164
+ * — unchanged, not a new gap.
165
+ * - **A single quoted segment that happens to spell the same characters with the dot included**
166
+ * (e.g. `["mcp_servers.jini"]`, which in real TOML names one key literally containing a `.`,
167
+ * not two nested tables) — this collapses to the same joined string as the real nested-table
168
+ * spelling and is therefore treated as a match. This is a false positive in the conservative
169
+ * direction the reported bug calls for: a missed detection duplicates a key and crashes Codex,
170
+ * so on this axis over-matching a spelling nobody would plausibly hand-write for an MCP server
171
+ * table is preferable to under-matching the real one.
172
+ * @param existingRaw - The real Codex home's `config.toml` content, already known to be defined
173
+ * (callers pass `''` for a missing file).
174
+ * @returns `existingRaw` with any jini table/subtable removed.
175
+ * @complexity O(n) in the number of lines.
176
+ */
177
+ function stripExistingJiniMcpServerTable(existingRaw, optional = {}) {
178
+ const kept = [];
179
+ let skipping = optional.mcpOnly === true;
180
+ for (const line of existingRaw.split('\n')) {
181
+ // The existing table scanner cannot safely rewrite inline/dotted root server values. Refuse
182
+ // that uncommon shape when isolating servers rather than accidentally preserving a grant.
183
+ if (optional.allServers && INLINE_MCP_SERVERS.test(line)) {
184
+ throw new CodexMcpIsolationError('Cannot turn off personal MCP servers: the Codex config.toml declares mcp_servers inline (a dotted key or `mcp_servers = {...}`), which cannot be removed safely; move each server into its own [mcp_servers.<name>] table.');
185
+ }
186
+ const header = TOML_TABLE_HEADER.exec(line);
187
+ // The header's key capture group is not optional, so `header[1]` is always set on a match.
188
+ if (header)
189
+ skipping = dropsTomlTable(splitTomlDottedKey(header[1]).join('.'), optional);
190
+ if (!skipping)
191
+ kept.push(line);
192
+ }
193
+ return kept.join('\n');
194
+ }
195
+ /**
196
+ * Builds the full `config.toml` a run's scratch `CODEX_HOME` gets: the real Codex home's own
197
+ * config, with any pre-existing `[mcp_servers.jini]` table removed (see
198
+ * {@link stripExistingJiniMcpServerTable}), then this run's own table appended.
199
+ *
200
+ * **Append-only by design, not a parse-and-merge, for everything but the jini table itself.**
201
+ * `mergeMcpJsonContent` (`mcp-json-file.ts`)/`mergeEnvContentMcpConfig` (`@jini-ai/agent-runtime`'s `defs/opencode/mcp-config.ts`) can safely parse-merge-reserialize because
202
+ * their formats have a JS-native parser (`JSON.parse`); re-serializing parsed TOML would drop
203
+ * comments and layout (see `buildCodexMcpServerToml`'s doc), and every other setting a real Codex
204
+ * install carries — model choice, sandbox policy, the trusted-project list, the operator's own
205
+ * other MCP servers — must survive a spawn byte-for-byte. Only the one table this driver itself
206
+ * owns (`jini` is this integration's own reserved server name — see {@link JINI_MCP_SERVER_KEY}) is
207
+ * removed by default, via the narrow line-oriented scan above, never a full TOML parse. Explicit
208
+ * per-run OFF choices additionally omit personal MCP tables or retain only those tables when
209
+ * user settings are off. Inline root MCP declarations fail closed when isolation is requested,
210
+ * and `isolation.ts` parses the result to refuse any server or trust entry this line scan could not see.
211
+ * @param existingRaw - The real Codex home's `config.toml` content, or `undefined` when it does not
212
+ * exist (a fresh Codex install — degrades to "start from just this run's block", matching
213
+ * {@link mergeMcpJsonContent}'s own "missing file" handling).
214
+ * @param entry - The shared bridge entry.
215
+ * @returns The full text to write to the scratch `CODEX_HOME`'s `config.toml`.
216
+ * @complexity O(n) in the existing config's length.
217
+ */
218
+ export function buildCodexHomeConfigToml({ existingRaw, entry, inheritUserMcp = true, inheritUserSettings = true, toolApprovalOwner }, _optional = {}) {
219
+ const base = stripExistingJiniMcpServerTable(existingRaw ?? '', { allServers: !inheritUserMcp, mcpOnly: !inheritUserSettings });
220
+ const blockBreak = base.endsWith('\n') ? '\n' : '\n\n';
221
+ const separator = base.length === 0 ? '' : blockBreak;
222
+ return `${base}${separator}${buildCodexMcpServerToml({ entry, toolApprovalOwner })}`;
223
+ }
224
+ //# sourceMappingURL=home-config.js.map
@@ -0,0 +1,57 @@
1
+ import type { NativeCapabilities } from '@jini-ai/core/contracts/agents';
2
+ import type { CodexBridgeEntry, CodexHomeIo, CodexHttpEndpoint, CodexToolApprovalOwner, PreparedCodexHome } from './contracts.js';
3
+ export declare const CODEX_HOME_ENV = "CODEX_HOME";
4
+ /**
5
+ * Where `'codex-toml'` reads the operator's REAL Codex config from, to seed a run's scratch copy —
6
+ * never where it writes. Resolved against the daemon HOST process's own environment (`hostEnv`,
7
+ * `process.env` at the real call site), not a run's sandboxed spawn env: `CODEX_HOME` is not in
8
+ * `BASELINE_AGENT_ENV_KEYS`, so a spawned child never inherits it anyway, and the whole point here
9
+ * is finding wherever the *operator's actual* Codex install lives, which is a host-machine fact.
10
+ * @param hostEnv - The daemon process's own environment.
11
+ * @returns `hostEnv.CODEX_HOME` when set to a non-blank value (matching Codex's own resolution
12
+ * order), else the CLI's documented default, `~/.codex`.
13
+ * @complexity O(1).
14
+ * @overallScore 100/100
15
+ */
16
+ export declare function resolveSourceCodexHomeDir({ hostEnv }: {
17
+ readonly hostEnv: NodeJS.ProcessEnv;
18
+ }): string;
19
+ /**
20
+ * The child env pointed at a staged `CODEX_HOME`. Drops `CODEX_INTERNAL_ORIGINATOR_OVERRIDE`: a
21
+ * first-party originator lets a mentioned skill install and start MCP servers (codex-rs
22
+ * `mcp_skill_dependencies.rs`), and `codex exec` is `codex_exec` without it.
23
+ */
24
+ export declare function withStagedCodexHome({ env, codexHomeDir }: {
25
+ readonly env: NodeJS.ProcessEnv;
26
+ readonly codexHomeDir: string;
27
+ }, _options?: {}): NodeJS.ProcessEnv;
28
+ /** True when a Codex run turns off the operator's personal MCP servers or settings, which only a staged home can do. */
29
+ export declare function codexTurnsOffPersonalConfig({ nativeCapabilities }: {
30
+ readonly nativeCapabilities?: Partial<NativeCapabilities>;
31
+ }, _optional?: Record<string, never>): boolean;
32
+ export type CodexHomeStageResult = {
33
+ readonly kind: 'staged';
34
+ readonly home: PreparedCodexHome;
35
+ } | {
36
+ readonly kind: 'refused';
37
+ readonly message: string;
38
+ };
39
+ /**
40
+ * Phase 10b's effect for Codex: stages this run's scratch `CODEX_HOME` directory. An isolation refusal comes back as
41
+ * `refused` with the user-facing message; any other staging failure rejects, for the host to turn into a pre-spawn failure.
42
+ * Either way a partially staged directory is already removed by {@link prepareCodexHomeForRun}.
43
+ * @param input.entry - The stdio bridge entry, or the explicit run listener (same isolation, state links and cleanup).
44
+ * @param input.hostEnv - The daemon's own environment, passed in rather than read from `process.env` so staging stays testable with an injected env.
45
+ * @complexity O(1) plus {@link prepareCodexHomeForRun}'s own cost.
46
+ * @overallScore 100/100
47
+ */
48
+ export declare function stageCodexHome(input: {
49
+ readonly runId: string;
50
+ readonly entry: CodexBridgeEntry | CodexHttpEndpoint;
51
+ readonly nativeToolAccess?: boolean | undefined;
52
+ readonly nativeCapabilities?: Partial<NativeCapabilities>;
53
+ readonly hostEnv: NodeJS.ProcessEnv;
54
+ readonly io: CodexHomeIo;
55
+ readonly toolApprovalOwner?: CodexToolApprovalOwner;
56
+ }, _optional?: Record<string, never>): Promise<CodexHomeStageResult>;
57
+ //# sourceMappingURL=home-staging.d.ts.map