@plaios/codex 0.0.0-stage → 0.1.7

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/README.md CHANGED
@@ -1,3 +1,43 @@
1
- # Temporary Holding Version
1
+ # @plaios/codex
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Codex AI capability for PLAIOS. It implements the provider-neutral `AIProvider` contract, including text and image inputs, structured function calls, capability execution loops, cancellation, and timeouts.
4
+
5
+ By default the provider starts one Codex `app-server` lazily and keeps it alive across requests. Runtime reloads close it cleanly, and an unexpected exit is restarted on the next request. Set `persistentProcess: false` only when compatibility with an older Codex CLI is required.
6
+
7
+ For a single unambiguous state-changing capability call, Codex can generate a natural confirmation together with the tool arguments. PLAIOS emits it only after the capability reports success, avoiding a second model round-trip. Reads, failures, delayed sequences, and multi-step requests continue through the result-aware loop.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pnpm add @plaios/codex --registry http://localhost:4873
13
+ ```
14
+
15
+ Or open the Store in `plaios start` and choose **Install**. PLAIOS discovers the `codex.ai` interface and creates its configuration automatically.
16
+
17
+ ## Configuration
18
+
19
+ The safe defaults are `read-only` sandboxing, `never` approval policy, disabled network access, and disabled web search. Authentication uses `CODEX_API_KEY` when supplied, otherwise the local Codex login/session.
20
+
21
+ ```yaml
22
+ - package: "@plaios/codex"
23
+ version: 0.1.2
24
+ interface: codex.ai
25
+ instanceId: ai:codex
26
+ config:
27
+ model: gpt-5.6-sol
28
+ sandboxMode: read-only
29
+ approvalPolicy: never
30
+ networkAccessEnabled: false
31
+ webSearchMode: disabled
32
+ ```
33
+
34
+ ## Runtime
35
+
36
+ ```ts
37
+ import { CodexProvider } from "@plaios/codex";
38
+
39
+ const provider = new CodexProvider({ model: "gpt-5.6-sol" });
40
+ const result = await provider.processInput("Explain this runtime in one paragraph.");
41
+ ```
42
+
43
+ The package also exports `@plaios/codex/web/ai`, a management microfrontend for settings, provider status, and the effective security boundary.
@@ -0,0 +1,72 @@
1
+ schemaVersion: 1
2
+ id: codex
3
+ name: Codex
4
+ version: 0.1.7
5
+ description: Codex AI provider with a persistent app-server, structured tool calling, low-latency successful command completion, and safe runtime defaults
6
+ interfaces:
7
+ - id: codex.ai
8
+ kind: system2
9
+ name: CodexProvider
10
+ entry: .
11
+ export: .
12
+ className: CodexProvider
13
+ description: Runs PLAIOS model requests through the Codex SDK
14
+ surfaces: [local, network]
15
+ permissions: [ai.codex]
16
+ required: []
17
+ config:
18
+ - key: model
19
+ env: CODEX_MODEL
20
+ type: string
21
+ required: false
22
+ default: gpt-5.6-sol
23
+ description: Default Codex model id
24
+ - key: apiKey
25
+ env: CODEX_API_KEY
26
+ type: secret
27
+ required: false
28
+ description: Optional API key; otherwise the local Codex session is used
29
+ - key: workingDirectory
30
+ type: string
31
+ required: false
32
+ description: Working directory visible to Codex
33
+ - key: skipGitRepoCheck
34
+ type: boolean
35
+ required: false
36
+ default: true
37
+ description: Allow the configured working directory outside a Git repository
38
+ - key: sandboxMode
39
+ type: string
40
+ required: false
41
+ default: read-only
42
+ description: Codex sandbox mode
43
+ - key: approvalPolicy
44
+ type: string
45
+ required: false
46
+ default: never
47
+ description: Codex approval policy
48
+ - key: modelReasoningEffort
49
+ type: string
50
+ required: false
51
+ description: Optional model reasoning effort
52
+ - key: networkAccessEnabled
53
+ type: boolean
54
+ required: false
55
+ default: false
56
+ description: Allow network access inside workspace-write sandbox
57
+ - key: webSearchMode
58
+ type: string
59
+ required: false
60
+ default: disabled
61
+ description: Codex web search mode
62
+ - key: persistentProcess
63
+ type: boolean
64
+ required: false
65
+ default: true
66
+ description: Keep one Codex app-server process warm across requests
67
+ startup:
68
+ when: always
69
+ web:
70
+ entry: ./web/ai
71
+ export: default
72
+ styles: ./web/styles.css
@@ -0,0 +1,61 @@
1
+ import { type ApprovalMode, type CodexOptions, type Input as CodexInput, type ModelReasoningEffort, type SandboxMode, type WebSearchMode } from "@openai/codex-sdk";
2
+ import type { AIExecutableFunctionDefinition, AIFunctionCallResult, AIFunctionDefinition, AIFunctionProcessOptions, AIInput, AIModelSettings, AIProcessOptions, AIProcessResult, JsonSchema, System2, SystemAnswers, SystemAskOptions, SystemQuestions } from "@plaios/core";
3
+ export interface CodexProviderOptions {
4
+ model: string;
5
+ apiKey?: string;
6
+ baseUrl?: string;
7
+ settings?: AIModelSettings;
8
+ workingDirectory?: string;
9
+ skipGitRepoCheck?: boolean;
10
+ sandboxMode?: SandboxMode;
11
+ approvalPolicy?: ApprovalMode;
12
+ modelReasoningEffort?: ModelReasoningEffort;
13
+ networkAccessEnabled?: boolean;
14
+ webSearchMode?: WebSearchMode;
15
+ codexPathOverride?: string;
16
+ config?: CodexOptions["config"];
17
+ persistentProcess?: boolean;
18
+ }
19
+ interface FunctionStep {
20
+ type: "text" | "function-call";
21
+ name: string;
22
+ arguments: unknown;
23
+ text: string | null;
24
+ finishOnSuccess: boolean;
25
+ }
26
+ export declare class CodexProvider implements System2 {
27
+ readonly provider: "codex";
28
+ readonly model: string;
29
+ readonly settings: Readonly<AIModelSettings>;
30
+ private readonly codex;
31
+ private readonly threadOptions;
32
+ private readonly status;
33
+ constructor(options: CodexProviderOptions);
34
+ microfrontendData(): {
35
+ credentialMode: "api-key" | "codex-session";
36
+ workingDirectory: string;
37
+ sandboxMode: SandboxMode;
38
+ approvalPolicy: ApprovalMode;
39
+ networkAccessEnabled: boolean;
40
+ webSearchMode: WebSearchMode;
41
+ modelReasoningEffort?: ModelReasoningEffort;
42
+ persistentProcess: boolean;
43
+ provider: "codex";
44
+ model: string;
45
+ };
46
+ processInput(input: AIInput, options?: AIProcessOptions): Promise<AIProcessResult>;
47
+ ask(state: Record<string, unknown>, questions: SystemQuestions, options?: SystemAskOptions): Promise<SystemAnswers>;
48
+ functionCall<TArguments>(input: string, definition: AIFunctionDefinition<TArguments>, options?: Omit<AIProcessOptions, "stream">): Promise<AIFunctionCallResult<TArguments>>;
49
+ processWithFunctions(input: AIInput, definitions: readonly AIExecutableFunctionDefinition[], options?: AIFunctionProcessOptions): Promise<AIProcessResult>;
50
+ close(): Promise<void>;
51
+ private startThread;
52
+ private runFunctionLoop;
53
+ }
54
+ export declare function createCodexInput(input: AIInput, instructions?: string, taskInstructions?: string): CodexInput;
55
+ export declare function createCapabilityFollowUp(name: string, output: unknown): CodexInput;
56
+ export declare function normalizeCodexOutputSchema(schema: JsonSchema): JsonSchema;
57
+ export declare function shouldFinishAfterCapability(step: Pick<FunctionStep, "type" | "text" | "finishOnSuccess">, output: unknown): boolean;
58
+ /** Decodes the `text` of an incomplete `{"type":"text", ...}` step so it can stream; undefined until the step is known to be text. */
59
+ export declare function partialFinalText(json: string): string | undefined;
60
+ export {};
61
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAS,KAAK,YAAY,EAAE,KAAK,YAAY,EAAE,KAAK,KAAK,IAAI,UAAU,EAAE,KAAK,oBAAoB,EAAE,KAAK,WAAW,EAAE,KAAK,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAC3K,OAAO,KAAK,EAAE,8BAA8B,EAAE,oBAAoB,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,OAAO,EAAE,eAAe,EAAE,gBAAgB,EAAE,eAAe,EAAE,UAAU,EAAE,OAAO,EAAE,aAAa,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAI7Q,MAAM,WAAW,oBAAoB;IACnC,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE,eAAe,CAAC;IAC3B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B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Aa,CAAC,CAElH;IAEK,YAAY,CAAC,UAAU,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,oBAAoB,CAAC,UAAU,CAAC,EAAE,OAAO,GAAE,IAAI,CAAC,gBAAgB,EAAE,QAAQ,CAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC,UAAU,CAAC,CAAC,CAKrL;IAEK,oBAAoB,CAAC,KAAK,EAAE,OAAO,EAAE,WAAW,EAAE,SAAS,8BAA8B,EAAE,EAAE,OAAO,GAAE,wBAA6B,GAAG,OAAO,CAAC,eAAe,CAAC,CAQnK;IAEK,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAE3B;IAED,OAAO,CAAC,WAAW;YAEJ,eAAe;CA2B/B;AAQD,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,EAAE,YAAY,CAAC,EAAE,MAAM,EAAE,gBAAgB,CAAC,EAAE,MAAM,GAAG,UAAU,CAK7G;AAID,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,UAAU,CAYlF;AAeD,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,UAAU,GAAG,UAAU,CAAsD;AAahI,wBAAgB,2BAA2B,CAAC,IAAI,EAAE,IAAI,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,iBAAiB,CAAC,EAAE,MAAM,EAAE,OAAO,GAAG,OAAO,CAAiL;AAgCrT,sIAAsI;AACtI,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAiBjE"}
@@ -0,0 +1,255 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { Codex } from "@openai/codex-sdk";
3
+ import { askWithFunctionCall } from "@plaios/systems";
4
+ import { PersistentCodexAppServer } from "./persistent-app-server.js";
5
+ const providerInstructions = [
6
+ "You are the model inside PLAIOS.",
7
+ "Do not inspect or modify the workspace and do not use Codex built-in tools.",
8
+ "Use only the request and the PLAIOS capabilities explicitly described in it.",
9
+ ].join(" ");
10
+ export class CodexProvider {
11
+ provider = "codex";
12
+ model;
13
+ settings;
14
+ codex;
15
+ threadOptions;
16
+ status;
17
+ constructor(options) {
18
+ const model = options.model?.trim();
19
+ if (!model)
20
+ throw new Error("CodexProvider model is required");
21
+ const workingDirectory = options.workingDirectory ?? process.cwd();
22
+ const sandboxMode = options.sandboxMode ?? "read-only";
23
+ const approvalPolicy = options.approvalPolicy ?? "never";
24
+ const networkAccessEnabled = options.networkAccessEnabled ?? false;
25
+ const webSearchMode = options.webSearchMode ?? "disabled";
26
+ const persistentProcess = options.persistentProcess ?? true;
27
+ this.model = model;
28
+ this.settings = Object.freeze({ ...options.settings });
29
+ this.codex = persistentProcess
30
+ ? new PersistentCodexAppServer({ apiKey: options.apiKey, baseUrl: options.baseUrl, codexPathOverride: options.codexPathOverride, config: options.config })
31
+ : new Codex({ apiKey: options.apiKey, baseUrl: options.baseUrl, codexPathOverride: options.codexPathOverride, config: options.config });
32
+ this.threadOptions = { model, workingDirectory, skipGitRepoCheck: options.skipGitRepoCheck ?? true, sandboxMode, approvalPolicy, modelReasoningEffort: options.modelReasoningEffort, networkAccessEnabled, webSearchMode };
33
+ this.status = { credentialMode: options.apiKey || process.env.CODEX_API_KEY ? "api-key" : "codex-session", workingDirectory, sandboxMode, approvalPolicy, networkAccessEnabled, webSearchMode, modelReasoningEffort: options.modelReasoningEffort, persistentProcess };
34
+ }
35
+ microfrontendData() {
36
+ return { provider: this.provider, model: this.model, ...this.status };
37
+ }
38
+ async processInput(input, options = {}) {
39
+ const prompt = createCodexInput(input, options.instructions);
40
+ const thread = this.startThread();
41
+ if (options.stream)
42
+ return { type: "stream", stream: streamText(thread, prompt, resolveSignal(this.settings, options)) };
43
+ const result = await thread.run(prompt, { signal: resolveSignal(this.settings, options) });
44
+ return { type: "text", text: result.finalResponse };
45
+ }
46
+ ask(state, questions, options) {
47
+ return askWithFunctionCall(this, state, questions, options);
48
+ }
49
+ async functionCall(input, definition, options = {}) {
50
+ validateDefinition(definition);
51
+ const prompt = createPrompt(input, options.instructions, `Return the arguments for the required "${definition.name}" function.\nFunction description: ${definition.description}\nReturn only the JSON object matching the supplied output schema.`);
52
+ const result = await this.startThread().run(prompt, { outputSchema: normalizeCodexOutputSchema(definition.inputSchema), signal: resolveSignal(this.settings, options) });
53
+ return { type: "function-call", name: definition.name, callId: `codex-${randomUUID()}`, arguments: parseJson(result.finalResponse, `function "${definition.name}" arguments`) };
54
+ }
55
+ async processWithFunctions(input, definitions, options = {}) {
56
+ if (definitions.length === 0)
57
+ return this.processInput(input, options);
58
+ validateDefinitions(definitions);
59
+ const stream = this.runFunctionLoop(input, definitions, options);
60
+ if (options.stream)
61
+ return { type: "stream", stream };
62
+ let text = "";
63
+ for await (const chunk of stream)
64
+ text += chunk;
65
+ return { type: "text", text };
66
+ }
67
+ async close() {
68
+ if (this.codex instanceof PersistentCodexAppServer)
69
+ await this.codex.close();
70
+ }
71
+ startThread() { return this.codex.startThread(this.threadOptions); }
72
+ async *runFunctionLoop(input, definitions, options) {
73
+ const thread = this.startThread();
74
+ const schema = createFunctionStepSchema(definitions);
75
+ const maxSteps = Math.max(1, options.maxSteps ?? 100);
76
+ let prompt = createCodexInput(input, options.instructions, createFunctionInstructions(definitions));
77
+ for (let step = 0; step < maxSteps; step += 1) {
78
+ // Stream the final answer's `text` field while the step JSON is still arriving; tool-call steps stay buffered.
79
+ let finalResponse = "";
80
+ let sent = 0;
81
+ for await (const text of agentMessages(thread, prompt, { outputSchema: schema, signal: resolveSignal(this.settings, options) })) {
82
+ finalResponse = text;
83
+ const decoded = partialFinalText(text);
84
+ if (decoded !== undefined && decoded.length > sent) {
85
+ yield decoded.slice(sent);
86
+ sent = decoded.length;
87
+ }
88
+ }
89
+ const requested = parseFunctionStep(finalResponse);
90
+ if (requested.type === "text") {
91
+ if (typeof requested.text !== "string")
92
+ throw new Error("Codex returned a final step without text");
93
+ const rest = requested.text.slice(sent);
94
+ if (rest)
95
+ yield rest;
96
+ return;
97
+ }
98
+ const definition = definitions.find((candidate) => candidate.name === requested.name);
99
+ if (!definition)
100
+ throw new Error(`Codex requested unknown function "${requested.name}"`);
101
+ const output = await definition.execute(requested.arguments, { callId: `codex-${randomUUID()}`, signal: options.signal });
102
+ if (shouldFinishAfterCapability(requested, output)) {
103
+ yield requested.text;
104
+ return;
105
+ }
106
+ prompt = createCapabilityFollowUp(definition.name, output);
107
+ }
108
+ throw new Error(`Codex exceeded the ${maxSteps}-step function-call limit`);
109
+ }
110
+ }
111
+ function createPrompt(input, instructions, taskInstructions) {
112
+ const normalized = input.trim();
113
+ if (!normalized)
114
+ throw new Error("AI input is required");
115
+ return [providerInstructions, instructions?.trim(), taskInstructions?.trim(), "Request:", normalized].filter((part) => Boolean(part)).join("\n\n");
116
+ }
117
+ export function createCodexInput(input, instructions, taskInstructions) {
118
+ const text = typeof input === "string" ? input : input.text;
119
+ const prompt = createPrompt(text, instructions, taskInstructions);
120
+ if (typeof input === "string" || input.images.length === 0)
121
+ return prompt;
122
+ return [{ type: "text", text: prompt }, ...input.images.map(({ path }) => ({ type: "local_image", path: requireImagePath(path) }))];
123
+ }
124
+ function requireImagePath(value) { const path = value.trim(); if (!path)
125
+ throw new Error("AI image path is required"); return path; }
126
+ export function createCapabilityFollowUp(name, output) {
127
+ const text = [
128
+ `PLAIOS executed "${name}".`,
129
+ "",
130
+ "Capability result:",
131
+ serialize(output),
132
+ "",
133
+ "Continue the original request. If the result includes a screenshot or localPath image, look at the image before answering.",
134
+ "Call another capability if another step is still needed, otherwise return the final answer.",
135
+ ].join("\n");
136
+ const images = imagesFromCapabilityOutput(output);
137
+ return images.length > 0 ? [{ type: "text", text }, ...images] : text;
138
+ }
139
+ function imagesFromCapabilityOutput(output) {
140
+ if (!isRecord(output) || !isRecord(output.data))
141
+ return [];
142
+ const path = typeof output.data.localPath === "string" ? output.data.localPath.trim() : "";
143
+ if (!path || !/\.(png|jpe?g|webp|gif)$/i.test(path))
144
+ return [];
145
+ return [{ type: "local_image", path }];
146
+ }
147
+ function createFunctionInstructions(definitions) { return ["Choose whether to call one PLAIOS capability or return the final answer.", "For a function call, set type to function-call and provide its exact name and arguments.", "Set finishOnSuccess to true only for one unambiguous state-changing command when no result data, follow-up capability, delay, or additional action is needed. In that case, write a short natural confirmation in the user's language in text; it will be sent only after the capability reports success.", "For reads, questions, uncertain targets, delayed, visual, or multi-step requests, set finishOnSuccess to false and text to null so you can inspect the capability result, including any screenshot.", "If a capability returns a screenshot or localPath image, look at that image before describing what you see.", "For a final answer, set type to text, name to an empty string, arguments to null, finishOnSuccess to false, and provide text.", "Available PLAIOS capabilities:", serialize(definitions.map(({ name, description, inputSchema }) => ({ name, description, inputSchema })))].join("\n"); }
148
+ function createFunctionStepSchema(definitions) {
149
+ return { type: "object", properties: { type: { type: "string", enum: ["text", "function-call"] }, name: { type: "string", enum: ["", ...definitions.map(({ name }) => name)] }, arguments: { anyOf: [{ type: "null" }, ...definitions.map(({ inputSchema }) => normalizeCodexOutputSchema(inputSchema))] }, text: { type: ["string", "null"] }, finishOnSuccess: { type: "boolean" } }, required: ["type", "name", "arguments", "text", "finishOnSuccess"], additionalProperties: false };
150
+ }
151
+ export function normalizeCodexOutputSchema(schema) { return normalizeSchemaNode(schema); }
152
+ function normalizeSchemaNode(value) {
153
+ if (Array.isArray(value))
154
+ return value.map(normalizeSchemaNode);
155
+ if (!isRecord(value))
156
+ return value;
157
+ const normalized = Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, normalizeSchemaNode(entry)]));
158
+ if (!isRecord(value.properties))
159
+ return normalized;
160
+ const originallyRequired = new Set(Array.isArray(value.required) ? value.required.filter((entry) => typeof entry === "string") : []);
161
+ const properties = Object.fromEntries(Object.entries(value.properties).map(([key, propertySchema]) => { const property = normalizeSchemaNode(propertySchema); return [key, originallyRequired.has(key) || allowsNull(property) ? property : { anyOf: [property, { type: "null" }] }]; }));
162
+ return { ...normalized, properties, required: Object.keys(properties), additionalProperties: false };
163
+ }
164
+ function allowsNull(value) { if (!isRecord(value))
165
+ return false; if (value.type === "null")
166
+ return true; if (Array.isArray(value.type) && value.type.includes("null"))
167
+ return true; if (Array.isArray(value.enum) && value.enum.includes(null))
168
+ return true; return ["anyOf", "oneOf"].some((key) => Array.isArray(value[key]) && value[key].some(allowsNull)); }
169
+ function parseFunctionStep(value) { const parsed = parseJson(value, "function step"); if ((parsed.type !== "text" && parsed.type !== "function-call") || typeof parsed.name !== "string" || (parsed.text !== null && typeof parsed.text !== "string") || typeof parsed.finishOnSuccess !== "boolean")
170
+ throw new Error("Codex returned an invalid function step"); return { type: parsed.type, name: parsed.name, arguments: parsed.arguments, text: parsed.text, finishOnSuccess: parsed.finishOnSuccess }; }
171
+ export function shouldFinishAfterCapability(step, output) { return step.type === "function-call" && step.finishOnSuccess && typeof step.text === "string" && step.text.trim().length > 0 && isRecord(output) && output.success === true; }
172
+ function validateDefinitions(definitions) { const names = new Set(); for (const definition of definitions) {
173
+ validateDefinition(definition);
174
+ if (names.has(definition.name))
175
+ throw new Error(`Duplicate AI function name: "${definition.name}"`);
176
+ names.add(definition.name);
177
+ } }
178
+ function validateDefinition(definition) { if (!/^[a-zA-Z0-9_-]+$/.test(definition.name))
179
+ throw new Error(`Invalid AI function name: "${definition.name}"`); }
180
+ function parseJson(value, label) { try {
181
+ return JSON.parse(value);
182
+ }
183
+ catch (error) {
184
+ throw new Error(`Codex returned invalid JSON for ${label}`, { cause: error });
185
+ } }
186
+ function serialize(value) { try {
187
+ return JSON.stringify(value, null, 2) ?? String(value);
188
+ }
189
+ catch {
190
+ return String(value);
191
+ } }
192
+ function resolveSignal(defaults, options) { const timeoutMs = options.settings?.timeoutMs ?? defaults.timeoutMs; const timeoutSignal = timeoutMs === undefined ? undefined : AbortSignal.timeout(Math.max(1, timeoutMs)); if (options.signal && timeoutSignal)
193
+ return AbortSignal.any([options.signal, timeoutSignal]); return options.signal ?? timeoutSignal; }
194
+ /** Yields the agent's message text as it grows; the last value is the complete response. */
195
+ async function* agentMessages(thread, input, options) {
196
+ if (!thread.runStreamed) {
197
+ yield (await thread.run(input, options)).finalResponse;
198
+ return;
199
+ }
200
+ let last = "";
201
+ for await (const event of (await thread.runStreamed(input, options)).events) {
202
+ if (event.type === "turn.failed")
203
+ throw new Error(event.error?.message ?? "Codex turn failed");
204
+ if (event.type === "error")
205
+ throw new Error(event.message ?? "Codex stream error");
206
+ if ((event.type === "item.updated" || event.type === "item.completed") && event.item?.type === "agent_message" && typeof event.item.text === "string") {
207
+ last = event.item.text;
208
+ yield last;
209
+ }
210
+ }
211
+ }
212
+ async function* streamText(thread, input, signal) {
213
+ let sent = 0;
214
+ for await (const text of agentMessages(thread, input, { signal })) {
215
+ if (text.length > sent) {
216
+ yield text.slice(sent);
217
+ sent = text.length;
218
+ }
219
+ }
220
+ }
221
+ /** Decodes the `text` of an incomplete `{"type":"text", ...}` step so it can stream; undefined until the step is known to be text. */
222
+ export function partialFinalText(json) {
223
+ if (!/^\s*\{\s*"type"\s*:\s*"text"/.test(json))
224
+ return undefined;
225
+ const match = /"text"\s*:\s*"/.exec(json);
226
+ if (!match)
227
+ return "";
228
+ const escapes = { n: "\n", t: "\t", r: "\r", b: "\b", f: "\f" };
229
+ let out = "";
230
+ for (let index = match.index + match[0].length; index < json.length; index += 1) {
231
+ const char = json[index];
232
+ if (char === '"')
233
+ return out;
234
+ if (char !== "\\") {
235
+ out += char;
236
+ continue;
237
+ }
238
+ const next = json[index + 1];
239
+ if (next === undefined)
240
+ return out;
241
+ if (next === "u") {
242
+ const hex = json.slice(index + 2, index + 6);
243
+ if (hex.length < 4)
244
+ return out;
245
+ out += String.fromCharCode(parseInt(hex, 16));
246
+ index += 5;
247
+ continue;
248
+ }
249
+ out += escapes[next] ?? next;
250
+ index += 1;
251
+ }
252
+ return out;
253
+ }
254
+ function isRecord(value) { return typeof value === "object" && value !== null && !Array.isArray(value); }
255
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"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AAC;QAC7B,IAAI,IAAI,KAAK,SAAS;YAAE,OAAO,GAAG,CAAC;QACnC,IAAI,IAAI,KAAK,GAAG,EAAE,CAAC;YAAC,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;YAAC,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC;gBAAE,OAAO,GAAG,CAAC;YAAC,GAAG,IAAI,MAAM,CAAC,YAAY,CAAC,QAAQ,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,CAAC;YAAC,KAAK,IAAI,CAAC,CAAC;YAAC,SAAS;QAAC,CAAC;QACxK,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC;QAC7B,KAAK,IAAI,CAAC,CAAC;IACb,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AACD,SAAS,QAAQ,CAAC,KAAc,IAAsC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC"}
@@ -0,0 +1,70 @@
1
+ import type { ApprovalMode, CodexOptions, Input as CodexInput, ModelReasoningEffort, SandboxMode, WebSearchMode } from "@openai/codex-sdk";
2
+ export interface PersistentThreadOptions {
3
+ model: string;
4
+ workingDirectory: string;
5
+ skipGitRepoCheck: boolean;
6
+ sandboxMode: SandboxMode;
7
+ approvalPolicy: ApprovalMode;
8
+ modelReasoningEffort?: ModelReasoningEffort;
9
+ networkAccessEnabled: boolean;
10
+ webSearchMode: WebSearchMode;
11
+ }
12
+ interface PersistentRunOptions {
13
+ onDelta?: (delta: string) => void;
14
+ outputSchema?: unknown;
15
+ signal?: AbortSignal;
16
+ }
17
+ interface PersistentRunResult {
18
+ finalResponse: string;
19
+ }
20
+ interface AppServerOptions {
21
+ apiKey?: string;
22
+ baseUrl?: string;
23
+ codexPathOverride?: string;
24
+ config?: CodexOptions["config"];
25
+ }
26
+ export declare class PersistentCodexAppServer {
27
+ private readonly options;
28
+ private child;
29
+ private starting;
30
+ private closed;
31
+ private nextRequestId;
32
+ private stdoutBuffer;
33
+ private readonly pending;
34
+ private readonly listeners;
35
+ private readonly stderr;
36
+ constructor(options: AppServerOptions);
37
+ startThread(options: PersistentThreadOptions): PersistentCodexThread;
38
+ runTurn(threadOptions: PersistentThreadOptions, existingThreadId: string | null, input: CodexInput, options: PersistentRunOptions): Promise<{
39
+ threadId: string;
40
+ result: PersistentRunResult;
41
+ }>;
42
+ close(): Promise<void>;
43
+ private createThread;
44
+ private waitForTurn;
45
+ private ensureStarted;
46
+ private start;
47
+ private request;
48
+ private notify;
49
+ private consumeStdout;
50
+ private failProcess;
51
+ }
52
+ declare class PersistentCodexThread {
53
+ private readonly server;
54
+ private readonly options;
55
+ private id;
56
+ constructor(server: PersistentCodexAppServer, options: PersistentThreadOptions);
57
+ run(input: CodexInput, options?: PersistentRunOptions): Promise<PersistentRunResult>;
58
+ /** Same shape as the SDK's streamed turn: agent message updates with the text so far, then the complete text. */
59
+ runStreamed(input: CodexInput, options?: PersistentRunOptions): Promise<{
60
+ events: AsyncGenerator<{
61
+ type: string;
62
+ item?: {
63
+ type: string;
64
+ text?: string;
65
+ };
66
+ }>;
67
+ }>;
68
+ }
69
+ export {};
70
+ //# sourceMappingURL=persistent-app-server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"persistent-app-server.d.ts","sourceRoot":"","sources":["../../src/persistent-app-server.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,KAAK,IAAI,UAAU,EAAE,oBAAoB,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAE3I,MAAM,WAAW,uBAAuB;IACtC,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,EAAE,MAAM,CAAC;IACzB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,W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,mBAAmB,CAAA;KAAE,CAAC,CAsBnM;IAEK,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAY3B;YAEa,YAAY;IAgB1B,OAAO,CAAC,WAAW;YAsEL,aAAa;YAQb,KAAK;IAkCnB,OAAO,CAAC,OAAO;IAcf,OAAO,CAAC,MAAM;IAMd,OAAO,CAAC,aAAa;IA2BrB,OAAO,CAAC,WAAW;CAKpB;AAED,cAAM,qBAAqB;IAGb,OAAO,CAAC,QAAQ,CAAC,MAAM;IAA4B,OAAO,CAAC,QAAQ,CAAC,OAAO;IAFvF,OAAO,CAAC,EAAE,CAAuB;IAEjC,YAA6B,MAAM,EAAE,wBAAwB,EAAmB,OAAO,EAAE,uBAAuB,EAAI;IAE9G,GAAG,CAAC,KAAK,EAAE,UAAU,EAAE,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAI7F;IAED,iHAAiH;IAC3G,WAAW,CAAC,KAAK,EAAE,UAAU,EAAE,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC;QAAE,MAAM,EAAE,cAAc,CAAC;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,IAAI,CAAC,EAAE;gBAAE,IAAI,EAAE,MAAM,CAAC;gBAAC,IAAI,CAAC,EAAE,MAAM,CAAA;aAAE,CAAA;SAAE,CAAC,CAAA;KAAE,CAAC,CAkBtK;CACF"}
@@ -0,0 +1,382 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createRequire } from "node:module";
3
+ export class PersistentCodexAppServer {
4
+ options;
5
+ child;
6
+ starting;
7
+ closed = false;
8
+ nextRequestId = 1;
9
+ stdoutBuffer = "";
10
+ pending = new Map();
11
+ listeners = new Set();
12
+ stderr = [];
13
+ constructor(options) {
14
+ this.options = options;
15
+ }
16
+ startThread(options) {
17
+ return new PersistentCodexThread(this, options);
18
+ }
19
+ async runTurn(threadOptions, existingThreadId, input, options) {
20
+ await this.ensureStarted();
21
+ const threadId = existingThreadId ?? await this.createThread(threadOptions);
22
+ const completion = this.waitForTurn(threadId, options.signal, options.onDelta);
23
+ try {
24
+ const response = asRecord(await this.request("turn/start", {
25
+ threadId,
26
+ input: toUserInput(input),
27
+ cwd: threadOptions.workingDirectory,
28
+ approvalPolicy: threadOptions.approvalPolicy,
29
+ model: threadOptions.model,
30
+ effort: threadOptions.modelReasoningEffort ?? null,
31
+ outputSchema: options.outputSchema ?? null,
32
+ }));
33
+ const turn = asRecord(response.turn);
34
+ const turnId = requireString(turn.id, "Codex app-server turn id");
35
+ completion.setTurnId(turnId);
36
+ return { threadId, result: { finalResponse: await completion.result } };
37
+ }
38
+ catch (error) {
39
+ completion.cancel();
40
+ throw error;
41
+ }
42
+ }
43
+ async close() {
44
+ this.closed = true;
45
+ const child = this.child;
46
+ this.child = undefined;
47
+ this.starting = undefined;
48
+ if (!child || child.exitCode !== null || child.signalCode !== null)
49
+ return;
50
+ child.stdin.end();
51
+ await Promise.race([
52
+ new Promise((resolve) => child.once("exit", () => resolve())),
53
+ new Promise((resolve) => setTimeout(resolve, 1_000)),
54
+ ]);
55
+ if (child.exitCode === null && child.signalCode === null)
56
+ child.kill();
57
+ }
58
+ async createThread(options) {
59
+ const config = {
60
+ web_search: options.webSearchMode,
61
+ sandbox_workspace_write: { network_access: options.networkAccessEnabled },
62
+ };
63
+ const response = asRecord(await this.request("thread/start", {
64
+ model: options.model,
65
+ cwd: options.workingDirectory,
66
+ approvalPolicy: options.approvalPolicy,
67
+ sandbox: options.sandboxMode,
68
+ config,
69
+ ephemeral: true,
70
+ }));
71
+ return requireString(asRecord(response.thread).id, "Codex app-server thread id");
72
+ }
73
+ waitForTurn(threadId, signal, onDelta) {
74
+ let turnId;
75
+ let finalResponse = "";
76
+ let settled = false;
77
+ let resolveResult;
78
+ let rejectResult;
79
+ const result = new Promise((resolve, reject) => { resolveResult = resolve; rejectResult = reject; });
80
+ void result.catch(() => undefined);
81
+ const cleanup = () => {
82
+ this.listeners.delete(onMessage);
83
+ signal?.removeEventListener("abort", onAbort);
84
+ };
85
+ const settle = (value) => {
86
+ if (settled)
87
+ return;
88
+ settled = true;
89
+ cleanup();
90
+ if (value instanceof Error)
91
+ rejectResult(value);
92
+ else
93
+ resolveResult(value);
94
+ };
95
+ const onMessage = (message) => {
96
+ const params = asOptionalRecord(message.params);
97
+ if (message.method === "process/error") {
98
+ settle(new Error(typeof params?.message === "string" ? params.message : "Codex app-server stopped"));
99
+ return;
100
+ }
101
+ if (!params || params.threadId !== threadId)
102
+ return;
103
+ if (turnId && typeof params.turnId === "string" && params.turnId !== turnId)
104
+ return;
105
+ if (message.method === "item/agentMessage/delta") {
106
+ if (typeof params.delta === "string")
107
+ onDelta?.(params.delta);
108
+ return;
109
+ }
110
+ if (message.method === "item/completed") {
111
+ const item = asOptionalRecord(params.item);
112
+ if (item?.type === "agentMessage" && typeof item.text === "string")
113
+ finalResponse = item.text;
114
+ return;
115
+ }
116
+ if (message.method === "turn/completed") {
117
+ const turn = asOptionalRecord(params.turn);
118
+ if (turn?.status === "failed") {
119
+ const error = asOptionalRecord(turn.error);
120
+ settle(new Error(typeof error?.message === "string" ? error.message : "Codex turn failed"));
121
+ return;
122
+ }
123
+ const items = Array.isArray(turn?.items) ? turn.items : [];
124
+ for (const value of items) {
125
+ const item = asOptionalRecord(value);
126
+ if (item?.type === "agentMessage" && typeof item.text === "string")
127
+ finalResponse = item.text;
128
+ }
129
+ settle(finalResponse);
130
+ return;
131
+ }
132
+ if (message.method === "error" && params.willRetry !== true) {
133
+ const error = asOptionalRecord(params.error);
134
+ settle(new Error(typeof error?.message === "string" ? error.message : "Codex turn failed"));
135
+ }
136
+ };
137
+ const onAbort = () => {
138
+ if (turnId)
139
+ void this.request("turn/interrupt", { threadId, turnId }).catch(() => undefined);
140
+ settle(signal?.reason instanceof Error ? signal.reason : new Error("Codex turn aborted"));
141
+ };
142
+ this.listeners.add(onMessage);
143
+ signal?.addEventListener("abort", onAbort, { once: true });
144
+ if (signal?.aborted)
145
+ onAbort();
146
+ return {
147
+ result,
148
+ setTurnId(value) { turnId = value; if (signal?.aborted)
149
+ onAbort(); },
150
+ cancel() { settle(new Error("Codex turn cancelled")); void result.catch(() => undefined); },
151
+ };
152
+ }
153
+ async ensureStarted() {
154
+ if (this.closed)
155
+ throw new Error("Codex app-server is closed");
156
+ if (this.starting)
157
+ return this.starting;
158
+ if (this.child && this.child.exitCode === null && !this.child.killed)
159
+ return;
160
+ this.starting = this.start().finally(() => { this.starting = undefined; });
161
+ await this.starting;
162
+ }
163
+ async start() {
164
+ const command = resolveCommand(this.options.codexPathOverride);
165
+ const args = [...command.args, "app-server", "--stdio", ...configArguments(this.options.config, this.options.baseUrl)];
166
+ const env = { ...process.env, CODEX_INTERNAL_ORIGINATOR_OVERRIDE: "agent_os" };
167
+ if (this.options.apiKey)
168
+ env.CODEX_API_KEY = this.options.apiKey;
169
+ const child = spawn(command.executable, args, { env, stdio: ["pipe", "pipe", "pipe"] });
170
+ this.child = child;
171
+ this.stdoutBuffer = "";
172
+ this.stderr.length = 0;
173
+ child.stdout.setEncoding("utf8");
174
+ child.stderr.setEncoding("utf8");
175
+ child.stdout.on("data", (chunk) => this.consumeStdout(chunk));
176
+ child.stderr.on("data", (chunk) => {
177
+ this.stderr.push(chunk);
178
+ if (this.stderr.length > 20)
179
+ this.stderr.shift();
180
+ });
181
+ child.once("error", (error) => this.failProcess(error));
182
+ child.once("exit", (code, processSignal) => {
183
+ if (this.child === child)
184
+ this.child = undefined;
185
+ if (!this.closed)
186
+ this.failProcess(new Error(`Codex app-server exited with ${processSignal ? `signal ${processSignal}` : `code ${code ?? 1}`}${this.stderr.length ? `: ${this.stderr.join("").trim()}` : ""}`));
187
+ });
188
+ try {
189
+ await this.request("initialize", {
190
+ clientInfo: { name: "agent-os", title: "PLAIOS", version: "0.1.2" },
191
+ capabilities: { experimentalApi: true, requestAttestation: false },
192
+ });
193
+ this.notify("initialized");
194
+ }
195
+ catch (error) {
196
+ if (this.child === child)
197
+ this.child = undefined;
198
+ child.kill();
199
+ throw error;
200
+ }
201
+ }
202
+ request(method, params) {
203
+ const child = this.child;
204
+ if (!child || child.exitCode !== null || child.killed)
205
+ return Promise.reject(new Error("Codex app-server is not running"));
206
+ const id = this.nextRequestId++;
207
+ return new Promise((resolve, reject) => {
208
+ this.pending.set(id, { resolve, reject });
209
+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method, id, params })}\n`, (error) => {
210
+ if (!error)
211
+ return;
212
+ this.pending.delete(id);
213
+ reject(error);
214
+ });
215
+ });
216
+ }
217
+ notify(method, params) {
218
+ const child = this.child;
219
+ if (!child || child.exitCode !== null || child.killed)
220
+ return;
221
+ child.stdin.write(`${JSON.stringify(params === undefined ? { jsonrpc: "2.0", method } : { jsonrpc: "2.0", method, params })}\n`);
222
+ }
223
+ consumeStdout(chunk) {
224
+ this.stdoutBuffer += chunk;
225
+ while (true) {
226
+ const newline = this.stdoutBuffer.indexOf("\n");
227
+ if (newline < 0)
228
+ return;
229
+ const line = this.stdoutBuffer.slice(0, newline).trim();
230
+ this.stdoutBuffer = this.stdoutBuffer.slice(newline + 1);
231
+ if (!line)
232
+ continue;
233
+ let message;
234
+ try {
235
+ message = JSON.parse(line);
236
+ }
237
+ catch {
238
+ continue;
239
+ }
240
+ if (message.id !== undefined && !message.method) {
241
+ const pending = this.pending.get(message.id);
242
+ if (!pending)
243
+ continue;
244
+ this.pending.delete(message.id);
245
+ if (message.error)
246
+ pending.reject(new Error(message.error.message ?? "Codex app-server request failed"));
247
+ else
248
+ pending.resolve(message.result);
249
+ continue;
250
+ }
251
+ if (message.id !== undefined && message.method) {
252
+ this.child?.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id: message.id, error: { code: -32601, message: "PLAIOS does not support this server request" } })}\n`);
253
+ continue;
254
+ }
255
+ for (const listener of this.listeners)
256
+ listener(message);
257
+ }
258
+ }
259
+ failProcess(error) {
260
+ for (const pending of this.pending.values())
261
+ pending.reject(error);
262
+ this.pending.clear();
263
+ for (const listener of this.listeners)
264
+ listener({ method: "process/error", params: { message: error.message } });
265
+ }
266
+ }
267
+ class PersistentCodexThread {
268
+ server;
269
+ options;
270
+ id = null;
271
+ constructor(server, options) {
272
+ this.server = server;
273
+ this.options = options;
274
+ }
275
+ async run(input, options = {}) {
276
+ const response = await this.server.runTurn(this.options, this.id, input, options);
277
+ this.id = response.threadId;
278
+ return response.result;
279
+ }
280
+ /** Same shape as the SDK's streamed turn: agent message updates with the text so far, then the complete text. */
281
+ async runStreamed(input, options = {}) {
282
+ const queue = [];
283
+ let text = "";
284
+ let done = false;
285
+ let failure;
286
+ let wake = () => { };
287
+ void this.run(input, { ...options, onDelta: (delta) => { text += delta; queue.push(text); wake(); } })
288
+ .then((result) => { queue.push(result.finalResponse); })
289
+ .catch((error) => { failure = error; })
290
+ .finally(() => { done = true; wake(); });
291
+ const events = (async function* () {
292
+ for (;;) {
293
+ while (queue.length)
294
+ yield { type: "item.updated", item: { type: "agent_message", text: queue.shift() } };
295
+ if (done) {
296
+ if (failure)
297
+ throw failure;
298
+ return;
299
+ }
300
+ await new Promise((resolve) => { wake = resolve; });
301
+ }
302
+ })();
303
+ return { events };
304
+ }
305
+ }
306
+ function toUserInput(input) {
307
+ if (typeof input === "string")
308
+ return [{ type: "text", text: input, text_elements: [] }];
309
+ return input.map((item) => item.type === "text"
310
+ ? { type: "text", text: item.text, text_elements: [] }
311
+ : { type: "localImage", path: item.path });
312
+ }
313
+ function resolveCommand(override) {
314
+ if (override)
315
+ return override.endsWith(".js") || override.endsWith(".mjs")
316
+ ? { executable: process.execPath, args: [override] }
317
+ : { executable: override, args: [] };
318
+ const sdkUrl = import.meta.resolve("@openai/codex-sdk");
319
+ const codexScript = createRequire(sdkUrl).resolve("@openai/codex/bin/codex.js");
320
+ return { executable: process.execPath, args: [codexScript] };
321
+ }
322
+ function configArguments(config, baseUrl) {
323
+ const values = [];
324
+ if (config)
325
+ flattenConfig(config, "", values);
326
+ if (baseUrl)
327
+ values.push(`openai_base_url=${JSON.stringify(baseUrl)}`);
328
+ return values.flatMap((value) => ["--config", value]);
329
+ }
330
+ function flattenConfig(value, prefix, output) {
331
+ if (!isPlainRecord(value)) {
332
+ if (!prefix)
333
+ throw new Error("Codex config overrides must be an object");
334
+ output.push(`${prefix}=${toToml(value, prefix)}`);
335
+ return;
336
+ }
337
+ for (const [key, child] of Object.entries(value)) {
338
+ if (!key)
339
+ throw new Error("Codex config keys must be non-empty");
340
+ if (child === undefined)
341
+ continue;
342
+ const path = prefix ? `${prefix}.${key}` : key;
343
+ if (isPlainRecord(child) && Object.keys(child).length > 0)
344
+ flattenConfig(child, path, output);
345
+ else
346
+ output.push(`${path}=${toToml(child, path)}`);
347
+ }
348
+ }
349
+ function toToml(value, path) {
350
+ if (typeof value === "string")
351
+ return JSON.stringify(value);
352
+ if (typeof value === "boolean")
353
+ return value ? "true" : "false";
354
+ if (typeof value === "number" && Number.isFinite(value))
355
+ return String(value);
356
+ if (Array.isArray(value))
357
+ return `[${value.map((item, index) => toToml(item, `${path}[${index}]`)).join(", ")}]`;
358
+ if (isPlainRecord(value))
359
+ return `{${Object.entries(value).map(([key, child]) => `${/^[A-Za-z0-9_-]+$/.test(key) ? key : JSON.stringify(key)} = ${toToml(child, `${path}.${key}`)}`).join(", ")}}`;
360
+ throw new Error(`Unsupported Codex config value at ${path}`);
361
+ }
362
+ function asRecord(value) {
363
+ const record = asOptionalRecord(value);
364
+ if (!record)
365
+ throw new Error("Codex app-server returned an invalid response");
366
+ return record;
367
+ }
368
+ function asOptionalRecord(value) {
369
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined;
370
+ }
371
+ function isPlainRecord(value) {
372
+ if (!asOptionalRecord(value))
373
+ return false;
374
+ const prototype = Object.getPrototypeOf(value);
375
+ return prototype === Object.prototype || prototype === null;
376
+ }
377
+ function requireString(value, label) {
378
+ if (typeof value !== "string" || !value)
379
+ throw new Error(`${label} is missing`);
380
+ return value;
381
+ }
382
+ //# sourceMappingURL=persistent-app-server.js.map
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G,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,MAAM,MAAM,CAAC,KAAK,EAAE,GAAG,IAAI,IAAI,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC;IACnM,MAAM,IAAI,KAAK,CAAC,qCAAqC,IAAI,EAAE,CAAC,CAAC;AAC/D,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC9B,MAAM,MAAM,GAAG,gBAAgB,CAAC,KAAK,CAAC,CAAC;IACvC,IAAI,CAAC,MAAM;QAAE,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;IAC9E,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAc;IACtC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAgC,CAAC,CAAC,CAAC,SAAS,CAAC;AAC7H,CAAC;AAED,SAAS,aAAa,CAAC,KAAc;IACnC,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC3C,MAAM,SAAS,GAAG,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC/C,OAAO,SAAS,KAAK,MAAM,CAAC,SAAS,IAAI,SAAS,KAAK,IAAI,CAAC;AAC9D,CAAC;AAED,SAAS,aAAa,CAAC,KAAc,EAAE,KAAa;IAClD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK;QAAE,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,aAAa,CAAC,CAAC;IAChF,OAAO,KAAK,CAAC;AACf,CAAC"}
@@ -0,0 +1,4 @@
1
+ import { type MicrofrontendProps } from "@plaios/microfrontend";
2
+ import type { CodexProviderData } from "../types.js";
3
+ export default function CodexAIMicrofrontend({ component, data, onSaveConfig }: MicrofrontendProps<CodexProviderData>): import("react").JSX.Element;
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../web/ai/index.tsx"],"names":[],"mappings":"AAEA,OAAO,EAA8H,KAAK,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC5L,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAErD,MAAM,CAAC,OAAO,UAAU,oBAAoB,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,YAAY,EAAE,EAAE,kBAAkB,CAAC,iBAAiB,CAAC,+BAYpH"}
@@ -0,0 +1,8 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { Badge, Card, CardContent, CardDescription, CardHeader, CardTitle, ConfigurationEditor, InstanceSummary, MicrofrontendFrame } from "@plaios/microfrontend";
4
+ export default function CodexAIMicrofrontend({ component, data, onSaveConfig }) {
5
+ return _jsxs(MicrofrontendFrame, { component: component, title: "Codex AI", description: "Configure the model adapter and inspect the security boundary used for PLAIOS requests.", children: [_jsxs("div", { className: "grid gap-5 xl:grid-cols-[minmax(0,1fr)_340px]", children: [_jsx(ConfigurationEditor, { component: component, onSaveConfig: onSaveConfig }), _jsxs("div", { className: "space-y-5", children: [_jsxs(Card, { children: [_jsxs(CardHeader, { children: [_jsxs("div", { className: "flex items-center justify-between gap-3", children: [_jsx(CardTitle, { children: "Provider status" }), _jsx(Badge, { variant: "success", children: "Ready" })] }), _jsx(CardDescription, { children: "Resolved Codex runtime configuration." })] }), _jsxs(CardContent, { className: "space-y-3 text-sm", children: [_jsx(Metric, { label: "Provider", value: data?.provider ?? "codex" }), _jsx(Metric, { label: "Model", value: data?.model ?? String(component.config.model ?? "Not configured") }), _jsx(Metric, { label: "Credentials", value: data?.credentialMode === "api-key" ? "API key" : "Local Codex session" }), _jsx(Metric, { label: "Process", value: data?.persistentProcess === false ? "Per request" : "Persistent" }), _jsx(Metric, { label: "Reasoning", value: data?.modelReasoningEffort ?? "Model default" })] })] }), _jsxs(Card, { children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: "Security boundary" }), _jsx(CardDescription, { children: "Capabilities remain disabled unless explicitly enabled." })] }), _jsxs(CardContent, { className: "space-y-3 text-sm", children: [_jsx(Metric, { label: "Sandbox", value: data?.sandboxMode ?? String(component.config.sandboxMode ?? "read-only") }), _jsx(Metric, { label: "Approvals", value: data?.approvalPolicy ?? String(component.config.approvalPolicy ?? "never") }), _jsx(Metric, { label: "Network", value: data?.networkAccessEnabled ? "Enabled" : "Disabled" }), _jsx(Metric, { label: "Web search", value: data?.webSearchMode ?? "disabled" })] })] }), _jsx(InstanceSummary, { component: component })] })] }), _jsxs(Card, { children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: "Execution context" }), _jsx(CardDescription, { children: "The directory supplied to new ephemeral Codex threads." })] }), _jsx(CardContent, { children: _jsx("code", { className: "block break-all border bg-muted/30 p-3 text-xs", children: data?.workingDirectory ?? String(component.config.workingDirectory ?? "Runtime project root") }) })] })] });
6
+ }
7
+ function Metric({ label, value }) { return _jsxs("div", { className: "flex items-start justify-between gap-4", children: [_jsx("span", { className: "text-muted-foreground", children: label }), _jsx("span", { className: "max-w-48 break-all text-right font-mono text-xs", children: value })] }); }
8
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../web/ai/index.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,WAAW,EAAE,eAAe,EAAE,UAAU,EAAE,SAAS,EAAE,mBAAmB,EAAE,eAAe,EAAE,kBAAkB,EAA2B,MAAM,uBAAuB,CAAC;AAG5L,MAAM,CAAC,OAAO,UAAU,oBAAoB,CAAC,EAAE,SAAS,EAAE,IAAI,EAAE,YAAY,E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codex-session";
5
+ workingDirectory: string;
6
+ sandboxMode: string;
7
+ approvalPolicy: string;
8
+ networkAccessEnabled: boolean;
9
+ webSearchMode: string;
10
+ modelReasoningEffort?: string;
11
+ persistentProcess: boolean;
12
+ }
13
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../web/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,OAAO,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,cAAc,EAAE,SAAS,GAAG,eAAe,CAAC;IAC5C,gBAAgB,EAAE,MAAM,CAAC;IACzB,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc,EAAE,MAAM,CAAC;IACvB,oBAAoB,EAAE,OAAO,CAAC;IAC9B,aAAa,EAAE,MAAM,CAAC;IACtB,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,iBAAiB,EAAE,OAAO,CAAC;CAC5B"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../web/types.ts"],"names":[],"mappings":""}
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@plaios/codex",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.7",
4
+ "description": "Codex AI provider and management surface for PLAIOS",
5
+ "keywords": [
6
+ "plaios",
7
+ "capability",
8
+ "system2",
9
+ "ai",
10
+ "codex",
11
+ "openai"
12
+ ],
13
+ "private": false,
14
+ "type": "module",
15
+ "sideEffects": [
16
+ "**/*.css"
17
+ ],
18
+ "files": [
19
+ "dist",
20
+ "web",
21
+ "agent-os.package.yaml",
22
+ "README.md"
23
+ ],
24
+ "main": "./dist/src/index.js",
25
+ "types": "./dist/src/index.d.ts",
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/src/index.d.ts",
29
+ "import": "./dist/src/index.js"
30
+ },
31
+ "./web/ai": {
32
+ "types": "./dist/web/ai/index.d.ts",
33
+ "import": "./dist/web/ai/index.js"
34
+ },
35
+ "./web/styles.css": "./web/styles.css"
36
+ },
37
+ "dependencies": {
38
+ "@openai/codex-sdk": "^0.163.0",
39
+ "@plaios/systems": "0.1.0",
40
+ "@plaios/microfrontend": "0.1.5",
41
+ "@plaios/core": "0.2.0"
42
+ },
43
+ "peerDependencies": {
44
+ "react": ">=19.0.0"
45
+ },
46
+ "devDependencies": {
47
+ "@types/node": "24.13.3",
48
+ "@types/react": "^19.0.0",
49
+ "react": "19.2.4",
50
+ "typescript": "7.0.2"
51
+ },
52
+ "engines": {
53
+ "node": ">=22.5.0"
54
+ },
55
+ "publishConfig": {
56
+ "access": "public"
57
+ },
58
+ "scripts": {
59
+ "build": "tsc -p tsconfig.json",
60
+ "test": "pnpm build && node --test test/**/*.test.mjs",
61
+ "typecheck": "tsc --noEmit -p tsconfig.json"
62
+ }
6
63
  }
@@ -0,0 +1,20 @@
1
+ "use client";
2
+
3
+ import { Badge, Card, CardContent, CardDescription, CardHeader, CardTitle, ConfigurationEditor, InstanceSummary, MicrofrontendFrame, type MicrofrontendProps } from "@plaios/microfrontend";
4
+ import type { CodexProviderData } from "../types.js";
5
+
6
+ export default function CodexAIMicrofrontend({ component, data, onSaveConfig }: MicrofrontendProps<CodexProviderData>) {
7
+ return <MicrofrontendFrame component={component} title="Codex AI" description="Configure the model adapter and inspect the security boundary used for PLAIOS requests.">
8
+ <div className="grid gap-5 xl:grid-cols-[minmax(0,1fr)_340px]">
9
+ <ConfigurationEditor component={component} onSaveConfig={onSaveConfig} />
10
+ <div className="space-y-5">
11
+ <Card><CardHeader><div className="flex items-center justify-between gap-3"><CardTitle>Provider status</CardTitle><Badge variant="success">Ready</Badge></div><CardDescription>Resolved Codex runtime configuration.</CardDescription></CardHeader><CardContent className="space-y-3 text-sm"><Metric label="Provider" value={data?.provider ?? "codex"} /><Metric label="Model" value={data?.model ?? String(component.config.model ?? "Not configured")} /><Metric label="Credentials" value={data?.credentialMode === "api-key" ? "API key" : "Local Codex session"} /><Metric label="Process" value={data?.persistentProcess === false ? "Per request" : "Persistent"} /><Metric label="Reasoning" value={data?.modelReasoningEffort ?? "Model default"} /></CardContent></Card>
12
+ <Card><CardHeader><CardTitle>Security boundary</CardTitle><CardDescription>Capabilities remain disabled unless explicitly enabled.</CardDescription></CardHeader><CardContent className="space-y-3 text-sm"><Metric label="Sandbox" value={data?.sandboxMode ?? String(component.config.sandboxMode ?? "read-only")} /><Metric label="Approvals" value={data?.approvalPolicy ?? String(component.config.approvalPolicy ?? "never")} /><Metric label="Network" value={data?.networkAccessEnabled ? "Enabled" : "Disabled"} /><Metric label="Web search" value={data?.webSearchMode ?? "disabled"} /></CardContent></Card>
13
+ <InstanceSummary component={component} />
14
+ </div>
15
+ </div>
16
+ <Card><CardHeader><CardTitle>Execution context</CardTitle><CardDescription>The directory supplied to new ephemeral Codex threads.</CardDescription></CardHeader><CardContent><code className="block break-all border bg-muted/30 p-3 text-xs">{data?.workingDirectory ?? String(component.config.workingDirectory ?? "Runtime project root")}</code></CardContent></Card>
17
+ </MicrofrontendFrame>;
18
+ }
19
+
20
+ function Metric({ label, value }: { label: string; value: string }) { return <div className="flex items-start justify-between gap-4"><span className="text-muted-foreground">{label}</span><span className="max-w-48 break-all text-right font-mono text-xs">{value}</span></div>; }
package/web/styles.css ADDED
@@ -0,0 +1,3 @@
1
+ @import "@plaios/microfrontend/styles.css";
2
+
3
+ @source ".";
package/web/types.ts ADDED
@@ -0,0 +1,12 @@
1
+ export interface CodexProviderData {
2
+ provider: "codex";
3
+ model: string;
4
+ credentialMode: "api-key" | "codex-session";
5
+ workingDirectory: string;
6
+ sandboxMode: string;
7
+ approvalPolicy: string;
8
+ networkAccessEnabled: boolean;
9
+ webSearchMode: string;
10
+ modelReasoningEffort?: string;
11
+ persistentProcess: boolean;
12
+ }