@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.
@@ -0,0 +1,64 @@
1
+ import { commandVersion, findOnPath, resolveWorkspacePackage } from './detect.ts';
2
+ import { type PackageManager, runCommand } from './install.ts';
3
+ import type { AgentProvider } from './provider.ts';
4
+ import type { AgentProviderId, AgentProviderStatus, AgentStatus } from './types.ts';
5
+
6
+ const INSTALL_TIMEOUT_MS = 10 * 60 * 1000;
7
+
8
+ async function providerStatus(
9
+ userCwd: string,
10
+ provider: AgentProvider,
11
+ ): Promise<AgentProviderStatus> {
12
+ const sdk = resolveWorkspacePackage(userCwd, provider.sdkPackage);
13
+ const cliPath = findOnPath(provider.cliCommand);
14
+ const [cliVersion, models] = await Promise.all([
15
+ cliPath ? commandVersion(cliPath) : null,
16
+ provider.models(),
17
+ ]);
18
+ return {
19
+ id: provider.id,
20
+ name: provider.name,
21
+ sdkPackage: provider.sdkPackage,
22
+ sdkVersion: sdk?.version ?? null,
23
+ cliCommand: provider.cliCommand,
24
+ cliFound: cliPath !== null,
25
+ cliVersion,
26
+ ready: sdk !== null,
27
+ models,
28
+ };
29
+ }
30
+
31
+ export async function agentStatus(
32
+ userCwd: string,
33
+ providers: Record<AgentProviderId, AgentProvider>,
34
+ packageManager: PackageManager,
35
+ ): Promise<AgentStatus> {
36
+ const list = await Promise.all(
37
+ Object.values(providers).map((provider) => providerStatus(userCwd, provider)),
38
+ );
39
+ return { enabled: true, packageManager, providers: list };
40
+ }
41
+
42
+ function installCommandFor(
43
+ packageManager: PackageManager,
44
+ pkg: string,
45
+ ): { cmd: string; args: string[] } {
46
+ switch (packageManager) {
47
+ case 'pnpm':
48
+ return { cmd: 'pnpm', args: ['add', '-D', pkg] };
49
+ case 'yarn':
50
+ return { cmd: 'yarn', args: ['add', '-D', pkg] };
51
+ case 'bun':
52
+ return { cmd: 'bun', args: ['add', '-d', pkg] };
53
+ case 'npm':
54
+ return { cmd: 'npm', args: ['install', '-D', pkg] };
55
+ }
56
+ }
57
+
58
+ export function installSdk(
59
+ packageManager: PackageManager,
60
+ pkg: string,
61
+ cwd: string,
62
+ ): Promise<void> {
63
+ return runCommand(installCommandFor(packageManager, pkg), cwd, INSTALL_TIMEOUT_MS);
64
+ }
@@ -0,0 +1,271 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import fs from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import {
6
+ type AgentItem,
7
+ type AgentProviderId,
8
+ type AgentSession,
9
+ type AgentSessionSummary,
10
+ type AgentStreamEvent,
11
+ isAgentProviderId,
12
+ sessionSummary,
13
+ } from './types.ts';
14
+
15
+ const MAX_SESSIONS = 30;
16
+ const MAX_ITEMS_PER_SESSION = 400;
17
+ const SAVE_DEBOUNCE_MS = 150;
18
+ const TITLE_MAX = 60;
19
+
20
+ export function newId(prefix: string): string {
21
+ return `${prefix}-${randomBytes(6).toString('hex')}`;
22
+ }
23
+
24
+ export function titleFromPrompt(text: string): string {
25
+ const line = text
26
+ .split('\n')
27
+ .map((l) => l.trim())
28
+ .find((l) => l.length > 0);
29
+ if (!line) return 'Untitled';
30
+ return line.length > TITLE_MAX ? `${line.slice(0, TITLE_MAX - 1)}…` : line;
31
+ }
32
+
33
+ type Listener = (event: AgentStreamEvent) => void;
34
+
35
+ type PersistedShape = { version: 1; sessions: AgentSession[] };
36
+
37
+ function readPersisted(file: string): AgentSession[] {
38
+ if (!existsSync(file)) return [];
39
+ try {
40
+ const parsed = JSON.parse(readFileSync(file, 'utf8')) as Partial<PersistedShape>;
41
+ if (parsed?.version !== 1 || !Array.isArray(parsed.sessions)) return [];
42
+ // A dev-server restart mid-turn leaves no process to finish it; every
43
+ // reloaded session starts idle and pending prompts are closed out.
44
+ return parsed.sessions
45
+ .filter((s) => isAgentProviderId(s.provider))
46
+ .map((s) => ({
47
+ ...s,
48
+ status: 'idle',
49
+ items: s.items.map(closePending),
50
+ }));
51
+ } catch {
52
+ return [];
53
+ }
54
+ }
55
+
56
+ function closePending(item: AgentItem): AgentItem {
57
+ if (item.kind === 'assistant' && item.streaming) return { ...item, streaming: false };
58
+ if (item.kind === 'tool' && item.status === 'running') return { ...item, status: 'error' };
59
+ if (item.kind === 'question' && item.status === 'pending')
60
+ return { ...item, status: 'cancelled' };
61
+ if (item.kind === 'permission' && item.status === 'pending') return { ...item, status: 'denied' };
62
+ if (item.kind === 'check' && item.status === 'running') {
63
+ return { ...item, status: 'failed', error: 'interrupted' };
64
+ }
65
+ return item;
66
+ }
67
+
68
+ export type SessionStore = ReturnType<typeof createSessionStore>;
69
+
70
+ export function createSessionStore(opts: { file: string | null }) {
71
+ const sessions = new Map<string, AgentSession>();
72
+ const listeners = new Set<Listener>();
73
+ let saveTimer: ReturnType<typeof setTimeout> | null = null;
74
+ // Touch order breaks ties between sessions updated in the same millisecond.
75
+ let seq = 0;
76
+ const order = new Map<string, number>();
77
+
78
+ if (opts.file) {
79
+ for (const s of readPersisted(opts.file)) {
80
+ sessions.set(s.id, s);
81
+ order.set(s.id, seq++);
82
+ }
83
+ }
84
+
85
+ const emit = (event: AgentStreamEvent) => {
86
+ for (const l of listeners) l(event);
87
+ };
88
+
89
+ const scheduleSave = () => {
90
+ if (!opts.file) return;
91
+ if (saveTimer) clearTimeout(saveTimer);
92
+ saveTimer = setTimeout(() => {
93
+ saveTimer = null;
94
+ void save();
95
+ }, SAVE_DEBOUNCE_MS);
96
+ };
97
+
98
+ const writeSnapshot = async (file: string) => {
99
+ const body: PersistedShape = {
100
+ version: 1,
101
+ sessions: list().flatMap((s) => sessions.get(s.id) ?? []),
102
+ };
103
+ const tmp = `${file}.tmp`;
104
+ try {
105
+ await fs.mkdir(path.dirname(file), { recursive: true });
106
+ await fs.writeFile(tmp, JSON.stringify(body), { encoding: 'utf8', mode: 0o600 });
107
+ await fs.rename(tmp, file);
108
+ } catch (err) {
109
+ console.error('[open-doc] failed to save agent sessions:', err);
110
+ await fs.rm(tmp, { force: true }).catch(() => {});
111
+ }
112
+ };
113
+
114
+ // Saves share one temp file, so a flush racing a debounced save must wait
115
+ // for it rather than interleave writes and renames.
116
+ let saving: Promise<void> = Promise.resolve();
117
+ const save = () => {
118
+ const file = opts.file;
119
+ if (!file) return saving;
120
+ saving = saving.then(() => writeSnapshot(file));
121
+ return saving;
122
+ };
123
+
124
+ const touch = (session: AgentSession) => {
125
+ session.updatedAt = new Date().toISOString();
126
+ order.set(session.id, seq++);
127
+ emit({ type: 'session', session: sessionSummary(session) });
128
+ scheduleSave();
129
+ };
130
+
131
+ const require = (id: string): AgentSession => {
132
+ const session = sessions.get(id);
133
+ if (!session) throw new Error(`unknown agent session: ${id}`);
134
+ return session;
135
+ };
136
+
137
+ function list(): AgentSessionSummary[] {
138
+ return Array.from(sessions.values())
139
+ .sort((a, b) => {
140
+ if (a.updatedAt !== b.updatedAt) return a.updatedAt < b.updatedAt ? 1 : -1;
141
+ return (order.get(b.id) ?? 0) - (order.get(a.id) ?? 0);
142
+ })
143
+ .map(sessionSummary);
144
+ }
145
+
146
+ function get(id: string): AgentSession | null {
147
+ return sessions.get(id) ?? null;
148
+ }
149
+
150
+ function create(provider: AgentProviderId, docId: string | null): AgentSession {
151
+ const now = new Date().toISOString();
152
+ const session: AgentSession = {
153
+ id: newId('s'),
154
+ provider,
155
+ title: 'New session',
156
+ createdAt: now,
157
+ updatedAt: now,
158
+ status: 'idle',
159
+ docId,
160
+ providerSessionId: null,
161
+ items: [],
162
+ };
163
+ sessions.set(session.id, session);
164
+ order.set(session.id, seq++);
165
+ const idle = list().filter((s) => s.status === 'idle');
166
+ for (const stale of idle.slice(MAX_SESSIONS)) {
167
+ sessions.delete(stale.id);
168
+ order.delete(stale.id);
169
+ emit({ type: 'session-removed', sessionId: stale.id });
170
+ }
171
+ touch(session);
172
+ return session;
173
+ }
174
+
175
+ function remove(id: string): boolean {
176
+ if (!sessions.delete(id)) return false;
177
+ order.delete(id);
178
+ emit({ type: 'session-removed', sessionId: id });
179
+ scheduleSave();
180
+ return true;
181
+ }
182
+
183
+ function patch(
184
+ id: string,
185
+ changes: Partial<
186
+ Pick<AgentSession, 'title' | 'status' | 'providerSessionId' | 'providerCheckpoint' | 'docId'>
187
+ >,
188
+ ): AgentSession {
189
+ const session = require(id);
190
+ Object.assign(session, changes);
191
+ touch(session);
192
+ return session;
193
+ }
194
+
195
+ function appendItem<T extends AgentItem>(sessionId: string, item: T): T {
196
+ const session = require(sessionId);
197
+ session.items.push(item);
198
+ if (session.items.length > MAX_ITEMS_PER_SESSION) {
199
+ session.items.splice(0, session.items.length - MAX_ITEMS_PER_SESSION);
200
+ session.trimmed = true;
201
+ }
202
+ emit({ type: 'item', sessionId, item });
203
+ touch(session);
204
+ return item;
205
+ }
206
+
207
+ function updateItem<K extends AgentItem['kind']>(
208
+ sessionId: string,
209
+ itemId: string,
210
+ kind: K,
211
+ changes: Partial<Extract<AgentItem, { kind: K }>>,
212
+ ): Extract<AgentItem, { kind: K }> | null {
213
+ const session = require(sessionId);
214
+ const index = session.items.findIndex((i) => i.id === itemId && i.kind === kind);
215
+ if (index === -1) return null;
216
+ const next = { ...session.items[index], ...changes } as Extract<AgentItem, { kind: K }>;
217
+ session.items[index] = next;
218
+ emit({ type: 'item', sessionId, item: next });
219
+ touch(session);
220
+ return next;
221
+ }
222
+
223
+ function truncateFrom(sessionId: string, itemId: string): boolean {
224
+ const session = require(sessionId);
225
+ const index = session.items.findIndex((i) => i.id === itemId);
226
+ if (index === -1) return false;
227
+ session.items.splice(index);
228
+ emit({ type: 'truncate', sessionId, itemId });
229
+ touch(session);
230
+ return true;
231
+ }
232
+
233
+ function appendDelta(sessionId: string, itemId: string, text: string): void {
234
+ if (!text) return;
235
+ const session = require(sessionId);
236
+ const item = session.items.find((i) => i.id === itemId);
237
+ if (item?.kind !== 'assistant') return;
238
+ item.text += text;
239
+ emit({ type: 'delta', sessionId, itemId, text });
240
+ scheduleSave();
241
+ }
242
+
243
+ function subscribe(listener: Listener): () => void {
244
+ listeners.add(listener);
245
+ return () => {
246
+ listeners.delete(listener);
247
+ };
248
+ }
249
+
250
+ async function flush(): Promise<void> {
251
+ if (saveTimer) {
252
+ clearTimeout(saveTimer);
253
+ saveTimer = null;
254
+ }
255
+ await save();
256
+ }
257
+
258
+ return {
259
+ list,
260
+ get,
261
+ create,
262
+ remove,
263
+ patch,
264
+ appendItem,
265
+ updateItem,
266
+ truncateFrom,
267
+ appendDelta,
268
+ subscribe,
269
+ flush,
270
+ };
271
+ }
@@ -0,0 +1,174 @@
1
+ // Codex only: Anthropic does not allow a third-party product to run on a reader's
2
+ // claude.ai login, so Claude Code is not offered here. A new agent is one more id.
3
+ export const AGENT_PROVIDER_IDS = ['codex'] as const;
4
+
5
+ export type AgentProviderId = (typeof AGENT_PROVIDER_IDS)[number];
6
+
7
+ export const AGENT_EFFORTS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const;
8
+
9
+ export type AgentEffort = (typeof AGENT_EFFORTS)[number];
10
+
11
+ export function isAgentProviderId(value: unknown): value is AgentProviderId {
12
+ return typeof value === 'string' && (AGENT_PROVIDER_IDS as readonly string[]).includes(value);
13
+ }
14
+
15
+ export function isAgentEffort(value: unknown): value is AgentEffort {
16
+ return typeof value === 'string' && (AGENT_EFFORTS as readonly string[]).includes(value);
17
+ }
18
+
19
+ export type AgentModelOption = {
20
+ // Empty when the option stands for the CLI's own default model.
21
+ id: string;
22
+ label: string;
23
+ efforts: AgentEffort[];
24
+ };
25
+
26
+ export type AgentProviderStatus = {
27
+ id: AgentProviderId;
28
+ name: string;
29
+ sdkPackage: string;
30
+ sdkVersion: string | null;
31
+ cliCommand: string;
32
+ cliFound: boolean;
33
+ cliVersion: string | null;
34
+ ready: boolean;
35
+ models: AgentModelOption[];
36
+ };
37
+
38
+ export type AgentStatus = {
39
+ enabled: boolean;
40
+ packageManager: string;
41
+ providers: AgentProviderStatus[];
42
+ };
43
+
44
+ type AgentQuestionOption = { label: string; description?: string };
45
+
46
+ export type AgentQuestion = {
47
+ header: string;
48
+ question: string;
49
+ options: AgentQuestionOption[];
50
+ multiSelect: boolean;
51
+ };
52
+
53
+ export type AgentItem =
54
+ | {
55
+ kind: 'user';
56
+ id: string;
57
+ ts: string;
58
+ text: string;
59
+ // The provider history point just before this message, so editing it
60
+ // can rewind the agent's conversation there.
61
+ resumeAt?: string;
62
+ newDoc?: boolean;
63
+ }
64
+ | { kind: 'assistant'; id: string; ts: string; text: string; streaming: boolean }
65
+ | {
66
+ kind: 'tool';
67
+ id: string;
68
+ ts: string;
69
+ name: string;
70
+ title: string;
71
+ detail: string | null;
72
+ status: 'running' | 'done' | 'error';
73
+ }
74
+ | {
75
+ kind: 'question';
76
+ id: string;
77
+ ts: string;
78
+ questions: AgentQuestion[];
79
+ answers: Record<string, string> | null;
80
+ status: 'pending' | 'answered' | 'cancelled';
81
+ }
82
+ | {
83
+ kind: 'permission';
84
+ id: string;
85
+ ts: string;
86
+ tool: string;
87
+ title: string;
88
+ detail: string | null;
89
+ status: 'pending' | 'allowed' | 'denied';
90
+ }
91
+ | { kind: 'error'; id: string; ts: string; text: string }
92
+ // `open-doc check`, run by the dev server after a turn whose agent cannot
93
+ // start a browser itself.
94
+ | {
95
+ kind: 'check';
96
+ id: string;
97
+ ts: string;
98
+ docId: string;
99
+ status: 'running' | 'done' | 'failed';
100
+ pageCount: number | null;
101
+ // The first few findings; `total` counts them all.
102
+ findings: AgentCheckFinding[];
103
+ total: number;
104
+ error: string | null;
105
+ }
106
+ | {
107
+ kind: 'result';
108
+ id: string;
109
+ ts: string;
110
+ durationMs: number | null;
111
+ costUsd: number | null;
112
+ aborted: boolean;
113
+ };
114
+
115
+ export type AgentCheckFinding = {
116
+ page: number;
117
+ severity: 'error' | 'warn';
118
+ message: string;
119
+ loc?: string;
120
+ };
121
+
122
+ type AgentSessionStatus = 'idle' | 'running';
123
+
124
+ export type AgentSessionSummary = {
125
+ id: string;
126
+ provider: AgentProviderId;
127
+ title: string;
128
+ createdAt: string;
129
+ updatedAt: string;
130
+ status: AgentSessionStatus;
131
+ docId: string | null;
132
+ };
133
+
134
+ export type AgentSession = AgentSessionSummary & {
135
+ providerSessionId: string | null;
136
+ providerCheckpoint?: string | null;
137
+ // Set once the oldest items were dropped to stay under the item cap.
138
+ trimmed?: boolean;
139
+ items: AgentItem[];
140
+ };
141
+
142
+ export type AgentTurnContext = {
143
+ docId?: string;
144
+ docTitle?: string;
145
+ pageNumber?: number;
146
+ totalPages?: number;
147
+ pendingComments?: number;
148
+ selection?: { line: number; column: number; tagName: string; text: string } | null;
149
+ newDoc?: boolean;
150
+ };
151
+
152
+ export type RespondPayload =
153
+ | { answers: Record<string, string> }
154
+ | { allow: boolean }
155
+ | { cancel: true };
156
+
157
+ export type AgentStreamEvent =
158
+ | { type: 'session'; session: AgentSessionSummary }
159
+ | { type: 'session-removed'; sessionId: string }
160
+ | { type: 'item'; sessionId: string; item: AgentItem }
161
+ | { type: 'delta'; sessionId: string; itemId: string; text: string }
162
+ | { type: 'truncate'; sessionId: string; itemId: string }
163
+ | { type: 'doc-renamed'; from: string; to: string };
164
+
165
+ export function sessionSummary(session: AgentSession): AgentSessionSummary {
166
+ const {
167
+ providerSessionId: _p,
168
+ providerCheckpoint: _c,
169
+ trimmed: _t,
170
+ items: _i,
171
+ ...summary
172
+ } = session;
173
+ return summary;
174
+ }
@@ -0,0 +1,46 @@
1
+ import { type LayoutOptions, layoutDiagram } from './layout.ts';
2
+ import { type Diagram, DiagramSyntaxError, parseDiagram } from './parse.ts';
3
+ import { type RenderOptions, renderDiagram } from './render.ts';
4
+
5
+ export type CompiledDiagram = {
6
+ svg: string;
7
+ width: number;
8
+ height: number;
9
+ /** The parsed graph, so a caller can inspect what was drawn without re-parsing. */
10
+ source: Diagram;
11
+ };
12
+
13
+ export type CompileOptions = LayoutOptions & RenderOptions;
14
+
15
+ /** Mermaid-flavoured text in, themed SVG out. One call, no browser. */
16
+ export function compileDiagram(source: string, options: CompileOptions = {}): CompiledDiagram {
17
+ const parsed = parseDiagram(source);
18
+ const laidOut = layoutDiagram(parsed, options);
19
+ return {
20
+ svg: renderDiagram(laidOut, options),
21
+ width: laidOut.width,
22
+ height: laidOut.height,
23
+ source: parsed,
24
+ };
25
+ }
26
+
27
+ export type {
28
+ LaidOutDiagram,
29
+ LaidOutEdge,
30
+ LaidOutLifeline,
31
+ LaidOutNode,
32
+ LaidOutSubgraph,
33
+ LayoutOptions,
34
+ } from './layout.ts';
35
+ export type {
36
+ Diagram,
37
+ DiagramEdge,
38
+ DiagramNode,
39
+ DiagramSubgraph,
40
+ Direction,
41
+ NodeShape,
42
+ SequenceMessage,
43
+ SequenceParticipant,
44
+ } from './parse.ts';
45
+ export type { RenderOptions } from './render.ts';
46
+ export { DiagramSyntaxError, layoutDiagram, parseDiagram, renderDiagram };