@open-document/core 0.14.1 → 0.14.2
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/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
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-document/core",
|
|
3
|
-
"version": "0.14.
|
|
3
|
+
"version": "0.14.2",
|
|
4
4
|
"description": "Runtime and CLI for open-doc — write documents in docs/, we handle the pages, print layout, and export.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -28,6 +28,11 @@
|
|
|
28
28
|
"dist",
|
|
29
29
|
"env.d.ts",
|
|
30
30
|
"src/app",
|
|
31
|
+
"src/agent",
|
|
32
|
+
"src/diagram",
|
|
33
|
+
"src/editing/placeholder-id.ts",
|
|
34
|
+
"!src/**/*.test.ts",
|
|
35
|
+
"!src/**/*.test.tsx",
|
|
31
36
|
"skills",
|
|
32
37
|
"templates",
|
|
33
38
|
"README.md",
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { AgentCheckFinding, AgentItem, AgentSession } from './types.ts';
|
|
2
|
+
|
|
3
|
+
/** How many findings a check item keeps; the rest are only counted. */
|
|
4
|
+
export const CHECK_FINDINGS_KEPT = 20;
|
|
5
|
+
|
|
6
|
+
// A file's mtime can trail the clock that stamped the message by a little.
|
|
7
|
+
const CLOCK_SLACK_MS = 1000;
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Whether the dev server should run `open-doc check` for the turn that just
|
|
11
|
+
* ended: only for an agent that cannot start a browser itself, only when the
|
|
12
|
+
* turn ran to its end, and only when it touched the document's source — it
|
|
13
|
+
* used a tool, and the file changed after the message. The mtime alone is not
|
|
14
|
+
* enough: a document copied or made from a template a moment earlier reads as
|
|
15
|
+
* fresh to a turn whose agent never even started.
|
|
16
|
+
*/
|
|
17
|
+
export function shouldCheckAfterTurn(opts: {
|
|
18
|
+
session: Pick<AgentSession, 'docId' | 'items'>;
|
|
19
|
+
userItemId: string;
|
|
20
|
+
canOpenBrowser: boolean;
|
|
21
|
+
entryMtimeMs: number | null;
|
|
22
|
+
}): boolean {
|
|
23
|
+
const { session, userItemId, canOpenBrowser, entryMtimeMs } = opts;
|
|
24
|
+
if (canOpenBrowser || !session.docId || entryMtimeMs === null) return false;
|
|
25
|
+
const start = session.items.findIndex((i) => i.id === userItemId);
|
|
26
|
+
if (start === -1) return false;
|
|
27
|
+
const turn = session.items.slice(start + 1);
|
|
28
|
+
const result = [...turn].reverse().find((i) => i.kind === 'result');
|
|
29
|
+
if (result?.kind === 'result' && result.aborted) return false;
|
|
30
|
+
if (!turn.some((i) => i.kind === 'tool')) return false;
|
|
31
|
+
const startedAt = Date.parse(session.items[start].ts);
|
|
32
|
+
return Number.isFinite(startedAt) && entryMtimeMs >= startedAt - CLOCK_SLACK_MS;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
type Report = {
|
|
36
|
+
pageCount: number;
|
|
37
|
+
findings: Array<{
|
|
38
|
+
page: number;
|
|
39
|
+
severity: 'error' | 'warn';
|
|
40
|
+
message: string;
|
|
41
|
+
loc?: string;
|
|
42
|
+
}>;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/** A check report as the transcript keeps it: errors first, the rest counted. */
|
|
46
|
+
export function checkItemResult(
|
|
47
|
+
report: Report,
|
|
48
|
+
): Pick<Extract<AgentItem, { kind: 'check' }>, 'pageCount' | 'findings' | 'total'> {
|
|
49
|
+
const ordered = [...report.findings].sort(
|
|
50
|
+
(a, b) => Number(b.severity === 'error') - Number(a.severity === 'error') || a.page - b.page,
|
|
51
|
+
);
|
|
52
|
+
const findings: AgentCheckFinding[] = ordered.slice(0, CHECK_FINDINGS_KEPT).map((f) => ({
|
|
53
|
+
page: f.page,
|
|
54
|
+
severity: f.severity,
|
|
55
|
+
message: f.message,
|
|
56
|
+
...(f.loc ? { loc: f.loc } : {}),
|
|
57
|
+
}));
|
|
58
|
+
return { pageCount: report.pageCount, findings, total: report.findings.length };
|
|
59
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
|
|
6
|
+
const IS_WINDOWS = process.platform === 'win32';
|
|
7
|
+
const VERSION_TIMEOUT_MS = 5000;
|
|
8
|
+
|
|
9
|
+
export function findOnPath(command: string, env: NodeJS.ProcessEnv = process.env): string | null {
|
|
10
|
+
const dirs = (env.PATH ?? env.Path ?? '').split(path.delimiter).filter(Boolean);
|
|
11
|
+
const exts = IS_WINDOWS ? (env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';') : [''];
|
|
12
|
+
for (const dir of dirs) {
|
|
13
|
+
for (const ext of exts) {
|
|
14
|
+
const candidate = path.join(dir, command + ext.toLowerCase());
|
|
15
|
+
try {
|
|
16
|
+
if (statSync(candidate, { throwIfNoEntry: false })?.isFile()) return candidate;
|
|
17
|
+
} catch {}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// The SDKs spawn the CLI without a shell, which cannot run a Windows .cmd shim,
|
|
24
|
+
// so only a real executable is worth overriding their bundled default with.
|
|
25
|
+
export function findSpawnableCli(command: string, env: NodeJS.ProcessEnv = process.env) {
|
|
26
|
+
const found = findOnPath(command, env);
|
|
27
|
+
if (!found || !IS_WINDOWS) return found;
|
|
28
|
+
return found.toLowerCase().endsWith('.exe') ? found : null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const versionCache = new Map<string, Promise<string | null>>();
|
|
32
|
+
|
|
33
|
+
export function commandVersion(file: string): Promise<string | null> {
|
|
34
|
+
let cached = versionCache.get(file);
|
|
35
|
+
if (!cached) {
|
|
36
|
+
cached = readVersion(file);
|
|
37
|
+
versionCache.set(file, cached);
|
|
38
|
+
}
|
|
39
|
+
return cached;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function readVersion(file: string): Promise<string | null> {
|
|
43
|
+
return new Promise((resolve) => {
|
|
44
|
+
let out = '';
|
|
45
|
+
let child: ReturnType<typeof spawn>;
|
|
46
|
+
try {
|
|
47
|
+
child = spawn(file, ['--version'], {
|
|
48
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
49
|
+
shell: IS_WINDOWS,
|
|
50
|
+
windowsHide: true,
|
|
51
|
+
});
|
|
52
|
+
} catch {
|
|
53
|
+
resolve(null);
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
const timer = setTimeout(() => {
|
|
57
|
+
child.kill();
|
|
58
|
+
resolve(null);
|
|
59
|
+
}, VERSION_TIMEOUT_MS);
|
|
60
|
+
child.stdout?.on('data', (c: Buffer) => {
|
|
61
|
+
out += c.toString('utf8');
|
|
62
|
+
});
|
|
63
|
+
child.stderr?.on('data', (c: Buffer) => {
|
|
64
|
+
out += c.toString('utf8');
|
|
65
|
+
});
|
|
66
|
+
child.on('error', () => {
|
|
67
|
+
clearTimeout(timer);
|
|
68
|
+
resolve(null);
|
|
69
|
+
});
|
|
70
|
+
child.on('close', () => {
|
|
71
|
+
clearTimeout(timer);
|
|
72
|
+
resolve(parseVersion(out));
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function parseVersion(output: string): string | null {
|
|
78
|
+
const m = /(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)/.exec(output);
|
|
79
|
+
return m ? m[1] : null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
type PackageJson = {
|
|
83
|
+
version?: string;
|
|
84
|
+
main?: string;
|
|
85
|
+
module?: string;
|
|
86
|
+
exports?: unknown;
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
export type ResolvedPackage = { dir: string; version: string; entry: string };
|
|
90
|
+
|
|
91
|
+
export function entryFromPackageJson(pkg: PackageJson): string | null {
|
|
92
|
+
const root = pickExport(pkg.exports);
|
|
93
|
+
if (root) return root;
|
|
94
|
+
return pkg.module ?? pkg.main ?? null;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function pickExport(exportsField: unknown): string | null {
|
|
98
|
+
if (!exportsField) return null;
|
|
99
|
+
if (typeof exportsField === 'string') return exportsField;
|
|
100
|
+
if (typeof exportsField !== 'object') return null;
|
|
101
|
+
const record = exportsField as Record<string, unknown>;
|
|
102
|
+
const keys = Object.keys(record);
|
|
103
|
+
const isSubpathMap = keys.some((k) => k.startsWith('.'));
|
|
104
|
+
const target = isSubpathMap ? record['.'] : exportsField;
|
|
105
|
+
return pickCondition(target);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function pickCondition(target: unknown): string | null {
|
|
109
|
+
if (!target) return null;
|
|
110
|
+
if (typeof target === 'string') return target;
|
|
111
|
+
if (Array.isArray(target)) {
|
|
112
|
+
for (const t of target) {
|
|
113
|
+
const hit = pickCondition(t);
|
|
114
|
+
if (hit) return hit;
|
|
115
|
+
}
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
if (typeof target !== 'object') return null;
|
|
119
|
+
const record = target as Record<string, unknown>;
|
|
120
|
+
for (const key of ['import', 'node', 'default', 'require']) {
|
|
121
|
+
if (key in record) {
|
|
122
|
+
const hit = pickCondition(record[key]);
|
|
123
|
+
if (hit) return hit;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Walks node_modules up from the workspace like Node does, but reads
|
|
130
|
+
// package.json directly: the SDKs' `exports` maps don't expose it, so
|
|
131
|
+
// `require.resolve('<pkg>/package.json')` would refuse.
|
|
132
|
+
export function resolveWorkspacePackage(userCwd: string, name: string): ResolvedPackage | null {
|
|
133
|
+
let dir = path.resolve(userCwd);
|
|
134
|
+
while (true) {
|
|
135
|
+
const pkgJsonPath = path.join(dir, 'node_modules', name, 'package.json');
|
|
136
|
+
if (existsSync(pkgJsonPath)) {
|
|
137
|
+
let pkg: PackageJson;
|
|
138
|
+
try {
|
|
139
|
+
pkg = JSON.parse(readFileSync(pkgJsonPath, 'utf8')) as PackageJson;
|
|
140
|
+
} catch {
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
143
|
+
const entry = entryFromPackageJson(pkg);
|
|
144
|
+
if (!entry) return null;
|
|
145
|
+
const pkgDir = path.dirname(pkgJsonPath);
|
|
146
|
+
return { dir: pkgDir, version: pkg.version ?? '0.0.0', entry: path.resolve(pkgDir, entry) };
|
|
147
|
+
}
|
|
148
|
+
const parent = path.dirname(dir);
|
|
149
|
+
if (parent === dir) return null;
|
|
150
|
+
dir = parent;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export async function importWorkspacePackage<T>(userCwd: string, name: string): Promise<T | null> {
|
|
155
|
+
const resolved = resolveWorkspacePackage(userCwd, name);
|
|
156
|
+
if (!resolved) return null;
|
|
157
|
+
return (await import(pathToFileURL(resolved.entry).href)) as T;
|
|
158
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
export type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun';
|
|
6
|
+
|
|
7
|
+
type CommandSpec = { cmd: string; args: string[] };
|
|
8
|
+
|
|
9
|
+
const LOCKFILES: ReadonlyArray<readonly [string, PackageManager]> = [
|
|
10
|
+
['pnpm-lock.yaml', 'pnpm'],
|
|
11
|
+
['yarn.lock', 'yarn'],
|
|
12
|
+
['bun.lockb', 'bun'],
|
|
13
|
+
['bun.lock', 'bun'],
|
|
14
|
+
['package-lock.json', 'npm'],
|
|
15
|
+
];
|
|
16
|
+
|
|
17
|
+
async function fileExists(file: string): Promise<boolean> {
|
|
18
|
+
try {
|
|
19
|
+
await fs.access(file);
|
|
20
|
+
return true;
|
|
21
|
+
} catch {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function detectPackageManager(cwd: string): Promise<PackageManager> {
|
|
27
|
+
const ua = process.env.npm_config_user_agent ?? '';
|
|
28
|
+
if (ua.startsWith('pnpm')) return 'pnpm';
|
|
29
|
+
if (ua.startsWith('yarn')) return 'yarn';
|
|
30
|
+
if (ua.startsWith('bun')) return 'bun';
|
|
31
|
+
if (ua.startsWith('npm')) return 'npm';
|
|
32
|
+
|
|
33
|
+
// Workspace members have no lockfile of their own; it lives at the root.
|
|
34
|
+
let dir = cwd;
|
|
35
|
+
while (true) {
|
|
36
|
+
for (const [lockfile, pm] of LOCKFILES) {
|
|
37
|
+
if (await fileExists(path.join(dir, lockfile))) return pm;
|
|
38
|
+
}
|
|
39
|
+
const parent = path.dirname(dir);
|
|
40
|
+
if (parent === dir) return 'npm';
|
|
41
|
+
dir = parent;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function runCommand(spec: CommandSpec, cwd: string, timeoutMs: number): Promise<void> {
|
|
46
|
+
const label = [spec.cmd, ...spec.args].join(' ');
|
|
47
|
+
await new Promise<void>((resolve, reject) => {
|
|
48
|
+
const child = spawn(spec.cmd, spec.args, {
|
|
49
|
+
cwd,
|
|
50
|
+
env: process.env,
|
|
51
|
+
shell: process.platform === 'win32',
|
|
52
|
+
stdio: ['ignore', 'ignore', 'pipe'],
|
|
53
|
+
windowsHide: true,
|
|
54
|
+
});
|
|
55
|
+
let stderr = '';
|
|
56
|
+
const timer = setTimeout(() => {
|
|
57
|
+
child.kill();
|
|
58
|
+
reject(new Error(`${label} timed out`));
|
|
59
|
+
}, timeoutMs);
|
|
60
|
+
child.stderr.on('data', (chunk: Buffer) => {
|
|
61
|
+
stderr = (stderr + chunk.toString('utf8')).slice(-2000);
|
|
62
|
+
});
|
|
63
|
+
child.on('error', (err) => {
|
|
64
|
+
clearTimeout(timer);
|
|
65
|
+
reject(err);
|
|
66
|
+
});
|
|
67
|
+
child.on('close', (code) => {
|
|
68
|
+
clearTimeout(timer);
|
|
69
|
+
if (code === 0) return resolve();
|
|
70
|
+
reject(new Error(stderr.trim() || `${label} exited with code ${code ?? 'unknown'}`));
|
|
71
|
+
});
|
|
72
|
+
});
|
|
73
|
+
}
|
|
@@ -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
|
+
}
|