@finalai/acp-adapter-codex 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/HOSTING.md +363 -0
- package/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +57 -2
- package/dist/modules/app-server.d.mts +11 -0
- package/dist/modules/app-server.mjs +69 -0
- package/dist/modules/app-server.mjs.map +7 -0
- package/dist/modules/cli.d.mts +2 -0
- package/dist/modules/cli.mjs +61 -0
- package/dist/modules/cli.mjs.map +7 -0
- package/dist/modules/config.d.mts +43 -0
- package/dist/modules/config.mjs +170 -0
- package/dist/modules/config.mjs.map +7 -0
- package/dist/modules/index.d.mts +4 -0
- package/dist/modules/index.mjs +12 -0
- package/dist/modules/index.mjs.map +7 -0
- package/dist/modules/json-rpc.d.mts +52 -0
- package/dist/modules/json-rpc.mjs +131 -0
- package/dist/modules/json-rpc.mjs.map +7 -0
- package/dist/modules/jsonl.d.mts +1 -0
- package/dist/modules/jsonl.mjs +20 -0
- package/dist/modules/jsonl.mjs.map +7 -0
- package/dist/modules/program.d.mts +16 -0
- package/dist/modules/program.mjs +50 -0
- package/dist/modules/program.mjs.map +7 -0
- package/dist/modules/session.d.mts +20 -0
- package/dist/modules/session.mjs +500 -0
- package/dist/modules/session.mjs.map +7 -0
- package/dist/modules/translate.d.mts +37 -0
- package/dist/modules/translate.mjs +504 -0
- package/dist/modules/translate.mjs.map +7 -0
- package/package.json +45 -4
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
const jsonlRecords = async function* (chunks) {
|
|
2
|
+
const maxRecordBytes = 32 * 1024 * 1024;
|
|
3
|
+
let buffer = "";
|
|
4
|
+
for await (const chunk of chunks) {
|
|
5
|
+
buffer += String(chunk);
|
|
6
|
+
let newline;
|
|
7
|
+
while ((newline = buffer.indexOf("\n")) >= 0) {
|
|
8
|
+
const line = buffer.slice(0, newline).replace(/\r$/u, "");
|
|
9
|
+
buffer = buffer.slice(newline + 1);
|
|
10
|
+
if (Buffer.byteLength(line) > maxRecordBytes) throw new Error("Native RPC record too large");
|
|
11
|
+
if (line.trim() !== "") yield line;
|
|
12
|
+
}
|
|
13
|
+
if (Buffer.byteLength(buffer) > maxRecordBytes) throw new Error("Native RPC record too large");
|
|
14
|
+
}
|
|
15
|
+
if (buffer.trim() !== "") throw new Error("Native RPC exited with an incomplete JSON record");
|
|
16
|
+
};
|
|
17
|
+
export {
|
|
18
|
+
jsonlRecords
|
|
19
|
+
};
|
|
20
|
+
//# sourceMappingURL=jsonl.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/jsonl.ts"],
|
|
4
|
+
"sourcesContent": ["// App-server records are LF-delimited, including when strings contain Unicode separators.\nexport const jsonlRecords = async function* (\n chunks: AsyncIterable<string | Buffer>,\n): AsyncGenerator<string> {\n const maxRecordBytes = 32 * 1024 * 1024;\n let buffer = '';\n for await (const chunk of chunks) {\n buffer += String(chunk);\n let newline: number;\n while ((newline = buffer.indexOf('\\n')) >= 0) {\n const line = buffer.slice(0, newline).replace(/\\r$/u, '');\n buffer = buffer.slice(newline + 1);\n if (Buffer.byteLength(line) > maxRecordBytes) throw new Error('Native RPC record too large');\n if (line.trim() !== '') yield line;\n }\n if (Buffer.byteLength(buffer) > maxRecordBytes) throw new Error('Native RPC record too large');\n }\n if (buffer.trim() !== '') throw new Error('Native RPC exited with an incomplete JSON record');\n};\n"],
|
|
5
|
+
"mappings": "AACO,MAAM,eAAe,iBAC1B,QACwB;AACxB,QAAM,iBAAiB,KAAK,OAAO;AACnC,MAAI,SAAS;AACb,mBAAiB,SAAS,QAAQ;AAChC,cAAU,OAAO,KAAK;AACtB,QAAI;AACJ,YAAQ,UAAU,OAAO,QAAQ,IAAI,MAAM,GAAG;AAC5C,YAAM,OAAO,OAAO,MAAM,GAAG,OAAO,EAAE,QAAQ,QAAQ,EAAE;AACxD,eAAS,OAAO,MAAM,UAAU,CAAC;AACjC,UAAI,OAAO,WAAW,IAAI,IAAI,eAAgB,OAAM,IAAI,MAAM,6BAA6B;AAC3F,UAAI,KAAK,KAAK,MAAM,GAAI,OAAM;AAAA,IAChC;AACA,QAAI,OAAO,WAAW,MAAM,IAAI,eAAgB,OAAM,IAAI,MAAM,6BAA6B;AAAA,EAC/F;AACA,MAAI,OAAO,KAAK,MAAM,GAAI,OAAM,IAAI,MAAM,kDAAkD;AAC9F;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { AdapterProgramIface } from '@finalai/acp-session/agent';
|
|
2
|
+
import { type SpawnAppServer } from "./app-server.mjs";
|
|
3
|
+
import { CodexApprovalPolicy } from "./config.mjs";
|
|
4
|
+
export declare const ADAPTER_NAME = "acp-adapter-codex";
|
|
5
|
+
export declare const ADAPTER_VERSION = "0.1.1";
|
|
6
|
+
export interface CodexProgramOptionsIface {
|
|
7
|
+
command?: {
|
|
8
|
+
command: string;
|
|
9
|
+
args: string[];
|
|
10
|
+
} | null;
|
|
11
|
+
approvalPolicy?: CodexApprovalPolicy;
|
|
12
|
+
env?: Record<string, string | undefined>;
|
|
13
|
+
spawnAppServer?: SpawnAppServer;
|
|
14
|
+
closeGraceMs?: number;
|
|
15
|
+
}
|
|
16
|
+
export declare const createCodexProgram: (options?: CodexProgramOptionsIface) => AdapterProgramIface;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { spawnCodexAppServer } from "./app-server.mjs";
|
|
4
|
+
import {
|
|
5
|
+
CodexApprovalPolicy,
|
|
6
|
+
codexConfigOptions,
|
|
7
|
+
codexConfigValue,
|
|
8
|
+
defaultCodexConfig
|
|
9
|
+
} from "./config.mjs";
|
|
10
|
+
import { assertDistinctMcpNames, forkCodexThread, openCodexSession } from "./session.mjs";
|
|
11
|
+
const ADAPTER_NAME = "acp-adapter-codex";
|
|
12
|
+
const ADAPTER_VERSION = "0.1.1";
|
|
13
|
+
const bundledCodex = () => {
|
|
14
|
+
const manifest = createRequire(import.meta.url).resolve("@openai/codex/package.json");
|
|
15
|
+
return {
|
|
16
|
+
command: process.execPath,
|
|
17
|
+
args: [join(dirname(manifest), "bin", "codex.js"), "app-server"]
|
|
18
|
+
};
|
|
19
|
+
};
|
|
20
|
+
const createCodexProgram = (options = {}) => {
|
|
21
|
+
const command = options.command ?? bundledCodex();
|
|
22
|
+
const deps = {
|
|
23
|
+
spawnAppServer: options.spawnAppServer ?? spawnCodexAppServer,
|
|
24
|
+
command: command.command,
|
|
25
|
+
args: command.args,
|
|
26
|
+
env: options.env ?? process.env,
|
|
27
|
+
version: ADAPTER_VERSION,
|
|
28
|
+
closeGraceMs: options.closeGraceMs ?? 1e4
|
|
29
|
+
};
|
|
30
|
+
return {
|
|
31
|
+
info: { name: ADAPTER_NAME, version: ADAPTER_VERSION },
|
|
32
|
+
program: "codex",
|
|
33
|
+
runtime: { name: ADAPTER_NAME, version: ADAPTER_VERSION },
|
|
34
|
+
fork: true,
|
|
35
|
+
mcp: { http: true, stdio: true, acp: true },
|
|
36
|
+
images: true,
|
|
37
|
+
defaultConfig: () => defaultCodexConfig(options.approvalPolicy),
|
|
38
|
+
configOptions: codexConfigOptions,
|
|
39
|
+
configValue: codexConfigValue,
|
|
40
|
+
checkMcpServers: (servers) => assertDistinctMcpNames(servers.map((server) => String(server.name))),
|
|
41
|
+
forkNative: (args) => forkCodexThread(args, deps),
|
|
42
|
+
open: (args) => openCodexSession(args, deps)
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
export {
|
|
46
|
+
ADAPTER_NAME,
|
|
47
|
+
ADAPTER_VERSION,
|
|
48
|
+
createCodexProgram
|
|
49
|
+
};
|
|
50
|
+
//# sourceMappingURL=program.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/program.ts"],
|
|
4
|
+
"sourcesContent": ["import { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\n\nimport type { AdapterProgramIface } from '@finalai/acp-session/agent';\n\nimport { spawnCodexAppServer, type SpawnAppServer } from \"./app-server.mjs\";\nimport {\n CodexApprovalPolicy,\n codexConfigOptions,\n codexConfigValue,\n defaultCodexConfig,\n} from \"./config.mjs\";\nimport { assertDistinctMcpNames, forkCodexThread, openCodexSession } from \"./session.mjs\";\n\nexport const ADAPTER_NAME = 'acp-adapter-codex';\nexport const ADAPTER_VERSION = '0.1.1';\n\nexport interface CodexProgramOptionsIface {\n // The app-server's command line (`codex app-server ...`); by default the Codex the\n // `@openai/codex` dependency installs.\n command?: { command: string; args: string[] } | null;\n // The approval policy a new session starts with.\n approvalPolicy?: CodexApprovalPolicy;\n // Environment of the app-server, inference credentials included (OPENAI_API_KEY and\n // OPENAI_BASE_URL, or CODEX_HOME for Codex's own login).\n env?: Record<string, string | undefined>;\n spawnAppServer?: SpawnAppServer;\n closeGraceMs?: number;\n}\n\n// The Codex CLI the dependency installs, run with this Node.\nconst bundledCodex = (): { command: string; args: string[] } => {\n const manifest = createRequire(import.meta.url).resolve('@openai/codex/package.json');\n return {\n command: process.execPath,\n args: [join(dirname(manifest), 'bin', 'codex.js'), 'app-server'],\n };\n};\n\n// The Codex app-server as the native program of an ACP adapter.\nexport const createCodexProgram = (options: CodexProgramOptionsIface = {}): AdapterProgramIface => {\n const command = options.command ?? bundledCodex();\n const deps = {\n spawnAppServer: options.spawnAppServer ?? spawnCodexAppServer,\n command: command.command,\n args: command.args,\n env: options.env ?? process.env,\n version: ADAPTER_VERSION,\n closeGraceMs: options.closeGraceMs ?? 10_000,\n };\n return {\n info: { name: ADAPTER_NAME, version: ADAPTER_VERSION },\n program: 'codex',\n runtime: { name: ADAPTER_NAME, version: ADAPTER_VERSION },\n fork: true,\n mcp: { http: true, stdio: true, acp: true },\n images: true,\n defaultConfig: () => defaultCodexConfig(options.approvalPolicy),\n configOptions: codexConfigOptions,\n configValue: codexConfigValue,\n checkMcpServers: (servers) =>\n assertDistinctMcpNames(servers.map((server) => String(server.name))),\n forkNative: (args) => forkCodexThread(args, deps),\n open: (args) => openCodexSession(args, deps),\n };\n};\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,qBAAqB;AAC9B,SAAS,SAAS,YAAY;AAI9B,SAAS,2BAAgD;AACzD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,wBAAwB,iBAAiB,wBAAwB;AAEnE,MAAM,eAAe;AACrB,MAAM,kBAAkB;AAgB/B,MAAM,eAAe,MAA2C;AAC9D,QAAM,WAAW,cAAc,YAAY,GAAG,EAAE,QAAQ,4BAA4B;AACpF,SAAO;AAAA,IACL,SAAS,QAAQ;AAAA,IACjB,MAAM,CAAC,KAAK,QAAQ,QAAQ,GAAG,OAAO,UAAU,GAAG,YAAY;AAAA,EACjE;AACF;AAGO,MAAM,qBAAqB,CAAC,UAAoC,CAAC,MAA2B;AACjG,QAAM,UAAU,QAAQ,WAAW,aAAa;AAChD,QAAM,OAAO;AAAA,IACX,gBAAgB,QAAQ,kBAAkB;AAAA,IAC1C,SAAS,QAAQ;AAAA,IACjB,MAAM,QAAQ;AAAA,IACd,KAAK,QAAQ,OAAO,QAAQ;AAAA,IAC5B,SAAS;AAAA,IACT,cAAc,QAAQ,gBAAgB;AAAA,EACxC;AACA,SAAO;AAAA,IACL,MAAM,EAAE,MAAM,cAAc,SAAS,gBAAgB;AAAA,IACrD,SAAS;AAAA,IACT,SAAS,EAAE,MAAM,cAAc,SAAS,gBAAgB;AAAA,IACxD,MAAM;AAAA,IACN,KAAK,EAAE,MAAM,MAAM,OAAO,MAAM,KAAK,KAAK;AAAA,IAC1C,QAAQ;AAAA,IACR,eAAe,MAAM,mBAAmB,QAAQ,cAAc;AAAA,IAC9D,eAAe;AAAA,IACf,aAAa;AAAA,IACb,iBAAiB,CAAC,YAChB,uBAAuB,QAAQ,IAAI,CAAC,WAAW,OAAO,OAAO,IAAI,CAAC,CAAC;AAAA,IACrE,YAAY,CAAC,SAAS,gBAAgB,MAAM,IAAI;AAAA,IAChD,MAAM,CAAC,SAAS,iBAAiB,MAAM,IAAI;AAAA,EAC7C;AACF;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type McpServerHttp } from '@agentclientprotocol/sdk/experimental/v2';
|
|
2
|
+
import { type JsonObject } from '@finalai/acp-session';
|
|
3
|
+
import type { AdapterOpenArgsIface, AdapterSessionIface } from '@finalai/acp-session/agent';
|
|
4
|
+
import type { SpawnAppServer } from "./app-server.mjs";
|
|
5
|
+
export interface CodexSessionDepsIface {
|
|
6
|
+
spawnAppServer: SpawnAppServer;
|
|
7
|
+
command: string;
|
|
8
|
+
args: string[];
|
|
9
|
+
env: Record<string, string | undefined>;
|
|
10
|
+
version: string;
|
|
11
|
+
closeGraceMs: number;
|
|
12
|
+
}
|
|
13
|
+
export declare const assertDistinctMcpNames: (names: readonly string[]) => void;
|
|
14
|
+
export declare const mcpOverrides: (servers: readonly McpServerHttp[]) => JsonObject;
|
|
15
|
+
export declare const forkCodexThread: (args: {
|
|
16
|
+
nativeId: string;
|
|
17
|
+
cwd: string;
|
|
18
|
+
config: Record<string, string>;
|
|
19
|
+
}, deps: CodexSessionDepsIface) => Promise<string>;
|
|
20
|
+
export declare const openCodexSession: (args: AdapterOpenArgsIface, deps: CodexSessionDepsIface) => Promise<AdapterSessionIface>;
|
|
@@ -0,0 +1,500 @@
|
|
|
1
|
+
import {
|
|
2
|
+
} from "@agentclientprotocol/sdk/experimental/v2";
|
|
3
|
+
import {
|
|
4
|
+
jsonObjectSchema,
|
|
5
|
+
jsonValueSchema,
|
|
6
|
+
StopReason
|
|
7
|
+
} from "@finalai/acp-session";
|
|
8
|
+
import { startMcpProxy } from "@finalai/acp-session/agent/node";
|
|
9
|
+
import * as z from "zod";
|
|
10
|
+
import {
|
|
11
|
+
CodexApprovalPolicy,
|
|
12
|
+
configFlags,
|
|
13
|
+
providerOverrides,
|
|
14
|
+
turnConfigOf
|
|
15
|
+
} from "./config.mjs";
|
|
16
|
+
import {
|
|
17
|
+
createJsonRpcPeer,
|
|
18
|
+
errorMessageOf
|
|
19
|
+
} from "./json-rpc.mjs";
|
|
20
|
+
import {
|
|
21
|
+
createTranslatorState,
|
|
22
|
+
translateCodexNotification
|
|
23
|
+
} from "./translate.mjs";
|
|
24
|
+
const threadResponseSchema = z.object({ thread: z.object({ id: z.string().min(1) }) });
|
|
25
|
+
const turnResponseSchema = z.object({ turn: z.object({ id: z.string().min(1) }) });
|
|
26
|
+
const turnSteerResponseSchema = z.object({ turnId: z.string().min(1) });
|
|
27
|
+
const approvalParamsSchema = z.object({
|
|
28
|
+
itemId: z.string().optional(),
|
|
29
|
+
command: z.string().nullish(),
|
|
30
|
+
cwd: z.string().nullish(),
|
|
31
|
+
reason: z.string().nullish()
|
|
32
|
+
});
|
|
33
|
+
const elicitationParamsSchema = z.object({
|
|
34
|
+
mode: z.string().optional(),
|
|
35
|
+
message: z.string().default(""),
|
|
36
|
+
serverName: z.string().optional()
|
|
37
|
+
}).loose();
|
|
38
|
+
const userInputParamsSchema = z.object({
|
|
39
|
+
itemId: z.string(),
|
|
40
|
+
questions: z.array(
|
|
41
|
+
z.object({
|
|
42
|
+
id: z.string().min(1),
|
|
43
|
+
header: z.string(),
|
|
44
|
+
question: z.string(),
|
|
45
|
+
isOther: z.boolean().default(false),
|
|
46
|
+
isSecret: z.boolean().default(false),
|
|
47
|
+
options: z.array(z.object({ label: z.string(), description: z.string() })).nullish()
|
|
48
|
+
})
|
|
49
|
+
).min(1)
|
|
50
|
+
});
|
|
51
|
+
const permissionProfileParamsSchema = z.object({
|
|
52
|
+
itemId: z.string(),
|
|
53
|
+
reason: z.string().nullish(),
|
|
54
|
+
permissions: z.object({
|
|
55
|
+
network: jsonObjectSchema.nullish(),
|
|
56
|
+
fileSystem: jsonObjectSchema.nullish()
|
|
57
|
+
})
|
|
58
|
+
});
|
|
59
|
+
const inputOf = (parts) => parts.map(
|
|
60
|
+
(part) => part.type === "text" ? { type: "text", text: part.text, text_elements: [] } : { type: "image", url: `data:${part.mimeType};base64,${part.data}` }
|
|
61
|
+
);
|
|
62
|
+
const decisionFor = (outcome) => {
|
|
63
|
+
if (outcome.outcome !== "selected" || !("optionId" in outcome)) return "cancel";
|
|
64
|
+
if (outcome.optionId === "allow_always") return "acceptForSession";
|
|
65
|
+
if (outcome.optionId === "allow_once") return "accept";
|
|
66
|
+
return "decline";
|
|
67
|
+
};
|
|
68
|
+
const approvalOptions = [
|
|
69
|
+
{ optionId: "allow_once", name: "Allow", kind: "allow_once" },
|
|
70
|
+
{ optionId: "allow_always", name: "Allow for this session", kind: "allow_always" },
|
|
71
|
+
{ optionId: "reject_once", name: "Reject", kind: "reject_once" }
|
|
72
|
+
];
|
|
73
|
+
const appServerApprovalPolicy = (policy) => policy === CodexApprovalPolicy.Never ? {
|
|
74
|
+
granular: {
|
|
75
|
+
sandbox_approval: false,
|
|
76
|
+
rules: false,
|
|
77
|
+
skill_approval: false,
|
|
78
|
+
request_permissions: false,
|
|
79
|
+
mcp_elicitations: true
|
|
80
|
+
}
|
|
81
|
+
} : policy;
|
|
82
|
+
const toml = (value) => value.replace(/[^A-Za-z0-9_-]/gu, "_");
|
|
83
|
+
const assertDistinctMcpNames = (names) => {
|
|
84
|
+
const seen = /* @__PURE__ */ new Map();
|
|
85
|
+
for (const name of names) {
|
|
86
|
+
const key = toml(name);
|
|
87
|
+
const other = seen.get(key);
|
|
88
|
+
if (other != null)
|
|
89
|
+
throw new Error(`MCP server names collide: ${other} and ${name} are both ${key} to Codex`);
|
|
90
|
+
seen.set(key, name);
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
const mcpOverrides = (servers) => {
|
|
94
|
+
assertDistinctMcpNames(servers.map((server) => server.name));
|
|
95
|
+
const overrides = {};
|
|
96
|
+
for (const server of servers) {
|
|
97
|
+
const key = `mcp_servers.${toml(server.name)}`;
|
|
98
|
+
overrides[`${key}.url`] = server.url;
|
|
99
|
+
if ((server.headers ?? []).length > 0) {
|
|
100
|
+
overrides[`${key}.http_headers`] = Object.fromEntries(
|
|
101
|
+
(server.headers ?? []).map((header) => [header.name, header.value])
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return overrides;
|
|
106
|
+
};
|
|
107
|
+
const spawnFor = (deps, where) => deps.spawnAppServer({
|
|
108
|
+
command: deps.command,
|
|
109
|
+
args: [...deps.args, ...configFlags(providerOverrides(deps.env))],
|
|
110
|
+
cwd: where.cwd,
|
|
111
|
+
env: Object.fromEntries(
|
|
112
|
+
Object.entries(deps.env).flatMap(([key, value]) => value == null ? [] : [[key, value]])
|
|
113
|
+
),
|
|
114
|
+
log: where.log,
|
|
115
|
+
closeGraceMs: deps.closeGraceMs
|
|
116
|
+
});
|
|
117
|
+
const initializeParams = (version) => ({
|
|
118
|
+
clientInfo: { name: "acp-adapter-codex", title: "ACP adapter for Codex", version },
|
|
119
|
+
capabilities: { experimentalApi: true }
|
|
120
|
+
});
|
|
121
|
+
const forkCodexThread = async (args, deps) => {
|
|
122
|
+
const config = turnConfigOf(args.config);
|
|
123
|
+
const peer = createJsonRpcPeer({
|
|
124
|
+
transport: spawnFor(deps, { cwd: args.cwd, log: () => void 0 }),
|
|
125
|
+
onRequest: async ({ method }) => ({
|
|
126
|
+
error: { code: -32601, message: `unsupported request ${method}` }
|
|
127
|
+
}),
|
|
128
|
+
onNotification: () => void 0
|
|
129
|
+
});
|
|
130
|
+
try {
|
|
131
|
+
await peer.request("initialize", initializeParams(deps.version));
|
|
132
|
+
peer.notify("initialized");
|
|
133
|
+
const forked = threadResponseSchema.parse(
|
|
134
|
+
await peer.request("thread/fork", {
|
|
135
|
+
threadId: args.nativeId,
|
|
136
|
+
cwd: args.cwd,
|
|
137
|
+
model: config.model,
|
|
138
|
+
approvalPolicy: appServerApprovalPolicy(config.approvalPolicy),
|
|
139
|
+
sandbox: config.sandbox
|
|
140
|
+
})
|
|
141
|
+
);
|
|
142
|
+
return forked.thread.id;
|
|
143
|
+
} finally {
|
|
144
|
+
await peer.shutdown().catch(() => void 0);
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
const openCodexSession = async (args, deps) => {
|
|
148
|
+
const { sink } = args;
|
|
149
|
+
assertDistinctMcpNames(args.mcpServers.map((server) => String(server.name)));
|
|
150
|
+
const proxy = await startMcpProxy({
|
|
151
|
+
servers: args.mcpServers,
|
|
152
|
+
cwd: args.cwd,
|
|
153
|
+
env: deps.env,
|
|
154
|
+
mcpMessage: sink.mcpMessage,
|
|
155
|
+
log: sink.log
|
|
156
|
+
});
|
|
157
|
+
const serverNames = new Map(proxy.servers.map((server) => [toml(server.name), server.name]));
|
|
158
|
+
const translator = createTranslatorState(args.cwd, ({ server, tool, input }) => {
|
|
159
|
+
const name = serverNames.get(server);
|
|
160
|
+
return name == null ? null : proxy.takeResult({ server: name, tool: (candidate) => candidate === tool, input });
|
|
161
|
+
});
|
|
162
|
+
const overrides = mcpOverrides(proxy.servers);
|
|
163
|
+
let peer = null;
|
|
164
|
+
let threadId = args.nativeId;
|
|
165
|
+
let sandbox = null;
|
|
166
|
+
let turn = null;
|
|
167
|
+
const early = /* @__PURE__ */ new Map();
|
|
168
|
+
const pending = /* @__PURE__ */ new Set();
|
|
169
|
+
const finish = (current, completion) => {
|
|
170
|
+
current.settled = true;
|
|
171
|
+
current.started.resolve(null);
|
|
172
|
+
current.done.resolve(completion);
|
|
173
|
+
};
|
|
174
|
+
const withAbort = async (run) => {
|
|
175
|
+
const controller = new AbortController();
|
|
176
|
+
pending.add(controller);
|
|
177
|
+
try {
|
|
178
|
+
return await run(controller.signal);
|
|
179
|
+
} finally {
|
|
180
|
+
pending.delete(controller);
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
const askApproval = async (method, params) => {
|
|
184
|
+
const parsed = approvalParamsSchema.safeParse(params);
|
|
185
|
+
const fileChange = method === "item/fileChange/requestApproval";
|
|
186
|
+
const detail = parsed.success ? parsed.data : { itemId: void 0, command: null, reason: null };
|
|
187
|
+
const title = fileChange ? "Apply file changes" : detail.command ?? "Run command";
|
|
188
|
+
const outcome = await withAbort(
|
|
189
|
+
(signal) => sink.requestPermission(
|
|
190
|
+
{
|
|
191
|
+
sessionId: args.sessionId,
|
|
192
|
+
title,
|
|
193
|
+
description: detail.reason ?? null,
|
|
194
|
+
subject: {
|
|
195
|
+
type: "tool_call",
|
|
196
|
+
toolCall: {
|
|
197
|
+
toolCallId: detail.itemId ?? crypto.randomUUID(),
|
|
198
|
+
name: fileChange ? "apply_patch" : "exec_command",
|
|
199
|
+
title,
|
|
200
|
+
kind: fileChange ? "edit" : "execute",
|
|
201
|
+
status: "pending",
|
|
202
|
+
rawInput: params ?? null
|
|
203
|
+
}
|
|
204
|
+
},
|
|
205
|
+
options: approvalOptions
|
|
206
|
+
},
|
|
207
|
+
signal
|
|
208
|
+
)
|
|
209
|
+
);
|
|
210
|
+
return { decision: decisionFor(outcome) };
|
|
211
|
+
};
|
|
212
|
+
const forwardElicitation = async (params) => {
|
|
213
|
+
const parsed = elicitationParamsSchema.safeParse(params);
|
|
214
|
+
if (!parsed.success) return { action: "decline", content: null, _meta: null };
|
|
215
|
+
const requestedSchema = z.object({ requestedSchema: z.record(z.string(), z.unknown()) }).safeParse(parsed.data);
|
|
216
|
+
const url = z.object({ url: z.string(), elicitationId: z.string() }).safeParse(parsed.data);
|
|
217
|
+
let request;
|
|
218
|
+
if (parsed.data.mode === "url" && url.success) {
|
|
219
|
+
request = {
|
|
220
|
+
mode: "url",
|
|
221
|
+
sessionId: args.sessionId,
|
|
222
|
+
message: parsed.data.message,
|
|
223
|
+
...url.data
|
|
224
|
+
};
|
|
225
|
+
} else if (requestedSchema.success) {
|
|
226
|
+
request = {
|
|
227
|
+
mode: "form",
|
|
228
|
+
sessionId: args.sessionId,
|
|
229
|
+
message: parsed.data.message,
|
|
230
|
+
requestedSchema: requestedSchema.data.requestedSchema
|
|
231
|
+
};
|
|
232
|
+
} else {
|
|
233
|
+
return { action: "decline", content: null, _meta: null };
|
|
234
|
+
}
|
|
235
|
+
const response = await withAbort((signal) => sink.elicit(request, signal));
|
|
236
|
+
const accepted = z.object({ action: z.string(), content: jsonValueSchema.nullish() }).safeParse(response);
|
|
237
|
+
if (!accepted.success) return { action: "cancel", content: null, _meta: null };
|
|
238
|
+
const action = ["accept", "decline", "cancel"].includes(accepted.data.action) ? accepted.data.action : "cancel";
|
|
239
|
+
return { action, content: accepted.data.content ?? null, _meta: null };
|
|
240
|
+
};
|
|
241
|
+
const askUserInput = async (params) => {
|
|
242
|
+
const parsed = userInputParamsSchema.safeParse(params);
|
|
243
|
+
if (!parsed.success)
|
|
244
|
+
return { error: { code: -32602, message: "invalid user input questions" } };
|
|
245
|
+
const questions = parsed.data.questions;
|
|
246
|
+
if (questions.some((question) => question.isSecret)) {
|
|
247
|
+
return { error: { code: -32e3, message: "secret questions are unavailable over ACP" } };
|
|
248
|
+
}
|
|
249
|
+
const properties = Object.fromEntries(
|
|
250
|
+
questions.map((question) => {
|
|
251
|
+
const labels = question.options?.map((entry) => entry.label) ?? [];
|
|
252
|
+
const property = {
|
|
253
|
+
type: "string",
|
|
254
|
+
title: question.header,
|
|
255
|
+
description: [
|
|
256
|
+
question.question,
|
|
257
|
+
...question.options?.map((entry) => `${entry.label}: ${entry.description}`) ?? []
|
|
258
|
+
].join("\n")
|
|
259
|
+
};
|
|
260
|
+
if (labels.length > 0 && !question.isOther) property.enum = labels;
|
|
261
|
+
return [question.id, property];
|
|
262
|
+
})
|
|
263
|
+
);
|
|
264
|
+
const response = await withAbort(
|
|
265
|
+
(signal) => sink.elicit(
|
|
266
|
+
{
|
|
267
|
+
mode: "form",
|
|
268
|
+
sessionId: args.sessionId,
|
|
269
|
+
message: questions.map((question) => question.question).join("\n\n"),
|
|
270
|
+
requestedSchema: {
|
|
271
|
+
type: "object",
|
|
272
|
+
properties,
|
|
273
|
+
required: questions.map((question) => question.id)
|
|
274
|
+
}
|
|
275
|
+
},
|
|
276
|
+
signal
|
|
277
|
+
)
|
|
278
|
+
);
|
|
279
|
+
const accepted = z.object({ action: z.literal("accept"), content: z.record(z.string(), z.string()) }).safeParse(response);
|
|
280
|
+
if (!accepted.success) return { result: { answers: {} } };
|
|
281
|
+
const content = accepted.data.content;
|
|
282
|
+
return {
|
|
283
|
+
result: {
|
|
284
|
+
answers: Object.fromEntries(
|
|
285
|
+
questions.flatMap((question) => {
|
|
286
|
+
const answer = content[question.id];
|
|
287
|
+
return answer == null ? [] : [[question.id, { answers: [answer] }]];
|
|
288
|
+
})
|
|
289
|
+
)
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
};
|
|
293
|
+
const askPermissionProfile = async (params) => {
|
|
294
|
+
const parsed = permissionProfileParamsSchema.safeParse(params);
|
|
295
|
+
if (!parsed.success) return { permissions: {}, scope: "turn" };
|
|
296
|
+
const title = "Grant additional permissions";
|
|
297
|
+
const outcome = await withAbort(
|
|
298
|
+
(signal) => sink.requestPermission(
|
|
299
|
+
{
|
|
300
|
+
sessionId: args.sessionId,
|
|
301
|
+
title,
|
|
302
|
+
description: parsed.data.reason ?? null,
|
|
303
|
+
subject: {
|
|
304
|
+
type: "tool_call",
|
|
305
|
+
toolCall: {
|
|
306
|
+
toolCallId: parsed.data.itemId,
|
|
307
|
+
name: "request_permissions",
|
|
308
|
+
title,
|
|
309
|
+
kind: "other",
|
|
310
|
+
status: "pending",
|
|
311
|
+
rawInput: params ?? null
|
|
312
|
+
}
|
|
313
|
+
},
|
|
314
|
+
options: approvalOptions
|
|
315
|
+
},
|
|
316
|
+
signal
|
|
317
|
+
)
|
|
318
|
+
);
|
|
319
|
+
const allowed = outcome.outcome === "selected" && "optionId" in outcome && (outcome.optionId === "allow_once" || outcome.optionId === "allow_always");
|
|
320
|
+
if (!allowed) return { permissions: {}, scope: "turn" };
|
|
321
|
+
return {
|
|
322
|
+
permissions: parsed.data.permissions,
|
|
323
|
+
scope: outcome.optionId === "allow_always" ? "session" : "turn"
|
|
324
|
+
};
|
|
325
|
+
};
|
|
326
|
+
const onServerRequest = async ({
|
|
327
|
+
method,
|
|
328
|
+
params
|
|
329
|
+
}) => {
|
|
330
|
+
switch (method) {
|
|
331
|
+
case "item/commandExecution/requestApproval":
|
|
332
|
+
case "item/fileChange/requestApproval":
|
|
333
|
+
return { result: await askApproval(method, params) };
|
|
334
|
+
case "mcpServer/elicitation/request":
|
|
335
|
+
return { result: await forwardElicitation(params) };
|
|
336
|
+
case "item/tool/requestUserInput":
|
|
337
|
+
return askUserInput(params);
|
|
338
|
+
case "item/permissions/requestApproval":
|
|
339
|
+
return { result: await askPermissionProfile(params) };
|
|
340
|
+
default:
|
|
341
|
+
return { error: { code: -32601, message: `unsupported request ${method}` } };
|
|
342
|
+
}
|
|
343
|
+
};
|
|
344
|
+
const onNotification = ({
|
|
345
|
+
method,
|
|
346
|
+
params
|
|
347
|
+
}) => {
|
|
348
|
+
const translation = translateCodexNotification(translator, { method, params });
|
|
349
|
+
for (const update of translation.updates) sink.update(update);
|
|
350
|
+
const completed = translation.turnCompleted;
|
|
351
|
+
if (completed == null) return;
|
|
352
|
+
if (turn?.id === completed.turnId) finish(turn, completed);
|
|
353
|
+
else early.set(completed.turnId, completed);
|
|
354
|
+
};
|
|
355
|
+
const threadParams = (config) => ({
|
|
356
|
+
cwd: args.cwd,
|
|
357
|
+
model: config.model,
|
|
358
|
+
approvalPolicy: appServerApprovalPolicy(config.approvalPolicy),
|
|
359
|
+
sandbox: config.sandbox,
|
|
360
|
+
config: overrides
|
|
361
|
+
});
|
|
362
|
+
const start = async (config) => {
|
|
363
|
+
const transport = spawnFor(deps, { cwd: args.cwd, log: sink.log });
|
|
364
|
+
const next = createJsonRpcPeer({
|
|
365
|
+
transport,
|
|
366
|
+
onRequest: onServerRequest,
|
|
367
|
+
onNotification,
|
|
368
|
+
log: sink.log
|
|
369
|
+
});
|
|
370
|
+
void next.closed.then(() => {
|
|
371
|
+
if (peer !== next) return;
|
|
372
|
+
peer = null;
|
|
373
|
+
for (const controller of pending) controller.abort();
|
|
374
|
+
if (turn != null) finish(turn, null);
|
|
375
|
+
});
|
|
376
|
+
peer = next;
|
|
377
|
+
await next.request("initialize", initializeParams(deps.version));
|
|
378
|
+
next.notify("initialized");
|
|
379
|
+
if (threadId != null) {
|
|
380
|
+
threadResponseSchema.parse(
|
|
381
|
+
await next.request("thread/resume", { ...threadParams(config), threadId })
|
|
382
|
+
);
|
|
383
|
+
} else if (args.forkOf != null) {
|
|
384
|
+
const forked = threadResponseSchema.parse(
|
|
385
|
+
await next.request("thread/fork", { ...threadParams(config), threadId: args.forkOf })
|
|
386
|
+
);
|
|
387
|
+
threadId = forked.thread.id;
|
|
388
|
+
sink.nativeIdChanged(threadId);
|
|
389
|
+
} else {
|
|
390
|
+
const started = threadResponseSchema.parse(
|
|
391
|
+
await next.request("thread/start", threadParams(config))
|
|
392
|
+
);
|
|
393
|
+
threadId = started.thread.id;
|
|
394
|
+
sink.nativeIdChanged(threadId);
|
|
395
|
+
}
|
|
396
|
+
sandbox = config.sandbox;
|
|
397
|
+
return next;
|
|
398
|
+
};
|
|
399
|
+
const stop = async () => {
|
|
400
|
+
const current = peer;
|
|
401
|
+
peer = null;
|
|
402
|
+
await current?.shutdown().catch(() => void 0);
|
|
403
|
+
};
|
|
404
|
+
return {
|
|
405
|
+
nativeId: () => threadId,
|
|
406
|
+
run: async ({ input, signal, config }) => {
|
|
407
|
+
if (signal.aborted) return { stopReason: StopReason.Cancelled, inputUnsent: true };
|
|
408
|
+
const wanted = turnConfigOf(config);
|
|
409
|
+
if (peer != null && sandbox !== wanted.sandbox) await stop();
|
|
410
|
+
const current = peer ?? await start(wanted);
|
|
411
|
+
if (signal.aborted) return { stopReason: StopReason.Cancelled, inputUnsent: true };
|
|
412
|
+
const started = {
|
|
413
|
+
id: null,
|
|
414
|
+
started: Promise.withResolvers(),
|
|
415
|
+
done: Promise.withResolvers(),
|
|
416
|
+
settled: false,
|
|
417
|
+
signal
|
|
418
|
+
};
|
|
419
|
+
turn = started;
|
|
420
|
+
const interrupt = () => {
|
|
421
|
+
for (const controller of pending) controller.abort();
|
|
422
|
+
if (started.id == null || threadId == null) return;
|
|
423
|
+
void current.request("turn/interrupt", { threadId, turnId: started.id }).catch((cause) => sink.log(`turn/interrupt failed: ${errorMessageOf(cause)}`));
|
|
424
|
+
};
|
|
425
|
+
signal.addEventListener("abort", interrupt, { once: true });
|
|
426
|
+
try {
|
|
427
|
+
const response = turnResponseSchema.parse(
|
|
428
|
+
await current.request("turn/start", {
|
|
429
|
+
threadId,
|
|
430
|
+
input: inputOf(input),
|
|
431
|
+
model: wanted.model,
|
|
432
|
+
effort: wanted.effort,
|
|
433
|
+
approvalPolicy: appServerApprovalPolicy(wanted.approvalPolicy)
|
|
434
|
+
})
|
|
435
|
+
);
|
|
436
|
+
started.id = response.turn.id;
|
|
437
|
+
started.started.resolve(response.turn.id);
|
|
438
|
+
const finished = early.get(response.turn.id);
|
|
439
|
+
early.delete(response.turn.id);
|
|
440
|
+
if (finished != null) finish(started, finished);
|
|
441
|
+
if (signal.aborted) interrupt();
|
|
442
|
+
const completion = await started.done.promise;
|
|
443
|
+
if (signal.aborted) return { stopReason: StopReason.Cancelled, usage: completion?.usage };
|
|
444
|
+
if (completion == null) {
|
|
445
|
+
return {
|
|
446
|
+
stopReason: StopReason.Error,
|
|
447
|
+
providerError: {
|
|
448
|
+
code: "app_server_exited",
|
|
449
|
+
message: "the Codex app-server exited mid-turn",
|
|
450
|
+
retryable: true
|
|
451
|
+
}
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
const end = {
|
|
455
|
+
stopReason: completion.stopReason,
|
|
456
|
+
providerError: completion.providerError,
|
|
457
|
+
usage: completion.usage
|
|
458
|
+
};
|
|
459
|
+
return end;
|
|
460
|
+
} finally {
|
|
461
|
+
started.settled = true;
|
|
462
|
+
started.started.resolve(null);
|
|
463
|
+
signal.removeEventListener("abort", interrupt);
|
|
464
|
+
if (turn === started) turn = null;
|
|
465
|
+
}
|
|
466
|
+
},
|
|
467
|
+
// turn/steer adds the input to the running turn; Codex answers it before the turn ends.
|
|
468
|
+
inject: async (input) => {
|
|
469
|
+
const current = turn;
|
|
470
|
+
const connection = peer;
|
|
471
|
+
if (current == null || connection == null || threadId == null) return false;
|
|
472
|
+
const turnId = await current.started.promise;
|
|
473
|
+
if (turnId == null || current.settled || current.signal.aborted) return false;
|
|
474
|
+
try {
|
|
475
|
+
turnSteerResponseSchema.parse(
|
|
476
|
+
await connection.request("turn/steer", {
|
|
477
|
+
threadId,
|
|
478
|
+
expectedTurnId: turnId,
|
|
479
|
+
input: inputOf(input)
|
|
480
|
+
})
|
|
481
|
+
);
|
|
482
|
+
return true;
|
|
483
|
+
} catch (cause) {
|
|
484
|
+
sink.log(`turn/steer failed: ${errorMessageOf(cause)}`);
|
|
485
|
+
return false;
|
|
486
|
+
}
|
|
487
|
+
},
|
|
488
|
+
close: async () => {
|
|
489
|
+
await stop();
|
|
490
|
+
await proxy.close();
|
|
491
|
+
}
|
|
492
|
+
};
|
|
493
|
+
};
|
|
494
|
+
export {
|
|
495
|
+
assertDistinctMcpNames,
|
|
496
|
+
forkCodexThread,
|
|
497
|
+
mcpOverrides,
|
|
498
|
+
openCodexSession
|
|
499
|
+
};
|
|
500
|
+
//# sourceMappingURL=session.mjs.map
|