@jini-ai/agent-runtime 0.7.3-next.2 → 0.7.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/README.md +38 -0
- package/dist/agent-protocol/acp/models.d.ts +0 -10
- package/dist/agent-protocol/acp/models.js +0 -10
- package/dist/agent-protocol/acp/rpc.d.ts +5 -1
- package/dist/agent-protocol/acp/rpc.js +2 -1
- package/dist/agent-protocol/acp/session-permission.js +4 -3
- package/dist/agent-protocol/acp/session-results.d.ts +4 -4
- package/dist/agent-protocol/acp/session-results.js +30 -21
- package/dist/agent-protocol/acp/session-run.js +0 -8
- package/dist/agent-protocol/acp/session-types.d.ts +0 -1
- package/dist/agent-protocol/acp/session-usage.d.ts +12 -0
- package/dist/agent-protocol/acp/session-usage.js +29 -0
- package/dist/agent-protocol/acp/session.d.ts +1 -1
- package/dist/agent-protocol/acp/session.js +10 -4
- package/dist/agent-protocol/acp/text-suppression.js +75 -71
- package/dist/agent-protocol/pi-rpc/events.d.ts +21 -4
- package/dist/agent-protocol/pi-rpc/events.js +9 -9
- package/dist/agent-protocol/pi-rpc/internal.d.ts +6 -2
- package/dist/agent-protocol/pi-rpc/internal.js +6 -4
- package/dist/agent-protocol/pi-rpc/session.js +4 -3
- package/dist/anthropic-live-models.js +0 -0
- package/dist/claude-code-models.d.ts +3 -1
- package/dist/claude-code-models.js +4 -4
- package/dist/claude-stream-frames.js +1 -1
- package/dist/cli-probe-cache.d.ts +33 -0
- package/dist/cli-probe-cache.js +59 -0
- package/dist/custom-instructions.d.ts +107 -0
- package/dist/custom-instructions.js +80 -0
- package/dist/defs/{aider.d.ts → aider/index.d.ts} +2 -1
- package/dist/defs/{aider.js → aider/index.js} +6 -3
- package/dist/defs/amr/executable-env.d.ts +2 -0
- package/dist/defs/amr/executable-env.js +2 -0
- package/dist/defs/amr/executable-resolution.d.ts +5 -1
- package/dist/defs/amr/executable-resolution.js +1 -1
- package/dist/defs/antigravity/index.d.ts +1 -0
- package/dist/defs/antigravity/index.js +3 -0
- package/dist/defs/antigravity/permissions.d.ts +26 -0
- package/dist/defs/antigravity/permissions.js +66 -0
- package/dist/defs/{auggie.d.ts → auggie/index.d.ts} +1 -1
- package/dist/defs/{auggie.js → auggie/index.js} +3 -3
- package/dist/defs/claude/config-dir.d.ts +62 -0
- package/dist/defs/claude/config-dir.js +133 -0
- package/dist/defs/claude/filesystem.d.ts +33 -0
- package/dist/defs/claude/filesystem.js +30 -0
- package/dist/defs/{claude.d.ts → claude/index.d.ts} +1 -1
- package/dist/defs/{claude.js → claude/index.js} +9 -9
- package/dist/defs/claude/mcp-config.d.ts +22 -0
- package/dist/defs/claude/mcp-config.js +29 -0
- package/dist/defs/claude/mcp-delivery.d.ts +57 -0
- package/dist/defs/claude/mcp-delivery.js +75 -0
- package/dist/defs/claude/mcp-json.d.ts +34 -0
- package/dist/defs/claude/mcp-json.js +38 -0
- package/dist/defs/claude/subagent-start.d.ts +12 -0
- package/dist/defs/claude/subagent-start.js +35 -0
- package/dist/defs/{cline.d.ts → cline/index.d.ts} +1 -1
- package/dist/defs/{cline.js → cline/index.js} +3 -3
- package/dist/defs/codex/contracts.d.ts +47 -0
- package/dist/defs/codex/contracts.js +6 -0
- package/dist/defs/codex/event-stream.d.ts +5 -1
- package/dist/defs/codex/event-stream.js +29 -24
- package/dist/defs/codex/home-config.d.ts +55 -0
- package/dist/defs/codex/home-config.js +224 -0
- package/dist/defs/codex/home-staging.d.ts +57 -0
- package/dist/defs/codex/home-staging.js +184 -0
- package/dist/defs/{codex.d.ts → codex/index.d.ts} +2 -2
- package/dist/defs/{codex.js → codex/index.js} +3 -3
- package/dist/defs/codex/isolation.d.ts +29 -0
- package/dist/defs/codex/isolation.js +69 -0
- package/dist/defs/codex/launch.d.ts +4 -1
- package/dist/defs/codex/launch.js +1 -1
- package/dist/defs/codex/mcp-delivery.d.ts +8 -0
- package/dist/defs/codex/mcp-delivery.js +5 -0
- package/dist/defs/{crush.d.ts → crush/index.d.ts} +1 -1
- package/dist/defs/{crush.js → crush/index.js} +3 -3
- package/dist/defs/cursor-agent/event-stream.d.ts +5 -1
- package/dist/defs/cursor-agent/event-stream.js +14 -7
- package/dist/defs/{cursor-agent.d.ts → cursor-agent/index.d.ts} +1 -1
- package/dist/defs/{cursor-agent.js → cursor-agent/index.js} +4 -4
- package/dist/defs/{deepseek.d.ts → deepseek/index.d.ts} +2 -1
- package/dist/defs/{deepseek.js → deepseek/index.js} +6 -3
- package/dist/defs/{devin.d.ts → devin/index.d.ts} +1 -1
- package/dist/defs/{devin.js → devin/index.js} +3 -3
- package/dist/defs/{droid.d.ts → droid/index.d.ts} +1 -1
- package/dist/defs/{droid.js → droid/index.js} +3 -3
- package/dist/defs/gemini/event-stream.d.ts +5 -1
- package/dist/defs/gemini/event-stream.js +15 -12
- package/dist/defs/gemini/tool-calls.d.ts +7 -0
- package/dist/defs/gemini/tool-calls.js +9 -0
- package/dist/defs/{goose.d.ts → goose/index.d.ts} +1 -1
- package/dist/defs/{goose.js → goose/index.js} +3 -3
- package/dist/defs/{grok-build.d.ts → grok-build/index.d.ts} +1 -1
- package/dist/defs/{grok-build.js → grok-build/index.js} +3 -3
- package/dist/defs/index.d.ts +28 -28
- package/dist/defs/index.js +28 -28
- package/dist/defs/{kilo.d.ts → kilo/index.d.ts} +1 -1
- package/dist/defs/{kilo.js → kilo/index.js} +3 -3
- package/dist/defs/kimi/event-stream.d.ts +4 -1
- package/dist/defs/kimi/event-stream.js +6 -5
- package/dist/defs/{kimi.d.ts → kimi/index.d.ts} +1 -1
- package/dist/defs/{kimi.js → kimi/index.js} +3 -3
- package/dist/defs/{kiro.d.ts → kiro/index.d.ts} +1 -1
- package/dist/defs/{kiro.js → kiro/index.js} +3 -3
- package/dist/defs/mimo/constants.d.ts +2 -0
- package/dist/defs/mimo/constants.js +2 -0
- package/dist/defs/{mimo.d.ts → mimo/index.d.ts} +1 -1
- package/dist/defs/{mimo.js → mimo/index.js} +3 -3
- package/dist/defs/opencode/constants.d.ts +2 -0
- package/dist/defs/opencode/constants.js +2 -0
- package/dist/defs/opencode/event-stream.d.ts +5 -1
- package/dist/defs/opencode/event-stream.js +13 -11
- package/dist/defs/{opencode.d.ts → opencode/index.d.ts} +2 -2
- package/dist/defs/{opencode.js → opencode/index.js} +5 -5
- package/dist/defs/opencode/mcp-config.d.ts +108 -0
- package/dist/defs/opencode/mcp-config.js +119 -0
- package/dist/defs/opencode/model-discovery.d.ts +3 -1
- package/dist/defs/opencode/model-discovery.js +1 -1
- package/dist/defs/opencode/tool-calls.d.ts +7 -0
- package/dist/defs/opencode/tool-calls.js +12 -0
- package/dist/defs/{opencode-acp.d.ts → opencode-acp/index.d.ts} +2 -2
- package/dist/defs/{opencode-acp.js → opencode-acp/index.js} +4 -4
- package/dist/defs/{pi.d.ts → pi/index.d.ts} +1 -1
- package/dist/defs/{pi.js → pi/index.js} +3 -3
- package/dist/defs/pi/model-discovery.d.ts +4 -1
- package/dist/defs/pi/model-discovery.js +1 -1
- package/dist/defs/{qoder.d.ts → qoder/index.d.ts} +1 -1
- package/dist/defs/{qoder.js → qoder/index.js} +3 -3
- package/dist/defs/{qwen.d.ts → qwen/index.d.ts} +1 -1
- package/dist/defs/{qwen.js → qwen/index.js} +3 -3
- package/dist/defs/{reasonix.d.ts → reasonix/index.d.ts} +1 -1
- package/dist/defs/{reasonix.js → reasonix/index.js} +3 -3
- package/dist/defs/{trae-cli.d.ts → trae-cli/index.d.ts} +1 -1
- package/dist/defs/{trae-cli.js → trae-cli/index.js} +3 -3
- package/dist/defs/{vibe.d.ts → vibe/index.d.ts} +1 -1
- package/dist/defs/{vibe.js → vibe/index.js} +3 -3
- package/dist/executables.js +1 -1
- package/dist/inventory/index.d.ts +61 -0
- package/dist/inventory/index.js +45 -0
- package/dist/json-event-stream-shared.d.ts +10 -2
- package/dist/json-event-stream-shared.js +21 -13
- package/dist/json-event-stream.js +6 -5
- package/dist/launch.js +1 -1
- package/dist/model-catalog-live-discovery.d.ts +103 -0
- package/dist/model-catalog-live-discovery.js +111 -0
- package/dist/model-discovery-adapters.d.ts +6 -1
- package/dist/model-discovery-adapters.js +4 -3
- package/dist/model-discovery-config.js +1 -1
- package/dist/native-permissions.d.ts +19 -0
- package/dist/native-permissions.js +22 -0
- package/dist/providers/anthropic-messages.js +3 -2
- package/dist/providers/connection-guard.js +99 -84
- package/dist/providers/connection-test.js +0 -5
- package/dist/providers/google-messages.js +1 -1
- package/dist/providers/oauth-provider.d.ts +1 -23
- package/dist/providers/oauth-provider.js +1 -35
- package/dist/providers/openai-chat-request.js +1 -1
- package/dist/providers/tool-loop-verdict.d.ts +1 -0
- package/dist/providers/tool-loop-verdict.js +4 -1
- package/dist/providers/tool-turn-types.d.ts +12 -9
- package/dist/providers/tool-turn.d.ts +63 -1
- package/dist/providers/tool-turn.js +67 -1
- package/dist/qoder-stream.js +66 -66
- package/dist/role-marker-guard.js +49 -30
- package/dist/runtime-def-binding.js +1 -1
- package/dist/runtime-port-bindings.d.ts +82 -0
- package/dist/runtime-port-bindings.js +4 -1
- package/dist/runtime-strategies.d.ts +100 -0
- package/dist/runtime-strategies.js +129 -0
- package/package.json +44 -10
- package/dist/defs/amp.d.ts +0 -2
- package/dist/defs/amp.js +0 -2
- package/dist/defs/amr.d.ts +0 -2
- package/dist/defs/amr.js +0 -2
- package/dist/defs/codebuddy.d.ts +0 -2
- package/dist/defs/codebuddy.js +0 -2
- package/dist/defs/hermes.d.ts +0 -2
- package/dist/defs/hermes.js +0 -2
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { promises as fsPromises } from 'node:fs';
|
|
2
|
+
function isRecord(value) {
|
|
3
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Merges the bridge's entry (under `serverName`) into an existing `.mcp.json`'s `mcpServers` map, preserving
|
|
7
|
+
* every other key and every other registered server untouched. A missing (`existingRaw ===
|
|
8
|
+
* undefined`), empty, or unparseable-as-a-JSON-object existing file all degrade to "start from an
|
|
9
|
+
* empty document" rather than throwing — an unparseable project `.mcp.json` is a pre-existing
|
|
10
|
+
* problem this driver did not create and cannot safely repair, so it is deliberately overwritten
|
|
11
|
+
* with a fresh, valid file containing just this run's bridge entry rather than left broken or
|
|
12
|
+
* left blocking the run. Pure — no I/O — so every branch is directly assertable.
|
|
13
|
+
* @complexity O(1) plus `JSON.parse`/`JSON.stringify`'s own cost on a small config file.
|
|
14
|
+
* @overallScore 100/100
|
|
15
|
+
*/
|
|
16
|
+
export function mergeMcpJsonContent({ existingRaw, serverEntry, serverName }) {
|
|
17
|
+
let doc = {};
|
|
18
|
+
if (existingRaw !== undefined) {
|
|
19
|
+
try {
|
|
20
|
+
const parsed = JSON.parse(existingRaw);
|
|
21
|
+
if (isRecord(parsed))
|
|
22
|
+
doc = parsed;
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
doc = {};
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
const existingServers = isRecord(doc.mcpServers) ? doc.mcpServers : {};
|
|
29
|
+
const mcpServers = { ...existingServers, [serverName]: serverEntry };
|
|
30
|
+
return `${JSON.stringify({ ...doc, mcpServers }, null, 2)}\n`;
|
|
31
|
+
}
|
|
32
|
+
export function defaultReadMcpJsonFile({ path }) {
|
|
33
|
+
return fsPromises.readFile(path, 'utf8');
|
|
34
|
+
}
|
|
35
|
+
export function defaultWriteMcpJsonFile({ path, content }) {
|
|
36
|
+
return fsPromises.writeFile(path, content, 'utf8');
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=mcp-json.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** Give each child a short load instruction; long approved ID lists remain complete on disk. */
|
|
2
|
+
export declare function prepareClaudeSubagentStartSettings({ directory, context, settings }: {
|
|
3
|
+
directory: string;
|
|
4
|
+
context: {
|
|
5
|
+
ids: readonly string[];
|
|
6
|
+
instructions: string;
|
|
7
|
+
};
|
|
8
|
+
settings?: string;
|
|
9
|
+
}, { platform }?: {
|
|
10
|
+
platform?: NodeJS.Platform;
|
|
11
|
+
}): Promise<string>;
|
|
12
|
+
//# sourceMappingURL=subagent-start.d.ts.map
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { writeFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
/** Give each child a short load instruction; long approved ID lists remain complete on disk. */
|
|
4
|
+
export async function prepareClaudeSubagentStartSettings({ directory, context, settings }, { platform = process.platform } = {}) {
|
|
5
|
+
const existing = JSON.parse(settings || '{}');
|
|
6
|
+
const additionalContext = await subagentStartContext({ directory, context });
|
|
7
|
+
const path = join(directory, 'subagent-start.json');
|
|
8
|
+
await writeFile(path, JSON.stringify({
|
|
9
|
+
hookSpecificOutput: { hookEventName: 'SubagentStart', additionalContext },
|
|
10
|
+
}), { encoding: 'utf8', mode: 0o600, flag: 'wx' });
|
|
11
|
+
const hook = printFileHook({ path, platform });
|
|
12
|
+
return JSON.stringify({ ...existing, hooks: { ...existing.hooks,
|
|
13
|
+
SubagentStart: [...(existing.hooks?.SubagentStart ?? []), hook],
|
|
14
|
+
} });
|
|
15
|
+
}
|
|
16
|
+
/** The start context inlines the IDs, or points at a manifest file when inlining would pass 2000 characters. */
|
|
17
|
+
async function subagentStartContext({ directory, context }, _optional = {}) {
|
|
18
|
+
const ids = JSON.stringify(context.ids);
|
|
19
|
+
let additionalContext = `Parent plugins: ${ids}.\n${context.instructions}`;
|
|
20
|
+
if (additionalContext.length >= 2000) {
|
|
21
|
+
const manifest = join(directory, 'subagent-plugin-ids.json');
|
|
22
|
+
additionalContext = `Parent plugins: read ${JSON.stringify(manifest)} before continuing. Apply these instructions to every ID in that manifest.\n${context.instructions}`;
|
|
23
|
+
if (additionalContext.length >= 2000)
|
|
24
|
+
throw new Error('Subagent startup context must be shorter than 2000 characters.');
|
|
25
|
+
await writeFile(manifest, ids, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
|
|
26
|
+
}
|
|
27
|
+
return additionalContext;
|
|
28
|
+
}
|
|
29
|
+
/** A command hook that prints the file at `path`, quoted for this platform's shell. */
|
|
30
|
+
function printFileHook({ path, platform }, _optional = {}) {
|
|
31
|
+
const quoted = platform === 'win32' ? path.replace(/['\u2018-\u201B]/g, '$&$&') : path.replaceAll("'", "'\\''");
|
|
32
|
+
const command = platform === 'win32' ? `Get-Content -Raw -Encoding UTF8 -LiteralPath '${quoted}'` : `cat -- '${quoted}'`;
|
|
33
|
+
return { hooks: [{ type: 'command', command, timeout: 5, ...(platform === 'win32' ? { shell: 'powershell' } : {}) }] };
|
|
34
|
+
}
|
|
35
|
+
//# sourceMappingURL=subagent-start.js.map
|
|
@@ -30,4 +30,4 @@ export declare const clineAgentDef: {
|
|
|
30
30
|
deps?: import("@jini-ai/core/contracts/agents").ModelDiscoveryDeps;
|
|
31
31
|
}): Promise<import("@jini-ai/core/contracts/agents").DefaultModelResolution>;
|
|
32
32
|
};
|
|
33
|
-
//# sourceMappingURL=
|
|
33
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createAgentModelDiscovery } from '
|
|
1
|
+
import { createAgentModelDiscovery } from '../../model-discovery-native.js';
|
|
2
2
|
/**
|
|
3
3
|
* @module defs/cline
|
|
4
4
|
*
|
|
@@ -9,7 +9,7 @@ import { createAgentModelDiscovery } from '../model-discovery-native.js';
|
|
|
9
9
|
* sign-in failed with "Authentication required: Call authenticate before starting a session",
|
|
10
10
|
* which `auth.ts`'s generic classifier already reads as a missing sign-in (fix: `cline auth`).
|
|
11
11
|
*/
|
|
12
|
-
import { acpModelFetcher, DEFAULT_MODEL_OPTION } from '
|
|
12
|
+
import { acpModelFetcher, DEFAULT_MODEL_OPTION } from '../shared.js';
|
|
13
13
|
export const clineAgentDef = {
|
|
14
14
|
// UNVERIFIED live integration locally; source/category and limits are documented in model-discovery-adapters.ts.
|
|
15
15
|
...createAgentModelDiscovery('cline', { fallbackModels: () => clineAgentDef.fallbackModels }),
|
|
@@ -26,4 +26,4 @@ export const clineAgentDef = {
|
|
|
26
26
|
// `acp-json-rpc` def — see `types.ts#RuntimeAgentDef.imageDelivery`'s doc.
|
|
27
27
|
imageDelivery: 'native',
|
|
28
28
|
};
|
|
29
|
-
//# sourceMappingURL=
|
|
29
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** A staged, run-scoped Codex `CODEX_HOME` — the directory-holding analogue of {@link PreparedPromptFile}/{@link PreparedAgentLogFile} from `@jini-ai/agent-runtime`. */
|
|
2
|
+
export type PreparedCodexHome = {
|
|
3
|
+
/** Absolute path to hand to the spawned child as its `CODEX_HOME` env var. */
|
|
4
|
+
readonly path: string;
|
|
5
|
+
/** Recursively removes the staged directory — the live `auth.json` copy it may hold makes this a confidentiality cleanup, not just tidiness. Safe to call more than once. */
|
|
6
|
+
readonly cleanup: () => Promise<void>;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* The bridge server's name in the staged `config.toml`. It must equal the host's own bridge key (the daemon's
|
|
10
|
+
* `JINI_MCP_SERVER_KEY`, passed to the slot as `serverName`); the daemon seam test pins that the two agree.
|
|
11
|
+
*/
|
|
12
|
+
export declare const JINI_MCP_SERVER_KEY = "jini";
|
|
13
|
+
/** The stdio bridge entry the host built, as the staged config needs it. */
|
|
14
|
+
export interface CodexBridgeEntry {
|
|
15
|
+
readonly command: string;
|
|
16
|
+
readonly args: readonly string[];
|
|
17
|
+
readonly env: Readonly<Record<string, string>>;
|
|
18
|
+
}
|
|
19
|
+
/** A private per-run HTTP listener: its URL and the bearer token that authorizes it. */
|
|
20
|
+
export type CodexHttpEndpoint = {
|
|
21
|
+
readonly url: string;
|
|
22
|
+
readonly token: string;
|
|
23
|
+
};
|
|
24
|
+
export type CodexToolApprovalOwner = 'host' | undefined;
|
|
25
|
+
/** The run-scoped filesystem seams staging uses: read/write are always supplied by the host, the rest default to the real filesystem. */
|
|
26
|
+
export interface CodexHomeIo {
|
|
27
|
+
readonly readFile: ({ path }: {
|
|
28
|
+
readonly path: string;
|
|
29
|
+
}) => Promise<string>;
|
|
30
|
+
readonly writeFile: ({ path, content }: {
|
|
31
|
+
readonly path: string;
|
|
32
|
+
readonly content: string;
|
|
33
|
+
}) => Promise<void>;
|
|
34
|
+
readonly mkdtemp?: ({ prefix }: {
|
|
35
|
+
readonly prefix: string;
|
|
36
|
+
}) => Promise<string>;
|
|
37
|
+
readonly removeDir?: ({ path }: {
|
|
38
|
+
readonly path: string;
|
|
39
|
+
}) => Promise<void>;
|
|
40
|
+
readonly linkSessionStore?: (required: {
|
|
41
|
+
runHome: string;
|
|
42
|
+
sourceHome: string;
|
|
43
|
+
}, optional?: {
|
|
44
|
+
inheritUserConfig?: boolean;
|
|
45
|
+
}) => Promise<void>;
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=contracts.d.ts.map
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The bridge server's name in the staged `config.toml`. It must equal the host's own bridge key (the daemon's
|
|
3
|
+
* `JINI_MCP_SERVER_KEY`, passed to the slot as `serverName`); the daemon seam test pins that the two agree.
|
|
4
|
+
*/
|
|
5
|
+
export const JINI_MCP_SERVER_KEY = 'jini';
|
|
6
|
+
//# sourceMappingURL=contracts.js.map
|
|
@@ -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:
|
|
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 (
|
|
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 (
|
|
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
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
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 =
|
|
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(
|
|
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 =
|
|
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(
|
|
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
|
-
|
|
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
|
-
|
|
336
|
+
const usage = getRecord({ value: obj.usage });
|
|
337
|
+
if (!usage)
|
|
334
338
|
return false;
|
|
335
|
-
onEvent({ type: 'usage', usage: pickUsage({ source:
|
|
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
|
-
|
|
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
|