@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
|
@@ -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
|
+
};
|
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
import {
|
|
2
|
+
answersPrompt,
|
|
3
|
+
buildTurnPrompt,
|
|
4
|
+
editedPrompt,
|
|
5
|
+
type PromptOptions,
|
|
6
|
+
rewoundPrompt,
|
|
7
|
+
systemPromptAppend,
|
|
8
|
+
} from './prompt.ts';
|
|
9
|
+
import type { AgentProvider, PermissionRequest, ProviderEvent } from './provider.ts';
|
|
10
|
+
import { newId, type SessionStore, titleFromPrompt } from './store.ts';
|
|
11
|
+
import type {
|
|
12
|
+
AgentEffort,
|
|
13
|
+
AgentProviderId,
|
|
14
|
+
AgentQuestion,
|
|
15
|
+
AgentTurnContext,
|
|
16
|
+
RespondPayload,
|
|
17
|
+
} from './types.ts';
|
|
18
|
+
|
|
19
|
+
type SendOptions = {
|
|
20
|
+
text: string;
|
|
21
|
+
context?: AgentTurnContext;
|
|
22
|
+
autoApprove?: boolean;
|
|
23
|
+
model?: string | null;
|
|
24
|
+
effort?: AgentEffort | null;
|
|
25
|
+
// Set when the turn answers questions the agent asked in its last reply:
|
|
26
|
+
// the question item stands in for the user message.
|
|
27
|
+
answering?: string;
|
|
28
|
+
// A user message to replace: the transcript is cut back to it and the
|
|
29
|
+
// turn runs again from there with the new text.
|
|
30
|
+
edit?: string;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
export type TurnSettings = Partial<
|
|
34
|
+
Pick<SendOptions, 'context' | 'autoApprove' | 'model' | 'effort'>
|
|
35
|
+
>;
|
|
36
|
+
|
|
37
|
+
export type TurnEnd = { sessionId: string; userItemId: string };
|
|
38
|
+
|
|
39
|
+
type PendingPrompt =
|
|
40
|
+
| { kind: 'question'; resolve: (answers: Record<string, string> | null) => void }
|
|
41
|
+
| { kind: 'permission'; resolve: (allow: boolean) => void };
|
|
42
|
+
|
|
43
|
+
function cancelPrompt(prompt: PendingPrompt): void {
|
|
44
|
+
if (prompt.kind === 'question') prompt.resolve(null);
|
|
45
|
+
else prompt.resolve(false);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export type AgentRunner = ReturnType<typeof createAgentRunner>;
|
|
49
|
+
|
|
50
|
+
export function createAgentRunner(opts: {
|
|
51
|
+
userCwd: string;
|
|
52
|
+
writableRoots: string[];
|
|
53
|
+
store: SessionStore;
|
|
54
|
+
providers: Record<AgentProviderId, AgentProvider>;
|
|
55
|
+
/** Read per turn: the dev server's origin is only known once it listens. */
|
|
56
|
+
promptOptions?: () => PromptOptions;
|
|
57
|
+
onTurnEnd?: (turn: TurnEnd) => void | Promise<void>;
|
|
58
|
+
}) {
|
|
59
|
+
const { userCwd, writableRoots, store, providers, onTurnEnd } = opts;
|
|
60
|
+
const promptOptions = opts.promptOptions ?? (() => ({ docsDir: 'docs' }));
|
|
61
|
+
const running = new Map<string, AbortController>();
|
|
62
|
+
const pending = new Map<string, PendingPrompt>();
|
|
63
|
+
const lastOptions = new Map<string, SendOptions>();
|
|
64
|
+
|
|
65
|
+
const now = () => new Date().toISOString();
|
|
66
|
+
|
|
67
|
+
function isRunning(sessionId: string): boolean {
|
|
68
|
+
return running.has(sessionId);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function send(sessionId: string, options: SendOptions): Promise<void> {
|
|
72
|
+
const session = store.get(sessionId);
|
|
73
|
+
if (!session) throw new Error(`unknown agent session: ${sessionId}`);
|
|
74
|
+
if (running.has(sessionId)) throw new Error('session is already running');
|
|
75
|
+
const text = options.text.trim();
|
|
76
|
+
if (!text) throw new Error('empty prompt');
|
|
77
|
+
|
|
78
|
+
const provider = providers[session.provider];
|
|
79
|
+
let context = options.context;
|
|
80
|
+
let promptText = text;
|
|
81
|
+
let resumeAt: string | null = null;
|
|
82
|
+
if (options.edit) {
|
|
83
|
+
const index = session.items.findIndex((i) => i.id === options.edit);
|
|
84
|
+
const target = session.items[index];
|
|
85
|
+
if (target?.kind !== 'user') throw new Error('unknown message');
|
|
86
|
+
// Once old items were trimmed, the oldest message left is not where the
|
|
87
|
+
// provider's history starts, so it can't restart from scratch.
|
|
88
|
+
const first =
|
|
89
|
+
!session.trimmed && !session.items.slice(0, index).some((i) => i.kind === 'user');
|
|
90
|
+
if (first) {
|
|
91
|
+
store.patch(sessionId, { providerSessionId: null, providerCheckpoint: null });
|
|
92
|
+
if (target.newDoc && context) context = { ...context, newDoc: true };
|
|
93
|
+
} else if (provider.canRewind && target.resumeAt) {
|
|
94
|
+
resumeAt = target.resumeAt;
|
|
95
|
+
store.patch(sessionId, { providerCheckpoint: resumeAt });
|
|
96
|
+
promptText = rewoundPrompt(text);
|
|
97
|
+
} else {
|
|
98
|
+
promptText = editedPrompt(target.text, text);
|
|
99
|
+
}
|
|
100
|
+
store.truncateFrom(sessionId, target.id);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const controller = new AbortController();
|
|
104
|
+
running.set(sessionId, controller);
|
|
105
|
+
|
|
106
|
+
lastOptions.set(sessionId, { ...options, context, edit: undefined });
|
|
107
|
+
if (session.items.length === 0) store.patch(sessionId, { title: titleFromPrompt(text) });
|
|
108
|
+
if (options.context?.docId && !session.docId) {
|
|
109
|
+
store.patch(sessionId, { docId: options.context.docId });
|
|
110
|
+
}
|
|
111
|
+
for (const item of session.items) {
|
|
112
|
+
if (item.kind === 'question' && item.status === 'pending' && item.id !== options.answering) {
|
|
113
|
+
store.updateItem(sessionId, item.id, 'question', { status: 'cancelled' });
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const userItemId = options.answering ?? newId('u');
|
|
117
|
+
if (!options.answering) {
|
|
118
|
+
store.appendItem(sessionId, {
|
|
119
|
+
kind: 'user',
|
|
120
|
+
id: userItemId,
|
|
121
|
+
ts: now(),
|
|
122
|
+
text,
|
|
123
|
+
...(session.providerCheckpoint ? { resumeAt: session.providerCheckpoint } : {}),
|
|
124
|
+
...(context?.newDoc ? { newDoc: true } : {}),
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
store.patch(sessionId, { status: 'running' });
|
|
128
|
+
|
|
129
|
+
const openText = new Set<string>();
|
|
130
|
+
const openTools = new Set<string>();
|
|
131
|
+
const startedAt = Date.now();
|
|
132
|
+
let resultSeen = false;
|
|
133
|
+
|
|
134
|
+
const appendQuestion = (questions: AgentQuestion[]) =>
|
|
135
|
+
store.appendItem(sessionId, {
|
|
136
|
+
kind: 'question',
|
|
137
|
+
id: newId('q'),
|
|
138
|
+
ts: now(),
|
|
139
|
+
questions,
|
|
140
|
+
answers: null,
|
|
141
|
+
status: 'pending',
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
const emit = (event: ProviderEvent) => {
|
|
145
|
+
if (!store.get(sessionId)) return;
|
|
146
|
+
switch (event.type) {
|
|
147
|
+
case 'session-id':
|
|
148
|
+
store.patch(sessionId, { providerSessionId: event.id });
|
|
149
|
+
return;
|
|
150
|
+
case 'checkpoint':
|
|
151
|
+
store.patch(sessionId, { providerCheckpoint: event.id });
|
|
152
|
+
return;
|
|
153
|
+
case 'text-start':
|
|
154
|
+
openText.add(event.id);
|
|
155
|
+
store.appendItem(sessionId, {
|
|
156
|
+
kind: 'assistant',
|
|
157
|
+
id: event.id,
|
|
158
|
+
ts: now(),
|
|
159
|
+
text: '',
|
|
160
|
+
streaming: true,
|
|
161
|
+
});
|
|
162
|
+
return;
|
|
163
|
+
case 'text-delta':
|
|
164
|
+
if (!openText.has(event.id)) emit({ type: 'text-start', id: event.id });
|
|
165
|
+
store.appendDelta(sessionId, event.id, event.text);
|
|
166
|
+
return;
|
|
167
|
+
case 'text-end': {
|
|
168
|
+
if (!openText.has(event.id)) {
|
|
169
|
+
if (!event.text) return;
|
|
170
|
+
emit({ type: 'text-start', id: event.id });
|
|
171
|
+
}
|
|
172
|
+
openText.delete(event.id);
|
|
173
|
+
const changes =
|
|
174
|
+
event.text !== null ? { streaming: false, text: event.text } : { streaming: false };
|
|
175
|
+
store.updateItem(sessionId, event.id, 'assistant', changes);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
case 'tool-start':
|
|
179
|
+
openTools.add(event.id);
|
|
180
|
+
store.appendItem(sessionId, {
|
|
181
|
+
kind: 'tool',
|
|
182
|
+
id: event.id,
|
|
183
|
+
ts: now(),
|
|
184
|
+
name: event.name,
|
|
185
|
+
title: event.title,
|
|
186
|
+
detail: event.detail,
|
|
187
|
+
status: 'running',
|
|
188
|
+
});
|
|
189
|
+
return;
|
|
190
|
+
case 'tool-end':
|
|
191
|
+
openTools.delete(event.id);
|
|
192
|
+
store.updateItem(sessionId, event.id, 'tool', { status: event.ok ? 'done' : 'error' });
|
|
193
|
+
return;
|
|
194
|
+
case 'error':
|
|
195
|
+
store.appendItem(sessionId, {
|
|
196
|
+
kind: 'error',
|
|
197
|
+
id: newId('e'),
|
|
198
|
+
ts: now(),
|
|
199
|
+
text: event.text,
|
|
200
|
+
});
|
|
201
|
+
return;
|
|
202
|
+
case 'questions':
|
|
203
|
+
appendQuestion(event.questions);
|
|
204
|
+
return;
|
|
205
|
+
case 'result':
|
|
206
|
+
resultSeen = true;
|
|
207
|
+
store.appendItem(sessionId, {
|
|
208
|
+
kind: 'result',
|
|
209
|
+
id: newId('r'),
|
|
210
|
+
ts: now(),
|
|
211
|
+
durationMs: event.durationMs ?? Date.now() - startedAt,
|
|
212
|
+
costUsd: event.costUsd,
|
|
213
|
+
aborted: false,
|
|
214
|
+
});
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
const askUser = (questions: AgentQuestion[]) =>
|
|
220
|
+
new Promise<Record<string, string> | null>((resolve) => {
|
|
221
|
+
if (controller.signal.aborted) return resolve(null);
|
|
222
|
+
const item = appendQuestion(questions);
|
|
223
|
+
pending.set(item.id, {
|
|
224
|
+
kind: 'question',
|
|
225
|
+
resolve: (answers) => {
|
|
226
|
+
pending.delete(item.id);
|
|
227
|
+
store.updateItem(sessionId, item.id, 'question', {
|
|
228
|
+
answers,
|
|
229
|
+
status: answers ? 'answered' : 'cancelled',
|
|
230
|
+
});
|
|
231
|
+
resolve(answers);
|
|
232
|
+
},
|
|
233
|
+
});
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
const requestPermission = (request: PermissionRequest) =>
|
|
237
|
+
new Promise<boolean>((resolve) => {
|
|
238
|
+
if (controller.signal.aborted) return resolve(false);
|
|
239
|
+
const item = store.appendItem(sessionId, {
|
|
240
|
+
kind: 'permission',
|
|
241
|
+
id: newId('p'),
|
|
242
|
+
ts: now(),
|
|
243
|
+
tool: request.tool,
|
|
244
|
+
title: request.title,
|
|
245
|
+
detail: request.detail,
|
|
246
|
+
status: options.autoApprove ? 'allowed' : 'pending',
|
|
247
|
+
});
|
|
248
|
+
if (options.autoApprove) return resolve(true);
|
|
249
|
+
pending.set(item.id, {
|
|
250
|
+
kind: 'permission',
|
|
251
|
+
resolve: (allow) => {
|
|
252
|
+
pending.delete(item.id);
|
|
253
|
+
store.updateItem(sessionId, item.id, 'permission', {
|
|
254
|
+
status: allow ? 'allowed' : 'denied',
|
|
255
|
+
});
|
|
256
|
+
resolve(allow);
|
|
257
|
+
},
|
|
258
|
+
});
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
const finish = () => {
|
|
262
|
+
running.delete(sessionId);
|
|
263
|
+
if (!store.get(sessionId)) return;
|
|
264
|
+
for (const id of openText) {
|
|
265
|
+
store.updateItem(sessionId, id, 'assistant', { streaming: false });
|
|
266
|
+
}
|
|
267
|
+
for (const id of openTools) {
|
|
268
|
+
store.updateItem(sessionId, id, 'tool', { status: 'error' });
|
|
269
|
+
}
|
|
270
|
+
if (!resultSeen) {
|
|
271
|
+
store.appendItem(sessionId, {
|
|
272
|
+
kind: 'result',
|
|
273
|
+
id: newId('r'),
|
|
274
|
+
ts: now(),
|
|
275
|
+
durationMs: Date.now() - startedAt,
|
|
276
|
+
costUsd: null,
|
|
277
|
+
aborted: controller.signal.aborted,
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
store.patch(sessionId, { status: 'idle' });
|
|
281
|
+
if (onTurnEnd) {
|
|
282
|
+
void Promise.resolve()
|
|
283
|
+
.then(() => onTurnEnd({ sessionId, userItemId }))
|
|
284
|
+
.catch((err: unknown) => {
|
|
285
|
+
console.error('[open-doc] agent turn-end handler failed:', err);
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
const promptOpts = promptOptions();
|
|
291
|
+
const prompt = buildTurnPrompt(promptText, context, promptOpts.docsDir);
|
|
292
|
+
void provider
|
|
293
|
+
.run({
|
|
294
|
+
cwd: userCwd,
|
|
295
|
+
writableRoots,
|
|
296
|
+
prompt,
|
|
297
|
+
systemPromptAppend: systemPromptAppend(provider.askInstruction, {
|
|
298
|
+
...promptOpts,
|
|
299
|
+
canOpenBrowser: provider.canOpenBrowser,
|
|
300
|
+
}),
|
|
301
|
+
resume: session.providerSessionId,
|
|
302
|
+
resumeAt,
|
|
303
|
+
model: options.model ?? null,
|
|
304
|
+
effort: options.effort ?? null,
|
|
305
|
+
signal: controller.signal,
|
|
306
|
+
emit,
|
|
307
|
+
askUser,
|
|
308
|
+
requestPermission,
|
|
309
|
+
})
|
|
310
|
+
.catch((err: unknown) => {
|
|
311
|
+
if (controller.signal.aborted) return;
|
|
312
|
+
emit({ type: 'error', text: err instanceof Error ? err.message : String(err) });
|
|
313
|
+
})
|
|
314
|
+
.finally(finish);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function stop(sessionId: string): boolean {
|
|
318
|
+
const controller = running.get(sessionId);
|
|
319
|
+
if (!controller) return false;
|
|
320
|
+
const session = store.get(sessionId);
|
|
321
|
+
if (session) {
|
|
322
|
+
for (const item of session.items) {
|
|
323
|
+
const prompt = pending.get(item.id);
|
|
324
|
+
if (prompt) cancelPrompt(prompt);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
controller.abort();
|
|
328
|
+
return true;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function respond(
|
|
332
|
+
sessionId: string,
|
|
333
|
+
itemId: string,
|
|
334
|
+
payload: RespondPayload,
|
|
335
|
+
next: TurnSettings = {},
|
|
336
|
+
): boolean {
|
|
337
|
+
const session = store.get(sessionId);
|
|
338
|
+
if (!session?.items.some((i) => i.id === itemId)) return false;
|
|
339
|
+
const prompt = pending.get(itemId);
|
|
340
|
+
if (!prompt) return answerInNextTurn(sessionId, itemId, payload, next);
|
|
341
|
+
if ('cancel' in payload) {
|
|
342
|
+
cancelPrompt(prompt);
|
|
343
|
+
return true;
|
|
344
|
+
}
|
|
345
|
+
if (prompt.kind === 'question' && 'answers' in payload) {
|
|
346
|
+
prompt.resolve(payload.answers);
|
|
347
|
+
return true;
|
|
348
|
+
}
|
|
349
|
+
if (prompt.kind === 'permission' && 'allow' in payload) {
|
|
350
|
+
prompt.resolve(payload.allow);
|
|
351
|
+
return true;
|
|
352
|
+
}
|
|
353
|
+
return false;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function answerInNextTurn(
|
|
357
|
+
sessionId: string,
|
|
358
|
+
itemId: string,
|
|
359
|
+
payload: RespondPayload,
|
|
360
|
+
next: TurnSettings,
|
|
361
|
+
): boolean {
|
|
362
|
+
const item = store.get(sessionId)?.items.find((i) => i.id === itemId);
|
|
363
|
+
if (item?.kind !== 'question' || item.status !== 'pending' || running.has(sessionId)) {
|
|
364
|
+
return false;
|
|
365
|
+
}
|
|
366
|
+
if (!('answers' in payload) && !('cancel' in payload)) return false;
|
|
367
|
+
const answers = 'answers' in payload ? payload.answers : null;
|
|
368
|
+
store.updateItem(sessionId, itemId, 'question', {
|
|
369
|
+
answers,
|
|
370
|
+
status: answers ? 'answered' : 'cancelled',
|
|
371
|
+
});
|
|
372
|
+
// The panel sends its current settings; what the last turn used only
|
|
373
|
+
// fills the gaps, e.g. a client that sent none.
|
|
374
|
+
const previous = { ...lastOptions.get(sessionId), ...next };
|
|
375
|
+
const context = previous.context ? { ...previous.context, newDoc: undefined } : undefined;
|
|
376
|
+
void send(sessionId, {
|
|
377
|
+
...previous,
|
|
378
|
+
context,
|
|
379
|
+
text: answersPrompt(item.questions, answers),
|
|
380
|
+
answering: itemId,
|
|
381
|
+
}).catch((err: unknown) => {
|
|
382
|
+
console.error('[open-doc] agent turn failed:', err);
|
|
383
|
+
});
|
|
384
|
+
return true;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function stopAll(): void {
|
|
388
|
+
for (const id of Array.from(running.keys())) stop(id);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
return { send, stop, respond, isRunning, stopAll };
|
|
392
|
+
}
|