@open-document/core 0.14.1 → 0.14.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{build-I0cgoERP.js → build-4K9V8ysT.js} +1 -1
- package/dist/{check-Dys96QSL.js → check-B40JlWME.js} +3 -3
- package/dist/cli/bin.js +9 -9
- package/dist/{context-C-osJW5f.js → context-Clm_nmr1.js} +1 -1
- package/dist/{dev-CC4PrIOC.js → dev-De3pLYn_.js} +1 -1
- package/dist/{diff-DhutD4TJ.js → diff-nU9ybiMk.js} +2 -2
- package/dist/{export-KrajVJO7.js → export-B9rrNBx2.js} +3 -3
- package/dist/{import-Yv34za3L.js → import-C3542Wry.js} +3 -3
- package/dist/ops/index.js +2 -2
- package/dist/{ops-Dux5HlkH.js → ops-ByJnGyuE.js} +1 -1
- package/dist/{preview-7eqn9Wzf.js → preview-id9mj3IU.js} +1 -1
- package/dist/{session-BSbrC5gK.js → session-CdkoJhi1.js} +15 -6
- package/dist/{templates-s-VLTSRc.js → templates-UJ_v7H-a.js} +3 -3
- package/dist/vite/index.js +1 -1
- package/package.json +6 -1
- package/src/agent/check-after-turn.ts +59 -0
- package/src/agent/detect.ts +158 -0
- package/src/agent/install.ts +73 -0
- package/src/agent/prompt.ts +175 -0
- package/src/agent/provider.ts +126 -0
- package/src/agent/providers/codex.ts +209 -0
- package/src/agent/providers/index.ts +7 -0
- package/src/agent/providers/sdk-types.ts +71 -0
- package/src/agent/runner.ts +392 -0
- package/src/agent/status.ts +64 -0
- package/src/agent/store.ts +271 -0
- package/src/agent/types.ts +174 -0
- package/src/diagram/index.ts +46 -0
- package/src/diagram/layout.ts +627 -0
- package/src/diagram/parse.ts +335 -0
- package/src/diagram/render.ts +162 -0
- package/src/editing/placeholder-id.ts +2 -0
- package/src/app/lib/chart.test.ts +0 -123
- package/src/app/lib/docx/ooxml.test.ts +0 -484
- package/src/app/lib/flow-measure.test.ts +0 -30
- package/src/app/lib/flow.test.ts +0 -129
- package/src/app/lib/footnotes.test.tsx +0 -102
- package/src/app/lib/i18n.test.ts +0 -24
- package/src/app/lib/inspector/inline-edit.test.ts +0 -244
- package/src/app/lib/page-range.test.ts +0 -104
- package/src/app/lib/records.test.ts +0 -38
- package/src/app/lib/sdk.test.ts +0 -30
- package/src/app/lib/view-mode.test.ts +0 -46
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { UNTITLED_DOC_ID_RE } from '../editing/placeholder-id.ts';
|
|
2
|
+
import { parseQuestions } from './provider.ts';
|
|
3
|
+
import type { AgentCheckFinding, AgentQuestion, AgentTurnContext } from './types.ts';
|
|
4
|
+
|
|
5
|
+
const SECTION_BY_SECTION =
|
|
6
|
+
'Write a new document section by section so the user can follow along on the page: first replace the file with the imports, meta (keeping its existing createdAt), design and the opening section only, then add each remaining section with its own separate edit, keeping the file compiling after every write.';
|
|
7
|
+
|
|
8
|
+
const DOC_SLUG =
|
|
9
|
+
"This document's folder still has a placeholder name. Never rename or move the folder yourself: once the document has content, end your final reply with a slug for it on a line of its own as <doc-slug>short-kebab-case-english-slug</doc-slug>, and open-doc renames the folder from it.";
|
|
10
|
+
|
|
11
|
+
export type PromptOptions = {
|
|
12
|
+
/** The workspace's documents folder, `docs` unless the config says otherwise. */
|
|
13
|
+
docsDir: string;
|
|
14
|
+
/** The dev server's own origin, for the single-page preview. */
|
|
15
|
+
origin?: string;
|
|
16
|
+
/** False when the agent's sandbox cannot start a browser, so it cannot check or preview. */
|
|
17
|
+
canOpenBrowser?: boolean;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export function systemPromptAppend(askInstruction: string, opts: PromptOptions): string {
|
|
21
|
+
const preview = opts.origin
|
|
22
|
+
? `${opts.origin}/d/<id>/preview?p=<page>`
|
|
23
|
+
: '/d/<id>/preview?p=<page> on the dev server';
|
|
24
|
+
return [
|
|
25
|
+
'You are running inside the open-doc dev server, driven from its in-app agent panel in the browser rather than a terminal.',
|
|
26
|
+
`The workspace is an open-doc project: documents live under ${opts.docsDir}/<id>/index.tsx and the dev server hot-reloads every edit, so the user sees changes immediately.`,
|
|
27
|
+
'Use the project skills: create-doc to draft a new document, apply-comments to resolve @doc-comment markers left by the inspector, create-theme for themes, and doc-authoring as the technical reference before writing a page.',
|
|
28
|
+
SECTION_BY_SECTION,
|
|
29
|
+
opts.canOpenBrowser === false
|
|
30
|
+
? 'Your sandbox cannot start a browser, so `open-doc check` and the page preview fail here: do not run them. open-doc runs the check itself once your turn ends and shows the user what it finds, so keep the file compiling after every write.'
|
|
31
|
+
: `After editing a document, run \`pnpm exec open-doc check <id>\` and fix what it reports. To look at one page as it prints, open ${preview} and wait for [data-od-preview-ready="true"].`,
|
|
32
|
+
'Keep replies short and concrete: the panel is narrow. Prefer doing the work over describing it, and finish with a one-line summary of what changed.',
|
|
33
|
+
askInstruction,
|
|
34
|
+
].join(' ');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function buildTurnPrompt(
|
|
38
|
+
text: string,
|
|
39
|
+
context: AgentTurnContext | undefined,
|
|
40
|
+
docsDir = 'docs',
|
|
41
|
+
): string {
|
|
42
|
+
const lines = contextLines(context, docsDir);
|
|
43
|
+
if (lines.length === 0) return text;
|
|
44
|
+
return `${text}\n\n<open-doc-context>\n${lines.join('\n')}\n</open-doc-context>`;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Document titles and selected text come from document content, so they sit in
|
|
48
|
+
// their own tags with `<` escaped and can't close the context block.
|
|
49
|
+
const escapeTag = (s: string) => s.replace(/</g, '<');
|
|
50
|
+
|
|
51
|
+
function contextLines(context: AgentTurnContext | undefined, docsDir: string): string[] {
|
|
52
|
+
if (!context?.docId) return [];
|
|
53
|
+
const file = `${docsDir}/${context.docId}/index.tsx`;
|
|
54
|
+
const lines: string[] = [];
|
|
55
|
+
if (context.newDoc) {
|
|
56
|
+
lines.push(
|
|
57
|
+
`${file} is a blank document created for this request. Draft the document the user describes into it with the create-doc skill: replace the placeholder content, keep the document id, and do not create another folder.`,
|
|
58
|
+
'Ask the create-doc scoping questions in a single round, only for what the request leaves unclear; skip any it already answers.',
|
|
59
|
+
SECTION_BY_SECTION,
|
|
60
|
+
DOC_SLUG,
|
|
61
|
+
);
|
|
62
|
+
return lines;
|
|
63
|
+
}
|
|
64
|
+
lines.push(`The user is viewing document "${context.docId}": ${file}.`);
|
|
65
|
+
if (UNTITLED_DOC_ID_RE.test(context.docId)) lines.push(DOC_SLUG);
|
|
66
|
+
if (context.docTitle) {
|
|
67
|
+
lines.push(`<doc-title>${escapeTag(context.docTitle)}</doc-title>`);
|
|
68
|
+
}
|
|
69
|
+
if (context.pageNumber && context.totalPages) {
|
|
70
|
+
lines.push(
|
|
71
|
+
`They are on page ${context.pageNumber} of ${context.totalPages} as the document prints.`,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
if (context.selection) {
|
|
75
|
+
const { line, column, tagName, text } = context.selection;
|
|
76
|
+
lines.push(
|
|
77
|
+
`They have selected a <${escapeTag(tagName)}> element at ${file}:${line}:${column}.${text ? ' Its text is in <selected-text>.' : ''} "This element" refers to it.`,
|
|
78
|
+
);
|
|
79
|
+
if (text) lines.push(`<selected-text>${escapeTag(text)}</selected-text>`);
|
|
80
|
+
}
|
|
81
|
+
if (context.pendingComments) {
|
|
82
|
+
lines.push(
|
|
83
|
+
`There are ${context.pendingComments} pending @doc-comment markers in this document's source.`,
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
return lines;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const DOC_SLUG_RE = /\s*<doc-slug>\s*([^<]*?)\s*<\/doc-slug>\s*/gi;
|
|
90
|
+
|
|
91
|
+
export function extractDocSlug(text: string): string | null {
|
|
92
|
+
let slug: string | null = null;
|
|
93
|
+
for (const match of text.matchAll(DOC_SLUG_RE)) slug = match[1] || slug;
|
|
94
|
+
return slug;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Also drops a tag that is still streaming in, so the marker never flashes
|
|
98
|
+
// in the transcript.
|
|
99
|
+
export function stripDocSlug(text: string): string {
|
|
100
|
+
return text
|
|
101
|
+
.replace(DOC_SLUG_RE, '\n')
|
|
102
|
+
.replace(/\s*<doc-slug>[^<]*$/i, '')
|
|
103
|
+
.trimEnd();
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** What the panel's "fix" button sends after a check the dev server ran. */
|
|
107
|
+
export function checkFixPrompt(
|
|
108
|
+
docId: string,
|
|
109
|
+
findings: AgentCheckFinding[],
|
|
110
|
+
total: number,
|
|
111
|
+
): string {
|
|
112
|
+
const lines = findings.map(
|
|
113
|
+
(f) =>
|
|
114
|
+
`- ${f.page > 0 ? `page ${f.page}` : 'document'} [${f.severity}] ${f.message}${f.loc ? ` (at ${f.loc})` : ''}`,
|
|
115
|
+
);
|
|
116
|
+
const more =
|
|
117
|
+
total > findings.length ? `\n- …and ${total - findings.length} more of the same kind` : '';
|
|
118
|
+
return `\`open-doc check\` found these problems in the document "${docId}". Fix them, keeping the content and the design otherwise as it is:\n${lines.join('\n')}${more}`;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function applyCommentsPrompt(docId: string): string {
|
|
122
|
+
return `Use the apply-comments skill to apply every pending @doc-comment marker in the document "${docId}", then remove the markers.`;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const QUESTIONS_RE = /<open-doc-questions>([\s\S]*?)<\/open-doc-questions>/i;
|
|
126
|
+
|
|
127
|
+
export const TEXT_QUESTIONS_INSTRUCTION =
|
|
128
|
+
'You cannot ask the user anything interactively here, and nothing you print in the middle of a turn can be answered. When you need answers before continuing, stop working and end your turn with a final message holding only an <open-doc-questions> block: a JSON array of at most 4 questions shaped like [{"header":"Length","question":"How long should it be?","multiSelect":false,"options":[{"label":"2-3 pages (Recommended)","description":"A short brief"}]}], each with 2 to 4 options, written in the user\'s language. The panel shows them as a form and sends the answers back as your next message. Write nothing after the block and do not continue the task in the same turn.';
|
|
129
|
+
|
|
130
|
+
// Splits a reply written under TEXT_QUESTIONS_INSTRUCTION into its prose and
|
|
131
|
+
// questions. Returns null when the reply holds no usable block.
|
|
132
|
+
export function extractQuestionBlock(
|
|
133
|
+
text: string,
|
|
134
|
+
): { text: string; questions: AgentQuestion[] } | null {
|
|
135
|
+
const match = QUESTIONS_RE.exec(text);
|
|
136
|
+
if (!match) return null;
|
|
137
|
+
const body = match[1]
|
|
138
|
+
.trim()
|
|
139
|
+
.replace(/^```(?:json)?\s*/i, '')
|
|
140
|
+
.replace(/\s*```$/, '');
|
|
141
|
+
let raw: unknown;
|
|
142
|
+
try {
|
|
143
|
+
raw = JSON.parse(body);
|
|
144
|
+
} catch {
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
const questions = parseQuestions({
|
|
148
|
+
questions: Array.isArray(raw) ? raw : (raw as { questions?: unknown } | null)?.questions,
|
|
149
|
+
});
|
|
150
|
+
if (questions.length === 0) return null;
|
|
151
|
+
return { text: text.replace(QUESTIONS_RE, '').trim(), questions };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function answersPrompt(
|
|
155
|
+
questions: AgentQuestion[],
|
|
156
|
+
answers: Record<string, string> | null,
|
|
157
|
+
): string {
|
|
158
|
+
if (!answers) {
|
|
159
|
+
return 'I skipped your questions. Continue the task with your best judgement and sensible defaults.';
|
|
160
|
+
}
|
|
161
|
+
const lines = questions.map((q) => `- ${q.question} ${answers[q.question] || '(no answer)'}`);
|
|
162
|
+
return `My answers:\n${lines.join('\n')}\n\nContinue the task with these answers.`;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// For agents whose history can't be rewound: the edited message goes on top
|
|
166
|
+
// of the old conversation, so the agent is told to set that part aside.
|
|
167
|
+
export function editedPrompt(original: string, text: string): string {
|
|
168
|
+
return `I went back and edited an earlier message of mine. Treat everything after it in this conversation, including your replies, as discarded, and respond to the edited version instead. Files keep whatever changes were already made.\n\n<original-message>\n${escapeTag(original)}\n</original-message>\n\n${text}`;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// For agents rewound to before the edited message: their history forgets the
|
|
172
|
+
// later turns, but the files on disk still hold what those turns wrote.
|
|
173
|
+
export function rewoundPrompt(text: string): string {
|
|
174
|
+
return `${text}\n\n<open-doc-note>I went back and edited this message. Files keep the changes made after it in the discarded part of this conversation, so read the current files before editing them.</open-doc-note>`;
|
|
175
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import type { AgentEffort, AgentModelOption, AgentProviderId, AgentQuestion } from './types.ts';
|
|
3
|
+
|
|
4
|
+
export type ProviderEvent =
|
|
5
|
+
| { type: 'session-id'; id: string }
|
|
6
|
+
// A point in the provider's own history that a later edit can rewind to.
|
|
7
|
+
| { type: 'checkpoint'; id: string }
|
|
8
|
+
| { type: 'text-start'; id: string }
|
|
9
|
+
| { type: 'text-delta'; id: string; text: string }
|
|
10
|
+
| { type: 'text-end'; id: string; text: string | null }
|
|
11
|
+
| { type: 'tool-start'; id: string; name: string; title: string; detail: string | null }
|
|
12
|
+
| { type: 'tool-end'; id: string; ok: boolean }
|
|
13
|
+
| { type: 'error'; text: string }
|
|
14
|
+
| { type: 'result'; durationMs: number | null; costUsd: number | null }
|
|
15
|
+
// Questions the agent wrote into its reply instead of asking through a
|
|
16
|
+
// tool: the turn ends, and the answers arrive as the next prompt.
|
|
17
|
+
| { type: 'questions'; questions: AgentQuestion[] };
|
|
18
|
+
|
|
19
|
+
export type PermissionRequest = { tool: string; title: string; detail: string | null };
|
|
20
|
+
|
|
21
|
+
export type ProviderRunOptions = {
|
|
22
|
+
cwd: string;
|
|
23
|
+
// Directories the agent may write to without asking: the deck and asset
|
|
24
|
+
// folders. Edits anywhere else (configs, package.json) need approval.
|
|
25
|
+
writableRoots: string[];
|
|
26
|
+
prompt: string;
|
|
27
|
+
systemPromptAppend: string;
|
|
28
|
+
resume: string | null;
|
|
29
|
+
resumeAt: string | null;
|
|
30
|
+
model: string | null;
|
|
31
|
+
effort: AgentEffort | null;
|
|
32
|
+
signal: AbortSignal;
|
|
33
|
+
emit: (event: ProviderEvent) => void;
|
|
34
|
+
askUser: (questions: AgentQuestion[]) => Promise<Record<string, string> | null>;
|
|
35
|
+
requestPermission: (request: PermissionRequest) => Promise<boolean>;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export interface AgentProvider {
|
|
39
|
+
id: AgentProviderId;
|
|
40
|
+
name: string;
|
|
41
|
+
sdkPackage: string;
|
|
42
|
+
cliCommand: string;
|
|
43
|
+
askInstruction: string;
|
|
44
|
+
canRewind: boolean;
|
|
45
|
+
// Whether the agent's own commands can start a browser. `open-doc check` and
|
|
46
|
+
// the page preview both drive Chromium, which Codex's macOS sandbox kills.
|
|
47
|
+
canOpenBrowser: boolean;
|
|
48
|
+
models(): Promise<AgentModelOption[]>;
|
|
49
|
+
run(opts: ProviderRunOptions): Promise<void>;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export class ProviderUnavailableError extends Error {
|
|
53
|
+
constructor(provider: AgentProvider) {
|
|
54
|
+
super(
|
|
55
|
+
`${provider.name} is not connected: install ${provider.sdkPackage} in this workspace to use it from the agent panel.`,
|
|
56
|
+
);
|
|
57
|
+
this.name = 'ProviderUnavailableError';
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const DETAIL_MAX = 400;
|
|
62
|
+
|
|
63
|
+
export function clipDetail(value: unknown): string | null {
|
|
64
|
+
if (value === undefined || value === null) return null;
|
|
65
|
+
const text = typeof value === 'string' ? value : safeJson(value);
|
|
66
|
+
if (!text) return null;
|
|
67
|
+
const oneLine = text.replace(/\s+/g, ' ').trim();
|
|
68
|
+
return oneLine.length > DETAIL_MAX ? `${oneLine.slice(0, DETAIL_MAX - 1)}…` : oneLine;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function safeJson(value: unknown): string {
|
|
72
|
+
try {
|
|
73
|
+
return JSON.stringify(value);
|
|
74
|
+
} catch {
|
|
75
|
+
return String(value);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function isInsideRoots(cwd: string, file: unknown, roots: string[]): boolean {
|
|
80
|
+
if (typeof file !== 'string' || !file) return false;
|
|
81
|
+
const resolved = path.resolve(cwd, file);
|
|
82
|
+
return roots.some((root) => {
|
|
83
|
+
const rel = path.relative(root, resolved);
|
|
84
|
+
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function relativeToCwd(cwd: string, file: unknown): string | null {
|
|
89
|
+
if (typeof file !== 'string' || !file) return null;
|
|
90
|
+
const normalizedCwd = cwd.replace(/[\\/]+$/, '');
|
|
91
|
+
if (file.startsWith(normalizedCwd)) {
|
|
92
|
+
const rest = file.slice(normalizedCwd.length).replace(/^[\\/]+/, '');
|
|
93
|
+
return rest || '.';
|
|
94
|
+
}
|
|
95
|
+
return file;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function parseQuestions(input: Record<string, unknown>): AgentQuestion[] {
|
|
99
|
+
const raw = Array.isArray(input.questions) ? input.questions : [];
|
|
100
|
+
const questions: AgentQuestion[] = [];
|
|
101
|
+
for (const q of raw) {
|
|
102
|
+
if (!q || typeof q !== 'object') continue;
|
|
103
|
+
const r = q as Record<string, unknown>;
|
|
104
|
+
const options = Array.isArray(r.options)
|
|
105
|
+
? r.options
|
|
106
|
+
.map((o) => {
|
|
107
|
+
if (!o || typeof o !== 'object') return null;
|
|
108
|
+
const opt = o as Record<string, unknown>;
|
|
109
|
+
if (typeof opt.label !== 'string') return null;
|
|
110
|
+
return {
|
|
111
|
+
label: opt.label,
|
|
112
|
+
description: typeof opt.description === 'string' ? opt.description : undefined,
|
|
113
|
+
};
|
|
114
|
+
})
|
|
115
|
+
.filter((o): o is { label: string; description: string | undefined } => o !== null)
|
|
116
|
+
: [];
|
|
117
|
+
if (typeof r.question !== 'string') continue;
|
|
118
|
+
questions.push({
|
|
119
|
+
header: typeof r.header === 'string' ? r.header : '',
|
|
120
|
+
question: r.question,
|
|
121
|
+
options,
|
|
122
|
+
multiSelect: r.multiSelect === true,
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
return questions;
|
|
126
|
+
}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { findSpawnableCli, importWorkspacePackage } from '../detect.ts';
|
|
5
|
+
import { extractQuestionBlock, TEXT_QUESTIONS_INSTRUCTION } from '../prompt.ts';
|
|
6
|
+
import {
|
|
7
|
+
type AgentProvider,
|
|
8
|
+
clipDetail,
|
|
9
|
+
type ProviderEvent,
|
|
10
|
+
type ProviderRunOptions,
|
|
11
|
+
ProviderUnavailableError,
|
|
12
|
+
} from '../provider.ts';
|
|
13
|
+
import { type AgentModelOption, isAgentEffort } from '../types.ts';
|
|
14
|
+
import type { CodexItem, CodexSdkModule, CodexThreadEvent } from './sdk-types.ts';
|
|
15
|
+
|
|
16
|
+
const CODEX_SDK_PACKAGE = '@openai/codex-sdk';
|
|
17
|
+
|
|
18
|
+
const CODEX_DEFAULT_MODEL: AgentModelOption = {
|
|
19
|
+
id: '',
|
|
20
|
+
label: 'Default',
|
|
21
|
+
efforts: ['low', 'medium', 'high'],
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
// The Codex CLI caches the model list it shows in its own /model picker.
|
|
25
|
+
// Reading that keeps the panel in step with whatever the user's account can
|
|
26
|
+
// use, without a network call of our own.
|
|
27
|
+
export function parseCodexModelsCache(raw: unknown): AgentModelOption[] {
|
|
28
|
+
const list = (raw as { models?: unknown } | null)?.models;
|
|
29
|
+
if (!Array.isArray(list)) return [];
|
|
30
|
+
const models: { option: AgentModelOption; priority: number }[] = [];
|
|
31
|
+
for (const entry of list) {
|
|
32
|
+
if (!entry || typeof entry !== 'object') continue;
|
|
33
|
+
const m = entry as Record<string, unknown>;
|
|
34
|
+
if (typeof m.slug !== 'string' || !m.slug) continue;
|
|
35
|
+
if (m.visibility !== undefined && m.visibility !== 'list') continue;
|
|
36
|
+
const levels = Array.isArray(m.supported_reasoning_levels) ? m.supported_reasoning_levels : [];
|
|
37
|
+
const efforts = levels
|
|
38
|
+
.map((l) => (l && typeof l === 'object' ? (l as { effort?: unknown }).effort : l))
|
|
39
|
+
.filter(isAgentEffort);
|
|
40
|
+
models.push({
|
|
41
|
+
option: {
|
|
42
|
+
id: m.slug,
|
|
43
|
+
label: typeof m.display_name === 'string' && m.display_name ? m.display_name : m.slug,
|
|
44
|
+
efforts,
|
|
45
|
+
},
|
|
46
|
+
priority: typeof m.priority === 'number' ? m.priority : Number.MAX_SAFE_INTEGER,
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
return models.sort((a, b) => a.priority - b.priority).map((m) => m.option);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function readCodexModels(): Promise<AgentModelOption[]> {
|
|
53
|
+
const home = process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
|
|
54
|
+
try {
|
|
55
|
+
const raw = JSON.parse(await fs.readFile(path.join(home, 'models_cache.json'), 'utf8'));
|
|
56
|
+
const models = parseCodexModelsCache(raw);
|
|
57
|
+
return models.length > 0 ? models : [CODEX_DEFAULT_MODEL];
|
|
58
|
+
} catch {
|
|
59
|
+
return [CODEX_DEFAULT_MODEL];
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// The Codex SDK only reports completed items (no token deltas), so each
|
|
64
|
+
// agent message lands as one finished block.
|
|
65
|
+
export function createCodexMapper(emit: (event: ProviderEvent) => void) {
|
|
66
|
+
const started = new Set<string>();
|
|
67
|
+
let resultSeen = false;
|
|
68
|
+
|
|
69
|
+
const startTool = (item: CodexItem, name: string, title: string, detail: string | null) => {
|
|
70
|
+
if (started.has(item.id)) return;
|
|
71
|
+
started.add(item.id);
|
|
72
|
+
emit({ type: 'tool-start', id: item.id, name, title, detail });
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const describe = (item: CodexItem): { name: string; title: string; detail: string | null } => {
|
|
76
|
+
switch (item.type) {
|
|
77
|
+
case 'command_execution':
|
|
78
|
+
return { name: 'command', title: 'Run command', detail: clipDetail(item.command) };
|
|
79
|
+
case 'file_change':
|
|
80
|
+
return {
|
|
81
|
+
name: 'file_change',
|
|
82
|
+
title: 'Edit',
|
|
83
|
+
detail: clipDetail(item.changes.map((c) => c.path).join(', ')),
|
|
84
|
+
};
|
|
85
|
+
case 'mcp_tool_call':
|
|
86
|
+
return { name: 'mcp', title: `${item.server}: ${item.tool}`, detail: null };
|
|
87
|
+
case 'web_search':
|
|
88
|
+
return { name: 'web_search', title: 'Web search', detail: clipDetail(item.query) };
|
|
89
|
+
default:
|
|
90
|
+
return { name: item.type, title: item.type, detail: null };
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
const handleItem = (phase: 'started' | 'updated' | 'completed', item: CodexItem) => {
|
|
95
|
+
switch (item.type) {
|
|
96
|
+
case 'agent_message': {
|
|
97
|
+
if (phase !== 'completed' || !item.text.trim()) return;
|
|
98
|
+
const asked = extractQuestionBlock(item.text);
|
|
99
|
+
const text = asked ? asked.text : item.text;
|
|
100
|
+
if (text) {
|
|
101
|
+
emit({ type: 'text-start', id: item.id });
|
|
102
|
+
emit({ type: 'text-end', id: item.id, text });
|
|
103
|
+
}
|
|
104
|
+
if (asked) emit({ type: 'questions', questions: asked.questions });
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
case 'error':
|
|
108
|
+
if (phase === 'completed') emit({ type: 'error', text: item.message });
|
|
109
|
+
return;
|
|
110
|
+
case 'command_execution':
|
|
111
|
+
case 'file_change':
|
|
112
|
+
case 'mcp_tool_call':
|
|
113
|
+
case 'web_search': {
|
|
114
|
+
const { name, title, detail } = describe(item);
|
|
115
|
+
startTool(item, name, title, detail);
|
|
116
|
+
if (phase === 'completed') {
|
|
117
|
+
const status = 'status' in item ? item.status : 'completed';
|
|
118
|
+
emit({ type: 'tool-end', id: item.id, ok: status !== 'failed' });
|
|
119
|
+
}
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
default:
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
return {
|
|
128
|
+
get resultSeen() {
|
|
129
|
+
return resultSeen;
|
|
130
|
+
},
|
|
131
|
+
handle(event: CodexThreadEvent): void {
|
|
132
|
+
if (!event || typeof event !== 'object') return;
|
|
133
|
+
switch (event.type) {
|
|
134
|
+
case 'thread.started':
|
|
135
|
+
emit({ type: 'session-id', id: event.thread_id });
|
|
136
|
+
return;
|
|
137
|
+
case 'item.started':
|
|
138
|
+
handleItem('started', event.item);
|
|
139
|
+
return;
|
|
140
|
+
case 'item.updated':
|
|
141
|
+
handleItem('updated', event.item);
|
|
142
|
+
return;
|
|
143
|
+
case 'item.completed':
|
|
144
|
+
handleItem('completed', event.item);
|
|
145
|
+
return;
|
|
146
|
+
case 'turn.failed':
|
|
147
|
+
resultSeen = true;
|
|
148
|
+
emit({ type: 'error', text: event.error.message });
|
|
149
|
+
emit({ type: 'result', durationMs: null, costUsd: null });
|
|
150
|
+
return;
|
|
151
|
+
case 'error':
|
|
152
|
+
emit({ type: 'error', text: event.message });
|
|
153
|
+
return;
|
|
154
|
+
case 'turn.completed':
|
|
155
|
+
resultSeen = true;
|
|
156
|
+
emit({ type: 'result', durationMs: null, costUsd: null });
|
|
157
|
+
return;
|
|
158
|
+
default:
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function createCodexProvider(): AgentProvider {
|
|
166
|
+
return {
|
|
167
|
+
id: 'codex',
|
|
168
|
+
name: 'Codex',
|
|
169
|
+
sdkPackage: CODEX_SDK_PACKAGE,
|
|
170
|
+
// `codex exec`, which the SDK drives, rejects request_user_input, so
|
|
171
|
+
// questions travel as a tagged block in the final reply instead.
|
|
172
|
+
askInstruction: TEXT_QUESTIONS_INSTRUCTION,
|
|
173
|
+
canRewind: false,
|
|
174
|
+
canOpenBrowser: false,
|
|
175
|
+
cliCommand: 'codex',
|
|
176
|
+
models: readCodexModels,
|
|
177
|
+
async run(opts: ProviderRunOptions): Promise<void> {
|
|
178
|
+
const sdk = await importWorkspacePackage<CodexSdkModule>(opts.cwd, CODEX_SDK_PACKAGE);
|
|
179
|
+
if (!sdk || typeof sdk.Codex !== 'function') throw new ProviderUnavailableError(this);
|
|
180
|
+
|
|
181
|
+
const localCli = findSpawnableCli('codex');
|
|
182
|
+
const codex = new sdk.Codex(localCli ? { codexPathOverride: localCli } : {});
|
|
183
|
+
const threadOptions = {
|
|
184
|
+
workingDirectory: opts.cwd,
|
|
185
|
+
skipGitRepoCheck: true,
|
|
186
|
+
sandboxMode: 'workspace-write' as const,
|
|
187
|
+
approvalPolicy: 'never' as const,
|
|
188
|
+
...(opts.model ? { model: opts.model } : {}),
|
|
189
|
+
...(opts.effort ? { modelReasoningEffort: opts.effort } : {}),
|
|
190
|
+
};
|
|
191
|
+
const thread = opts.resume
|
|
192
|
+
? codex.resumeThread(opts.resume, threadOptions)
|
|
193
|
+
: codex.startThread(threadOptions);
|
|
194
|
+
|
|
195
|
+
// Codex has no system-prompt hook, so the panel preamble rides on the
|
|
196
|
+
// first turn of a thread only.
|
|
197
|
+
const input = opts.resume ? opts.prompt : `${opts.systemPromptAppend}\n\n${opts.prompt}`;
|
|
198
|
+
const mapper = createCodexMapper(opts.emit);
|
|
199
|
+
const { events } = await thread.runStreamed(input, { signal: opts.signal });
|
|
200
|
+
try {
|
|
201
|
+
for await (const event of events) mapper.handle(event);
|
|
202
|
+
} catch (err) {
|
|
203
|
+
if (opts.signal.aborted || mapper.resultSeen) return;
|
|
204
|
+
throw err;
|
|
205
|
+
}
|
|
206
|
+
if (thread.id) opts.emit({ type: 'session-id', id: thread.id });
|
|
207
|
+
},
|
|
208
|
+
};
|
|
209
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { AgentProvider } from '../provider.ts';
|
|
2
|
+
import type { AgentProviderId } from '../types.ts';
|
|
3
|
+
import { createCodexProvider } from './codex.ts';
|
|
4
|
+
|
|
5
|
+
export function createProviders(): Record<AgentProviderId, AgentProvider> {
|
|
6
|
+
return { codex: createCodexProvider() };
|
|
7
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Hand-written slices of the agent SDK's public types. The packages are
|
|
2
|
+
// resolved from the user's workspace at runtime and never installed here, so
|
|
3
|
+
// these cover only the fields the adapters read.
|
|
4
|
+
|
|
5
|
+
import type { AgentEffort } from '../types.ts';
|
|
6
|
+
|
|
7
|
+
type CodexOptions = { codexPathOverride?: string };
|
|
8
|
+
|
|
9
|
+
type CodexThreadOptions = {
|
|
10
|
+
workingDirectory?: string;
|
|
11
|
+
skipGitRepoCheck?: boolean;
|
|
12
|
+
sandboxMode?: 'read-only' | 'workspace-write' | 'danger-full-access';
|
|
13
|
+
approvalPolicy?: 'never' | 'on-request' | 'on-failure' | 'untrusted';
|
|
14
|
+
model?: string;
|
|
15
|
+
modelReasoningEffort?: AgentEffort;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
export type CodexItem =
|
|
19
|
+
| { type: 'agent_message'; id: string; text: string }
|
|
20
|
+
| { type: 'reasoning'; id: string; text: string }
|
|
21
|
+
| {
|
|
22
|
+
type: 'command_execution';
|
|
23
|
+
id: string;
|
|
24
|
+
command: string;
|
|
25
|
+
aggregated_output?: string;
|
|
26
|
+
exit_code?: number;
|
|
27
|
+
status: 'in_progress' | 'completed' | 'failed';
|
|
28
|
+
}
|
|
29
|
+
| {
|
|
30
|
+
type: 'file_change';
|
|
31
|
+
id: string;
|
|
32
|
+
changes: { path: string; kind: 'add' | 'delete' | 'update' }[];
|
|
33
|
+
status: 'completed' | 'failed';
|
|
34
|
+
}
|
|
35
|
+
| {
|
|
36
|
+
type: 'mcp_tool_call';
|
|
37
|
+
id: string;
|
|
38
|
+
server: string;
|
|
39
|
+
tool: string;
|
|
40
|
+
status: 'in_progress' | 'completed' | 'failed';
|
|
41
|
+
}
|
|
42
|
+
| { type: 'web_search'; id: string; query: string }
|
|
43
|
+
| { type: 'todo_list'; id: string; items: { text: string; completed: boolean }[] }
|
|
44
|
+
| { type: 'error'; id: string; message: string };
|
|
45
|
+
|
|
46
|
+
export type CodexThreadEvent =
|
|
47
|
+
| { type: 'thread.started'; thread_id: string }
|
|
48
|
+
| { type: 'turn.started' }
|
|
49
|
+
| { type: 'turn.completed'; usage: unknown }
|
|
50
|
+
| { type: 'turn.failed'; error: { message: string } }
|
|
51
|
+
| { type: 'item.started'; item: CodexItem }
|
|
52
|
+
| { type: 'item.updated'; item: CodexItem }
|
|
53
|
+
| { type: 'item.completed'; item: CodexItem }
|
|
54
|
+
| { type: 'error'; message: string };
|
|
55
|
+
|
|
56
|
+
type CodexThread = {
|
|
57
|
+
id: string | null;
|
|
58
|
+
runStreamed: (
|
|
59
|
+
input: string,
|
|
60
|
+
turnOptions?: { signal?: AbortSignal },
|
|
61
|
+
) => Promise<{ events: AsyncIterable<CodexThreadEvent> }>;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export type CodexSdkModule = {
|
|
65
|
+
Codex: new (
|
|
66
|
+
options?: CodexOptions,
|
|
67
|
+
) => {
|
|
68
|
+
startThread: (options?: CodexThreadOptions) => CodexThread;
|
|
69
|
+
resumeThread: (id: string, options?: CodexThreadOptions) => CodexThread;
|
|
70
|
+
};
|
|
71
|
+
};
|