@yuriai/web 0.2.7 → 0.2.8-beta.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/README.md +7 -0
- package/dist/assets/{AssistantView-Be0OKo5o.js → AssistantView-BjpY2u0c.js} +3 -3
- package/dist/assets/{DiagramView-Rpb6oenk.js → DiagramView-7j0sZC_P.js} +1 -1
- package/dist/assets/{GuiPluginSurface-DTH9jNDf.js → GuiPluginSurface-D_TK-2vZ.js} +1 -1
- package/dist/assets/MarkdownRenderer-B8zgOCfr.js +2 -0
- package/dist/assets/{MarkdownRendererImpl-CZ9lU4VJ.js → MarkdownRendererImpl-Dh7XVDLd.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-DastQdu7.js → MarkstreamRendererImpl-D-qtRrvg.js} +1 -1
- package/dist/assets/{MobileDetailNavigation-CittPDZ0.js → MobileDetailNavigation-LkTVYLZX.js} +1 -1
- package/dist/assets/{MobileShareBridge-BxsoZnUJ.js → MobileShareBridge-CsTyKMtN.js} +1 -1
- package/dist/assets/{MobileTabPageHeader-BEgQ3L4u.js → MobileTabPageHeader-xz9RMXg4.js} +1 -1
- package/dist/assets/{MultiRunWindow-1o528NZE.js → MultiRunWindow-hMpjV7so.js} +1 -1
- package/dist/assets/{SettingsView-BGEaQC4R.js → SettingsView-D8qpss-X.js} +1 -1
- package/dist/assets/{SettingsWindow-MuJFADe3.js → SettingsWindow-B1VuFkFq.js} +1 -1
- package/dist/assets/{TerminalView-CHDyibi_.js → TerminalView-CLcaJh2M.js} +1 -1
- package/dist/assets/{ToolOutputDialog-Bcry3eoE.js → ToolOutputDialog-BuZo3XvN.js} +1 -1
- package/dist/assets/{appThemeRegistry-CJoBy_eP.js → appThemeRegistry-B7sp1Hw8.js} +1 -1
- package/dist/assets/{capgoAdapter-_oWtDrgf.js → capgoAdapter-vxOdqloD.js} +1 -1
- package/dist/assets/{fileMentionTouchSelection-7KLhnK1O.js → fileMentionTouchSelection-DspnKU8D.js} +1 -1
- package/dist/assets/{gitApi-BEXddXMX.js → gitApi-BLYdWaG8.js} +1 -1
- package/dist/assets/{insertionBoundaries-HkddYmJd.js → insertionBoundaries-DqlfZVY9.js} +1 -1
- package/dist/assets/{main-BKkCvf3L.js → main-DA7z198b.js} +2 -2
- package/dist/assets/{main-CXE9lij2.js → main-Qw23QJ7L.js} +4 -4
- package/dist/assets/{mcpQueries-xfKOWrAa.js → mcpQueries-C6Tu2cF3.js} +1 -1
- package/dist/assets/{miniChat-BKr-HXzy.js → miniChat-HafcB3H-.js} +2 -2
- package/dist/assets/{mobile-CGL4wWLz.js → mobile-DwXoGpxm.js} +2 -2
- package/dist/assets/{mobileBackNavigation-VzxRWLxN.js → mobileBackNavigation-9MR5h5K6.js} +1 -1
- package/dist/assets/{multirun-BmF58wXR.js → multirun-D-je_w02.js} +1 -1
- package/dist/assets/{native-config-CYjStyIM.js → native-config-Bb3pPQPD.js} +1 -1
- package/dist/assets/{projectMeta-DhdEWvmC.js → projectMeta-DaCyZW_D.js} +1 -1
- package/dist/assets/{readiness-uM7foMQ8.js → readiness-BHqz_NPS.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-CYjZYsCZ.js → renderElectronMiniChatApp-COaMALRh.js} +2 -2
- package/dist/assets/{renderMobileApp-Dy2bPXrM.js → renderMobileApp-BOGntDSu.js} +4 -4
- package/dist/assets/{runtimeConfig-Cjjf4017.js → runtimeConfig-BiSluBXe.js} +1 -1
- package/dist/assets/{runtimeEndpointReset-CNyugOcU.js → runtimeEndpointReset-CJwlI_R-.js} +3 -3
- package/dist/assets/{sessionChangeSummary-5npOjhNG.js → sessionChangeSummary-BAv8zzro.js} +1 -1
- package/dist/assets/{sessionLookup-ClhS_rqE.js → sessionLookup-DOw7g15p.js} +1 -1
- package/dist/assets/{speechSettingsQueries-CpOY2X9w.js → speechSettingsQueries-B8zEN5QM.js} +1 -1
- package/dist/assets/types-BiP0jssb.js +2 -0
- package/dist/assets/{useAppFontEffects-BMXDDJtn.js → useAppFontEffects-De1qI6c-.js} +5 -5
- package/dist/assets/{useDesktopWindowControlsLayout-l2q0zXMx.js → useDesktopWindowControlsLayout-BzXi6Wf1.js} +1 -1
- package/dist/assets/{useEffectiveDirectory-rDw8BJo1.js → useEffectiveDirectory-BcbBl_6y.js} +1 -1
- package/dist/assets/{useMobileNavigationStore-EmnPOl61.js → useMobileNavigationStore-DqDCVXO1.js} +3 -3
- package/dist/assets/{useWorkerHighlightedLines-up7t7cwh.js → useWorkerHighlightedLines-CDVleuma.js} +1 -1
- package/dist/index.html +5 -5
- package/dist/mini-chat.html +5 -5
- package/dist/mobile.html +5 -5
- package/package.json +9 -4
- package/server/index.js +3 -3
- package/server/lib/assistants/DOCUMENTATION.md +14 -0
- package/server/lib/assistants/contact-tools.js +145 -10
- package/server/lib/assistants/contact-tools.test.js +11 -2
- package/server/lib/assistants/harness.js +23 -16
- package/server/lib/assistants/harness.test.js +76 -23
- package/server/lib/assistants/memory.http.test.js +2 -2
- package/server/lib/assistants/routes.js +2 -3
- package/server/lib/assistants/service.js +66 -1
- package/server/lib/assistants/service.test.js +37 -0
- package/server/lib/llm/DOCUMENTATION.md +119 -161
- package/server/lib/llm/bridge-client.js +60 -0
- package/server/lib/llm/bridge-client.test.js +35 -0
- package/server/lib/llm/bridge-contract.js +24 -0
- package/server/lib/llm/bridge-plugin.bundle.js +1136 -0
- package/server/lib/llm/bridge-plugin.js +127 -0
- package/server/lib/llm/bridge-plugin.test.js +164 -0
- package/server/lib/llm/completions.js +43 -18
- package/server/lib/llm/completions.test.js +17 -4
- package/server/lib/llm/generate.js +43 -728
- package/server/lib/llm/generate.test.js +62 -1063
- package/server/lib/llm/routes.js +0 -2
- package/server/lib/opencode/feature-routes-runtime.js +1 -0
- package/server/lib/small-model/DOCUMENTATION.md +11 -17
- package/server/lib/small-model/index.js +5 -4
- package/dist/assets/MarkdownRenderer-Dk1A4sLM.js +0 -2
- package/dist/assets/types-C2ml30_A.js +0 -2
- package/server/lib/llm/temp-directory.js +0 -58
- package/server/lib/llm/temp-directory.test.js +0 -57
|
@@ -1,119 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { ensureLlmTempDirectory } from './temp-directory.js';
|
|
1
|
+
import { generateCleanCompletion } from './bridge-client.js';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
4
3
|
|
|
5
|
-
const LLM_AGENT_NAME = 'yuri-llm';
|
|
6
|
-
const TEXT_AGENT_NAME = 'yuri-text';
|
|
7
|
-
const GENERATE_TIMEOUT_MS = 90_000;
|
|
8
|
-
const AGENT_READY_WAIT_MS = 5_000;
|
|
9
|
-
const AGENT_READY_POLL_MS = 250;
|
|
10
|
-
const EMPTY_TEXT_RETRY_DELAYS_MS = [500, 1_000];
|
|
11
|
-
const TEXT_ENVELOPE_INSTRUCTION = 'Transport requirement: serialize your entire next assistant response as a JSON object with exactly one string field "text". Put all requested yuri-message/yuri-tool/yuri-final fences INSIDE that JSON string, escaping newlines and quotes. This is data generation, not a native function call. Do not call native tools. Return only the JSON object, never an empty response.';
|
|
12
4
|
/** Single attachment payload cap (decoded bytes). Composer UI allows larger drafts; gateway enforces this. */
|
|
13
5
|
export const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;
|
|
14
|
-
const MAX_INLINE_FILE_CHARS = 100_000;
|
|
15
6
|
const TEXT_FILE_MIME = /^(text\/|application\/(json|javascript|xml|sql|yaml|x-yaml|toml))/i;
|
|
16
7
|
|
|
17
|
-
const positiveMs = (value, fallback) => (
|
|
18
|
-
Number.isFinite(value) && value > 0 ? Math.trunc(value) : fallback
|
|
19
|
-
);
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* Agent frontmatter for official client agent permissions (action/resource/effect).
|
|
23
|
-
* The final catch-all must deny, with only denies after it; verified before prompt.
|
|
24
|
-
*/
|
|
25
|
-
const AGENT_MARKDOWN = `---
|
|
26
|
-
mode: primary
|
|
27
|
-
hidden: true
|
|
28
|
-
permissions:
|
|
29
|
-
- action: "*"
|
|
30
|
-
resource: "*"
|
|
31
|
-
effect: deny
|
|
32
|
-
---
|
|
33
|
-
|
|
34
|
-
You generate responses for an application-owned assistant. Follow the supplied system instructions and response format.
|
|
35
|
-
The application executes its registered tools, including yuri-tool JSON fences in your response, and supplies their results on the next request.
|
|
36
|
-
Emit the requested application tool call when an action requires one. Your native tool permissions describe this generator process; the application's supplied tool catalog describes the assistant's capabilities.
|
|
37
|
-
Report execution and failures from supplied tool results only.
|
|
38
|
-
Do not call native OpenCode tools, MCP tools, or skill tools. Native permissions are denied for this generator session.
|
|
39
|
-
`;
|
|
40
|
-
|
|
41
|
-
/** Neutral deny-all agent for text-only `session.generate`; the caller's instructions travel in the prompt. */
|
|
42
|
-
const TEXT_AGENT_MARKDOWN = `---
|
|
43
|
-
mode: primary
|
|
44
|
-
hidden: true
|
|
45
|
-
permissions:
|
|
46
|
-
- action: "*"
|
|
47
|
-
resource: "*"
|
|
48
|
-
effect: deny
|
|
49
|
-
---
|
|
50
|
-
|
|
51
|
-
Follow the instructions in the request and respond in the requested format.
|
|
52
|
-
Native OpenCode, MCP, and skill tools are denied for this generator session.
|
|
53
|
-
When the request defines an application tool-call format (such as fenced JSON), write it as plain text in your reply; the application executes it.
|
|
54
|
-
`;
|
|
55
|
-
|
|
56
|
-
const failGenerate = (message, code = 'upstream_error') => {
|
|
57
|
-
const error = new Error(message);
|
|
58
|
-
error.code = code;
|
|
59
|
-
throw error;
|
|
60
|
-
};
|
|
61
|
-
|
|
62
|
-
const clientErrorMessage = (error, fallback) => {
|
|
63
|
-
if (typeof error?.message === 'string' && error.message.trim()) return error.message;
|
|
64
|
-
if (typeof error === 'string' && error.trim()) return error;
|
|
65
|
-
return fallback;
|
|
66
|
-
};
|
|
67
|
-
|
|
68
|
-
const isAbortLike = (error, signal) => (
|
|
69
|
-
signal?.aborted
|
|
70
|
-
|| error?.name === 'AbortError'
|
|
71
|
-
|| error?.code === 'ABORT_ERR'
|
|
72
|
-
|| (typeof error?.message === 'string' && /aborted|This operation was aborted/i.test(error.message))
|
|
73
|
-
);
|
|
74
|
-
|
|
75
|
-
const rethrowIfAborted = (error, signal) => {
|
|
76
|
-
if (!isAbortLike(error, signal)) return;
|
|
77
|
-
if (error instanceof Error) throw error;
|
|
78
|
-
const next = new Error(clientErrorMessage(error, 'aborted'));
|
|
79
|
-
next.name = 'AbortError';
|
|
80
|
-
throw next;
|
|
81
|
-
};
|
|
82
|
-
|
|
83
|
-
const assistantErrorDetail = (error) => {
|
|
84
|
-
if (typeof error === 'string' && error.trim()) return error;
|
|
85
|
-
if (error && typeof error === 'object') {
|
|
86
|
-
if (typeof error.message === 'string' && error.message.trim()) return error.message;
|
|
87
|
-
try {
|
|
88
|
-
return JSON.stringify(error);
|
|
89
|
-
} catch {
|
|
90
|
-
return String(error);
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
return '';
|
|
94
|
-
};
|
|
95
|
-
|
|
96
|
-
const messageText = (message) => {
|
|
97
|
-
if (typeof message?.content === 'string') return message.content;
|
|
98
|
-
if (Array.isArray(message?.content)) {
|
|
99
|
-
return message.content.map((part) => (typeof part?.text === 'string' ? part.text : '')).join('');
|
|
100
|
-
}
|
|
101
|
-
return '';
|
|
102
|
-
};
|
|
103
|
-
|
|
104
|
-
const messageFileParts = (message) => {
|
|
105
|
-
const fromParts = Array.isArray(message?.parts) ? message.parts : [];
|
|
106
|
-
const fromContent = Array.isArray(message?.content) ? message.content : [];
|
|
107
|
-
return [...fromParts, ...fromContent]
|
|
108
|
-
.filter((part) => part?.type === 'file' && typeof part.mime === 'string' && typeof part.url === 'string')
|
|
109
|
-
.map((part) => ({
|
|
110
|
-
type: 'file',
|
|
111
|
-
mime: part.mime,
|
|
112
|
-
url: part.url,
|
|
113
|
-
...(typeof part.filename === 'string' && part.filename.trim() ? { filename: part.filename.trim() } : {}),
|
|
114
|
-
}));
|
|
115
|
-
};
|
|
116
|
-
|
|
117
8
|
/**
|
|
118
9
|
* Strict data-URL parse. Returns null when the URI is not a well-formed data URL.
|
|
119
10
|
* Decoded size is checked against MAX_ATTACHMENT_BYTES.
|
|
@@ -124,638 +15,62 @@ export function parseDataUrl(url) {
|
|
|
124
15
|
if (comma < 5) return null;
|
|
125
16
|
const meta = url.slice(5, comma);
|
|
126
17
|
const payload = url.slice(comma + 1);
|
|
127
|
-
if (!meta || payload
|
|
18
|
+
if (!meta || !payload) return null;
|
|
128
19
|
const parts = meta.split(';');
|
|
129
|
-
const mime =
|
|
20
|
+
const mime = /^[\w.+-]+\/[\w.+-]+$/.test(parts[0]) ? parts[0] : null;
|
|
130
21
|
if (!mime) return null;
|
|
131
|
-
const isBase64 = parts.some(
|
|
22
|
+
const isBase64 = parts.some(part => part.toLowerCase() === 'base64');
|
|
132
23
|
let bytes;
|
|
133
|
-
try {
|
|
134
|
-
|
|
135
|
-
? Buffer.from(payload, 'base64')
|
|
136
|
-
: Buffer.from(decodeURIComponent(payload), 'utf8');
|
|
137
|
-
} catch {
|
|
138
|
-
return null;
|
|
139
|
-
}
|
|
24
|
+
try { bytes = isBase64 ? Buffer.from(payload, 'base64') : Buffer.from(decodeURIComponent(payload), 'utf8'); }
|
|
25
|
+
catch { return null; }
|
|
140
26
|
// Reject corrupt base64 that decodes to empty while payload was non-empty.
|
|
141
|
-
if (isBase64 && bytes.length
|
|
142
|
-
if (bytes.length > MAX_ATTACHMENT_BYTES) {
|
|
143
|
-
const error = new Error(`Attachment exceeds ${MAX_ATTACHMENT_BYTES} byte limit`);
|
|
144
|
-
error.code = 'validation_error';
|
|
145
|
-
throw error;
|
|
146
|
-
}
|
|
27
|
+
if (isBase64 && !bytes.length && payload.replace(/\s/g, '').length) return null;
|
|
28
|
+
if (bytes.length > MAX_ATTACHMENT_BYTES) throw Object.assign(new Error(`Attachment exceeds ${MAX_ATTACHMENT_BYTES} byte limit`), { code: 'validation_error' });
|
|
147
29
|
return { mime, bytes, isBase64, byteLength: bytes.length };
|
|
148
30
|
}
|
|
149
31
|
|
|
150
|
-
const
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
parsed = parseDataUrl(url);
|
|
155
|
-
} catch (error) {
|
|
156
|
-
if (error?.code === 'validation_error') throw error;
|
|
157
|
-
return null;
|
|
158
|
-
}
|
|
159
|
-
if (!parsed) return null;
|
|
160
|
-
const text = parsed.bytes.toString('utf8');
|
|
161
|
-
return text.length > MAX_INLINE_FILE_CHARS ? `${text.slice(0, MAX_INLINE_FILE_CHARS)}\n…` : text;
|
|
162
|
-
};
|
|
163
|
-
|
|
164
|
-
const describeContactFilePart = (part) => {
|
|
165
|
-
const name = part.filename || 'attachment';
|
|
166
|
-
const mime = part.mime || 'application/octet-stream';
|
|
167
|
-
if (typeof mime === 'string' && mime.startsWith('image/')) return `[image: ${name} (${mime})]`;
|
|
168
|
-
const decoded = decodeDataUrlText(part.url, mime);
|
|
169
|
-
if (decoded != null) return `[file: ${name} (${mime})]\n${decoded}`;
|
|
170
|
-
return `[file: ${name} (${mime})]`;
|
|
171
|
-
};
|
|
172
|
-
|
|
173
|
-
/**
|
|
174
|
-
* Validate every file part URL before generate. Non-data URLs are rejected
|
|
175
|
-
* (gateway only accepts contact data-URL attachments).
|
|
176
|
-
*/
|
|
177
|
-
export function assertValidAttachmentParts(files) {
|
|
178
|
-
for (const part of files) {
|
|
179
|
-
if (!part || typeof part.url !== 'string') {
|
|
180
|
-
failGenerate('Attachment is missing a data URL', 'validation_error');
|
|
181
|
-
}
|
|
182
|
-
if (!part.url.startsWith('data:')) {
|
|
183
|
-
failGenerate('Attachment URL must be a data URL', 'validation_error');
|
|
184
|
-
}
|
|
32
|
+
const prepareMessages = (messages, forwardImageParts) => messages.map(message => {
|
|
33
|
+
const descriptions = [];
|
|
34
|
+
const images = [];
|
|
35
|
+
for (const part of message.parts ?? []) {
|
|
185
36
|
const parsed = parseDataUrl(part.url);
|
|
186
|
-
if (!parsed) {
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
const flattenMessages = (messages) => {
|
|
193
|
-
const system = [];
|
|
194
|
-
const turns = [];
|
|
195
|
-
const files = [];
|
|
196
|
-
for (const message of messages) {
|
|
197
|
-
if (!message) continue;
|
|
198
|
-
const text = messageText(message);
|
|
199
|
-
const fileParts = message.role === 'user' ? messageFileParts(message) : [];
|
|
200
|
-
if (message.role === 'system') {
|
|
201
|
-
if (text.trim()) system.push(text);
|
|
202
|
-
continue;
|
|
37
|
+
if (!parsed) throw Object.assign(new Error('Attachment data URL is malformed'), { code: 'validation_error' });
|
|
38
|
+
if (forwardImageParts && part.mime.startsWith('image/')) {
|
|
39
|
+
images.push({ ...part, url: `data:${part.mime};base64,${parsed.bytes.toString('base64')}` });
|
|
40
|
+
} else {
|
|
41
|
+
const label = `[${part.mime.startsWith('image/') ? 'image' : 'file'}: ${part.filename || 'attachment'} (${part.mime})]`;
|
|
42
|
+
descriptions.push(TEXT_FILE_MIME.test(part.mime) ? `${label}\n${parsed.bytes.toString('utf8').slice(0, 100_000)}` : label);
|
|
203
43
|
}
|
|
204
|
-
if (message.role !== 'user' && message.role !== 'assistant') continue;
|
|
205
|
-
const body = [text, ...fileParts.map(describeContactFilePart)].filter((item) => String(item || '').trim()).join('\n');
|
|
206
|
-
if (!body && fileParts.length === 0) continue;
|
|
207
|
-
turns.push(`${message.role === 'assistant' ? 'Assistant' : 'User'}: ${body || '[attachment]'}`);
|
|
208
|
-
files.push(...fileParts);
|
|
209
44
|
}
|
|
210
|
-
return {
|
|
211
|
-
system: system.join('\n\n').trim(),
|
|
212
|
-
prompt: turns.join('\n\n').trim(),
|
|
213
|
-
files,
|
|
214
|
-
};
|
|
215
|
-
};
|
|
216
|
-
|
|
217
|
-
/** Image bytes only when the catalog model is vision-capable. */
|
|
218
|
-
const filesForPrompt = (files, forwardImageParts) => {
|
|
219
|
-
if (forwardImageParts) return files;
|
|
220
|
-
return files.filter((part) => !String(part?.mime || '').startsWith('image/'));
|
|
221
|
-
};
|
|
222
|
-
|
|
223
|
-
const imageFilesForSession = (files, forwardImageParts) => {
|
|
224
|
-
if (!forwardImageParts) return [];
|
|
225
|
-
return files.filter((part) => String(part?.mime || '').startsWith('image/'));
|
|
226
|
-
};
|
|
227
|
-
|
|
228
|
-
const modelRef = (providerID, modelID, variant) => ({
|
|
229
|
-
id: modelID,
|
|
230
|
-
providerID,
|
|
231
|
-
...(variant ? { variant } : {}),
|
|
45
|
+
return { ...message, content: [message.content, ...descriptions].filter(Boolean).join('\n'), ...(images.length ? { parts: images } : { parts: undefined }) };
|
|
232
46
|
});
|
|
233
47
|
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
/**
|
|
244
|
-
* Forward real OpenCode `session.text.delta` tokens for one throwaway session.
|
|
245
|
-
* Consumes data.sessionID / assistantMessageID / ordinal / delta.
|
|
246
|
-
* Returns unsubscribe, or null when deltas cannot be observed.
|
|
247
|
-
*
|
|
248
|
-
* @param {{ globalEventHub?: { subscribeEvent?: Function } | null, sessionID: string, onTextDelta?: ((text: string) => void) | null }} args
|
|
249
|
-
* @returns {(() => void) | null}
|
|
250
|
-
*/
|
|
251
|
-
export function subscribeThrowawayTextDeltas({ globalEventHub, sessionID, onTextDelta }) {
|
|
252
|
-
if (typeof onTextDelta !== 'function') return null;
|
|
253
|
-
if (typeof sessionID !== 'string' || !sessionID) return null;
|
|
254
|
-
if (typeof globalEventHub?.subscribeEvent !== 'function') return null;
|
|
255
|
-
|
|
256
|
-
let assistantMessageID = null;
|
|
257
|
-
let lastOrdinal = -1;
|
|
258
|
-
|
|
259
|
-
const unsubscribe = globalEventHub.subscribeEvent((event) => {
|
|
260
|
-
const payload = eventPayload(event);
|
|
261
|
-
if (payload?.type !== 'session.text.delta') return;
|
|
262
|
-
const data = eventDeltaData(payload);
|
|
263
|
-
if (!data) return;
|
|
264
|
-
if (data.sessionID !== sessionID) return;
|
|
265
|
-
if (typeof data.delta !== 'string' || data.delta.length === 0) return;
|
|
266
|
-
|
|
267
|
-
const messageID = typeof data.assistantMessageID === 'string' && data.assistantMessageID
|
|
268
|
-
? data.assistantMessageID
|
|
269
|
-
: null;
|
|
270
|
-
if (assistantMessageID) {
|
|
271
|
-
if (messageID && messageID !== assistantMessageID) return;
|
|
272
|
-
} else if (messageID) {
|
|
273
|
-
assistantMessageID = messageID;
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
if (typeof data.ordinal === 'number' && Number.isFinite(data.ordinal)) {
|
|
277
|
-
if (data.ordinal <= lastOrdinal) return;
|
|
278
|
-
lastOrdinal = data.ordinal;
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
try {
|
|
282
|
-
onTextDelta(data.delta);
|
|
283
|
-
} catch {
|
|
284
|
-
// Caller callback failures must not abort generate or leave the hub broken.
|
|
285
|
-
}
|
|
286
|
-
});
|
|
287
|
-
|
|
288
|
-
return typeof unsubscribe === 'function' ? unsubscribe : null;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
/**
|
|
292
|
-
* OpenCode loads a new location's config lazily: the first requests against a
|
|
293
|
-
* fresh temp directory can report no agents at all. Poll `agent.get` within a
|
|
294
|
-
* bounded window instead of failing on that first read.
|
|
295
|
-
*/
|
|
296
|
-
const readGeneratorAgent = async ({ client, location, signal, agentID, waitMs, pollMs }) => {
|
|
297
|
-
const deadline = Date.now() + waitMs;
|
|
298
|
-
for (;;) {
|
|
299
|
-
try {
|
|
300
|
-
return await client.agent.get({
|
|
301
|
-
agentID,
|
|
302
|
-
...(location ? { location } : {}),
|
|
303
|
-
}, { signal });
|
|
304
|
-
} catch (error) {
|
|
305
|
-
rethrowIfAborted(error, signal);
|
|
306
|
-
if (Date.now() + pollMs > deadline) throw error;
|
|
307
|
-
await new Promise((resolve) => setTimeout(resolve, pollMs));
|
|
308
|
-
}
|
|
309
|
-
}
|
|
310
|
-
};
|
|
311
|
-
|
|
312
|
-
/**
|
|
313
|
-
* Verify the generator agent has a deny-all rule followed only by denies.
|
|
314
|
-
* Title alone is never treated as isolation. Failure must happen before prompt.
|
|
315
|
-
*/
|
|
316
|
-
export async function assertLlmAgentDenyAll({
|
|
317
|
-
client,
|
|
318
|
-
location,
|
|
319
|
-
signal,
|
|
320
|
-
agentID = LLM_AGENT_NAME,
|
|
321
|
-
waitMs = AGENT_READY_WAIT_MS,
|
|
322
|
-
pollMs = AGENT_READY_POLL_MS,
|
|
323
|
-
}) {
|
|
324
|
-
let result;
|
|
325
|
-
try {
|
|
326
|
-
result = await readGeneratorAgent({ client, location, signal, agentID, waitMs, pollMs });
|
|
327
|
-
} catch (error) {
|
|
328
|
-
rethrowIfAborted(error, signal);
|
|
329
|
-
failGenerate(
|
|
330
|
-
`OpenCode LLM agent is unavailable (${clientErrorMessage(error, 'agent.get failed')}); generation blocked`,
|
|
331
|
-
'llm_attachment_generation_unavailable',
|
|
332
|
-
);
|
|
333
|
-
}
|
|
334
|
-
const permissions = result?.data?.permissions;
|
|
335
|
-
if (!Array.isArray(permissions) || permissions.length === 0) {
|
|
336
|
-
failGenerate(
|
|
337
|
-
'OpenCode LLM agent permissions are missing; generation blocked',
|
|
338
|
-
'llm_attachment_generation_unavailable',
|
|
339
|
-
);
|
|
340
|
-
}
|
|
341
|
-
const lastCatchAll = permissions.findLastIndex(
|
|
342
|
-
(rule) => rule?.action === '*' && rule?.resource === '*',
|
|
343
|
-
);
|
|
344
|
-
const isolated = lastCatchAll > -1
|
|
345
|
-
&& permissions.slice(lastCatchAll).every((rule) => rule?.effect === 'deny');
|
|
346
|
-
if (!isolated) {
|
|
347
|
-
failGenerate(
|
|
348
|
-
'OpenCode LLM agent final permission is not deny-all; generation blocked',
|
|
349
|
-
'llm_attachment_generation_unavailable',
|
|
350
|
-
);
|
|
351
|
-
}
|
|
352
|
-
return result.data;
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
const assistantTextFromMessages = (messages) => {
|
|
356
|
-
if (!Array.isArray(messages) || messages.length === 0) return '';
|
|
357
|
-
for (const message of messages) {
|
|
358
|
-
// message.list order:desc — first assistant is the newest.
|
|
359
|
-
const role = message?.type ?? message?.role ?? message?.info?.role;
|
|
360
|
-
if (role !== 'assistant') continue;
|
|
361
|
-
const error = message?.error ?? message?.info?.error;
|
|
362
|
-
if (error) {
|
|
363
|
-
const detail = assistantErrorDetail(error);
|
|
364
|
-
failGenerate(detail || 'OpenCode assistant error');
|
|
365
|
-
}
|
|
366
|
-
const finish = message?.finish ?? message?.info?.finish;
|
|
367
|
-
if (finish === 'error') {
|
|
368
|
-
failGenerate(assistantErrorDetail(message?.error) || 'OpenCode assistant finish=error');
|
|
369
|
-
}
|
|
370
|
-
const content = Array.isArray(message?.content)
|
|
371
|
-
? message.content
|
|
372
|
-
: Array.isArray(message?.parts)
|
|
373
|
-
? message.parts
|
|
374
|
-
: [];
|
|
375
|
-
const text = content
|
|
376
|
-
.map((part) => (part?.type === 'text' && typeof part.text === 'string' ? part.text : ''))
|
|
377
|
-
.filter(Boolean)
|
|
378
|
-
.join('');
|
|
379
|
-
return text;
|
|
380
|
-
}
|
|
381
|
-
return '';
|
|
382
|
-
};
|
|
383
|
-
|
|
384
|
-
const makeClient = ({ baseUrl, headers, clientFactory }) => {
|
|
385
|
-
if (typeof clientFactory === 'function') return clientFactory();
|
|
386
|
-
return OpenCode.make({ baseUrl, headers });
|
|
387
|
-
};
|
|
388
|
-
|
|
389
|
-
const prepareGeneratorDirectory = async ({ ensureTempDirectory, agentName, agentMarkdown }) => {
|
|
390
|
-
let workingDirectory;
|
|
391
|
-
try {
|
|
392
|
-
workingDirectory = await ensureTempDirectory({ agentName, agentMarkdown });
|
|
393
|
-
} catch (error) {
|
|
394
|
-
failGenerate(
|
|
395
|
-
`LLM temp directory failed (${clientErrorMessage(error, 'ensure failed')})`,
|
|
396
|
-
'llm_attachment_generation_unavailable',
|
|
397
|
-
);
|
|
398
|
-
}
|
|
399
|
-
if (typeof workingDirectory !== 'string' || !workingDirectory.trim()) {
|
|
400
|
-
failGenerate(
|
|
401
|
-
'LLM temp directory is empty; generation blocked',
|
|
402
|
-
'llm_attachment_generation_unavailable',
|
|
403
|
-
);
|
|
404
|
-
}
|
|
405
|
-
return workingDirectory.trim();
|
|
406
|
-
};
|
|
407
|
-
|
|
408
|
-
/**
|
|
409
|
-
* Run `work(sessionID)` inside a throwaway OpenCode session owned by a
|
|
410
|
-
* verified deny-all agent. The session is always removed afterwards;
|
|
411
|
-
* cancellation interrupts it first.
|
|
412
|
-
*/
|
|
413
|
-
async function withThrowawaySession({
|
|
414
|
-
client,
|
|
415
|
-
workingDirectory,
|
|
416
|
-
agentName,
|
|
417
|
-
providerID,
|
|
418
|
-
modelID,
|
|
419
|
-
variant,
|
|
420
|
-
signal,
|
|
421
|
-
persistSessionMetadata,
|
|
422
|
-
onSystemSessionPersisted,
|
|
423
|
-
}, work) {
|
|
424
|
-
const location = { directory: workingDirectory };
|
|
425
|
-
|
|
426
|
-
// Permission isolation must be verified before any prompt. Never use title as isolation.
|
|
427
|
-
await assertLlmAgentDenyAll({ client, location, signal, agentID: agentName });
|
|
428
|
-
|
|
429
|
-
let sessionID = null;
|
|
48
|
+
// Retrying this single inference call cannot replay tools: their execution belongs to the caller.
|
|
49
|
+
export async function generateOpenCodeText({ messages, signal, timeoutMs = 0,
|
|
50
|
+
retryEmptyTextUntilCancelled = false, forwardImageParts = false,
|
|
51
|
+
generateCompletion = generateCleanCompletion, ...options }) {
|
|
52
|
+
signal?.throwIfAborted();
|
|
53
|
+
const controller = new AbortController();
|
|
54
|
+
const requestSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
|
|
55
|
+
const timeout = timeoutMs > 0 ? setTimeout(() => controller.abort(new Error('LLM inference timed out')), timeoutMs) : null;
|
|
430
56
|
try {
|
|
431
|
-
|
|
432
|
-
const
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
metadata: isolationMetadata,
|
|
440
|
-
}, { signal });
|
|
441
|
-
} catch (error) {
|
|
442
|
-
// Temp workspace invisible to OpenCode must fail explicitly.
|
|
443
|
-
failGenerate(
|
|
444
|
-
`OpenCode LLM session create failed (${clientErrorMessage(error, 'create failed')})`,
|
|
445
|
-
'llm_attachment_generation_unavailable',
|
|
446
|
-
);
|
|
447
|
-
}
|
|
448
|
-
sessionID = created?.id ?? created?.data?.id;
|
|
449
|
-
if (!sessionID) {
|
|
450
|
-
failGenerate('OpenCode LLM session create returned no id', 'llm_attachment_generation_unavailable');
|
|
451
|
-
}
|
|
452
|
-
if (typeof persistSessionMetadata === 'function') {
|
|
453
|
-
try {
|
|
454
|
-
await persistSessionMetadata(sessionID, isolationMetadata);
|
|
455
|
-
onSystemSessionPersisted?.({
|
|
456
|
-
sessionID,
|
|
457
|
-
directory: workingDirectory,
|
|
458
|
-
metadata: isolationMetadata,
|
|
459
|
-
});
|
|
460
|
-
} catch (error) {
|
|
461
|
-
console.warn('[llm] failed to persist system session metadata:', error?.message || error);
|
|
462
|
-
}
|
|
463
|
-
}
|
|
464
|
-
return await work(sessionID);
|
|
465
|
-
} finally {
|
|
466
|
-
if (sessionID) {
|
|
467
|
-
if (signal?.aborted) {
|
|
468
|
-
try {
|
|
469
|
-
await client.session.interrupt({ sessionID, continue: false });
|
|
470
|
-
} catch {
|
|
471
|
-
// Best-effort interrupt on timeout/abort.
|
|
472
|
-
}
|
|
57
|
+
const prepared = prepareMessages(messages, forwardImageParts);
|
|
58
|
+
const cacheKey = options.cacheKey || randomUUID();
|
|
59
|
+
for (let attempt = 0; ; attempt++) {
|
|
60
|
+
requestSignal.throwIfAborted();
|
|
61
|
+
const result = await generateCompletion({ ...options, cacheKey, messages: prepared, signal: requestSignal });
|
|
62
|
+
requestSignal.throwIfAborted();
|
|
63
|
+
if (result.finishReason === 'length' || result.finishReason === 'content-filter' || result.finishReason === 'error') {
|
|
64
|
+
throw Object.assign(new Error(`LLM inference ended with ${result.finishReason}`), { code: 'upstream_error' });
|
|
473
65
|
}
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
} catch (error) {
|
|
477
|
-
console.warn('[llm] failed to remove throwaway OpenCode session:', error?.message || error);
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
/**
|
|
484
|
-
* Text-only generation through `session.generate`: one model call per attempt with the
|
|
485
|
-
* session's provider context (so session-scoped providers such as OpenCode Go
|
|
486
|
-
* work), no tool loop, and no messages written to the session.
|
|
487
|
-
*/
|
|
488
|
-
async function generateViaSessionGenerate({ client, prompt, signal, retryEmptyTextUntilCancelled, textEnvelope, ...sessionOptions }) {
|
|
489
|
-
const requestPrompt = textEnvelope ? `${prompt}\n\n${TEXT_ENVELOPE_INSTRUCTION}` : prompt;
|
|
490
|
-
return withThrowawaySession({ client, signal, ...sessionOptions }, async (sessionID) => {
|
|
491
|
-
for (let attempt = 0; ; attempt += 1) {
|
|
492
|
-
signal?.throwIfAborted();
|
|
493
|
-
let result;
|
|
494
|
-
try {
|
|
495
|
-
result = await client.session.generate({ sessionID, prompt: requestPrompt }, { signal });
|
|
496
|
-
} catch (error) {
|
|
497
|
-
rethrowIfAborted(error, signal);
|
|
498
|
-
failGenerate(clientErrorMessage(error, 'OpenCode session.generate failed'));
|
|
499
|
-
}
|
|
500
|
-
signal?.throwIfAborted();
|
|
501
|
-
let text = typeof result?.text === 'string'
|
|
502
|
-
? result.text.trim()
|
|
503
|
-
: typeof result?.data?.text === 'string'
|
|
504
|
-
? result.data.text.trim()
|
|
505
|
-
: '';
|
|
506
|
-
if (textEnvelope && text) {
|
|
507
|
-
const json = text.replace(/^```json\s*\n([\s\S]*)\n```$/u, '$1');
|
|
508
|
-
try {
|
|
509
|
-
const envelope = JSON.parse(json);
|
|
510
|
-
if (envelope && typeof envelope === 'object' && !Array.isArray(envelope)
|
|
511
|
-
&& Object.keys(envelope).length === 1 && typeof envelope.text === 'string') {
|
|
512
|
-
text = envelope.text.trim();
|
|
513
|
-
}
|
|
514
|
-
} catch {
|
|
515
|
-
// Some models still emit the unwrapped protocol; the contact parser validates it.
|
|
516
|
-
}
|
|
517
|
-
}
|
|
518
|
-
if (text) return { text, source: 'session.generate' };
|
|
519
|
-
const delayMs = retryEmptyTextUntilCancelled
|
|
520
|
-
? Math.min(500 * (2 ** Math.min(attempt, 6)), 30_000)
|
|
521
|
-
: EMPTY_TEXT_RETRY_DELAYS_MS[attempt];
|
|
522
|
-
if (delayMs === undefined) failGenerate('OpenCode session.generate returned no text');
|
|
523
|
-
// This call produces text only; retrying it cannot replay application tools.
|
|
66
|
+
if (result.text?.trim() || result.toolCalls?.length) return result;
|
|
67
|
+
if (!retryEmptyTextUntilCancelled && attempt >= 2) throw Object.assign(new Error('LLM returned no text or tool calls'), { code: 'upstream_error' });
|
|
524
68
|
await new Promise((resolve, reject) => {
|
|
525
|
-
const onAbort = () => {
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
};
|
|
530
|
-
const timer = setTimeout(() => {
|
|
531
|
-
signal?.removeEventListener('abort', onAbort);
|
|
532
|
-
resolve();
|
|
533
|
-
}, delayMs);
|
|
534
|
-
signal?.addEventListener('abort', onAbort, { once: true });
|
|
535
|
-
if (signal?.aborted) onAbort();
|
|
536
|
-
});
|
|
537
|
-
}
|
|
538
|
-
});
|
|
539
|
-
}
|
|
540
|
-
|
|
541
|
-
async function generateViaAttachmentSession({
|
|
542
|
-
client,
|
|
543
|
-
system,
|
|
544
|
-
prompt,
|
|
545
|
-
imageFiles,
|
|
546
|
-
signal,
|
|
547
|
-
onTextDelta,
|
|
548
|
-
globalEventHub,
|
|
549
|
-
...sessionOptions
|
|
550
|
-
}) {
|
|
551
|
-
return withThrowawaySession({ client, signal, ...sessionOptions }, async (sessionID) => {
|
|
552
|
-
if (system) {
|
|
553
|
-
try {
|
|
554
|
-
await client.session.instructions.entry.put({
|
|
555
|
-
sessionID,
|
|
556
|
-
key: 'system',
|
|
557
|
-
value: system,
|
|
558
|
-
}, { signal });
|
|
559
|
-
} catch (error) {
|
|
560
|
-
failGenerate(clientErrorMessage(error, 'instructions.entry.put failed'));
|
|
561
|
-
}
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
const unsubscribeDeltas = subscribeThrowawayTextDeltas({
|
|
565
|
-
globalEventHub,
|
|
566
|
-
sessionID,
|
|
567
|
-
onTextDelta,
|
|
568
|
-
});
|
|
569
|
-
try {
|
|
570
|
-
return await promptAttachmentSession({ client, sessionID, prompt, imageFiles, signal });
|
|
571
|
-
} finally {
|
|
572
|
-
try {
|
|
573
|
-
unsubscribeDeltas?.();
|
|
574
|
-
} catch {
|
|
575
|
-
// Unsubscribe must not mask generate errors or block session remove.
|
|
576
|
-
}
|
|
577
|
-
}
|
|
578
|
-
});
|
|
579
|
-
}
|
|
580
|
-
|
|
581
|
-
async function promptAttachmentSession({ client, sessionID, prompt, imageFiles, signal }) {
|
|
582
|
-
const files = imageFiles.map((part) => ({
|
|
583
|
-
uri: part.url,
|
|
584
|
-
...(part.filename ? { name: part.filename } : {}),
|
|
585
|
-
}));
|
|
586
|
-
|
|
587
|
-
try {
|
|
588
|
-
await client.session.prompt({
|
|
589
|
-
sessionID,
|
|
590
|
-
text: prompt || '[attachment]',
|
|
591
|
-
...(files.length > 0 ? { files } : {}),
|
|
592
|
-
delivery: 'steer',
|
|
593
|
-
}, { signal });
|
|
594
|
-
} catch (error) {
|
|
595
|
-
rethrowIfAborted(error, signal);
|
|
596
|
-
failGenerate(clientErrorMessage(error, 'session.prompt failed'));
|
|
597
|
-
}
|
|
598
|
-
|
|
599
|
-
try {
|
|
600
|
-
await client.session.wait({ sessionID }, { signal });
|
|
601
|
-
} catch (error) {
|
|
602
|
-
rethrowIfAborted(error, signal);
|
|
603
|
-
failGenerate(clientErrorMessage(error, 'session.wait failed'));
|
|
604
|
-
}
|
|
605
|
-
|
|
606
|
-
let listed;
|
|
607
|
-
try {
|
|
608
|
-
listed = await client.message.list({
|
|
609
|
-
sessionID,
|
|
610
|
-
limit: 20,
|
|
611
|
-
order: 'desc',
|
|
612
|
-
}, { signal });
|
|
613
|
-
} catch (error) {
|
|
614
|
-
rethrowIfAborted(error, signal);
|
|
615
|
-
failGenerate(clientErrorMessage(error, 'message.list failed'));
|
|
616
|
-
}
|
|
617
|
-
|
|
618
|
-
const messages = Array.isArray(listed?.data) ? listed.data : [];
|
|
619
|
-
const text = assistantTextFromMessages(messages);
|
|
620
|
-
if (!text.trim()) {
|
|
621
|
-
failGenerate('OpenCode LLM generator returned no assistant text');
|
|
622
|
-
}
|
|
623
|
-
return { text: text.trim(), source: 'attachment-session' };
|
|
624
|
-
}
|
|
625
|
-
|
|
626
|
-
/**
|
|
627
|
-
* Generate assistant text through OpenCode's connected providers via
|
|
628
|
-
* `@opencode/client`.
|
|
629
|
-
*
|
|
630
|
-
* Both paths run in a throwaway session owned by a verified deny-all agent in
|
|
631
|
-
* the LLM temp directory, and the session is removed afterwards.
|
|
632
|
-
* - Pure text: `session.generate` (one model call per attempt, nothing written).
|
|
633
|
-
* - Vision image attachments: `session.prompt` + wait + message list.
|
|
634
|
-
* - Non-vision: keep `[image: …]` descriptions; never forward image bytes.
|
|
635
|
-
*
|
|
636
|
-
* Optional internal streaming: `onTextDelta` + `globalEventHub` forwards real
|
|
637
|
-
* `session.text.delta` tokens on the attachment-session path only.
|
|
638
|
-
* `session.generate` cannot emit live deltas (no fake typewriter).
|
|
639
|
-
*
|
|
640
|
-
* Optional `signal` from the contact continuation is combined with the generator
|
|
641
|
-
* deadline (`timeoutMs: 0` disables it). Cancellation still runs throwaway-session cleanup.
|
|
642
|
-
*/
|
|
643
|
-
export async function generateOpenCodeText({
|
|
644
|
-
buildOpenCodeUrl,
|
|
645
|
-
getOpenCodeAuthHeaders,
|
|
646
|
-
providerID,
|
|
647
|
-
modelID,
|
|
648
|
-
messages,
|
|
649
|
-
variant,
|
|
650
|
-
clientFactory,
|
|
651
|
-
ensureTempDirectory = ensureLlmTempDirectory,
|
|
652
|
-
forwardImageParts = false,
|
|
653
|
-
onTextDelta = null,
|
|
654
|
-
globalEventHub = null,
|
|
655
|
-
persistSessionMetadata = null,
|
|
656
|
-
onSystemSessionPersisted = null,
|
|
657
|
-
signal: parentSignal = null,
|
|
658
|
-
timeoutMs = GENERATE_TIMEOUT_MS,
|
|
659
|
-
retryEmptyTextUntilCancelled = false,
|
|
660
|
-
textEnvelope = false,
|
|
661
|
-
}) {
|
|
662
|
-
parentSignal?.throwIfAborted?.();
|
|
663
|
-
if (!providerID || !modelID) {
|
|
664
|
-
const error = new Error('providerID and modelID are required');
|
|
665
|
-
error.code = 'validation_error';
|
|
666
|
-
throw error;
|
|
667
|
-
}
|
|
668
|
-
const flattened = flattenMessages(messages);
|
|
669
|
-
const allFiles = flattened.files;
|
|
670
|
-
assertValidAttachmentParts(allFiles);
|
|
671
|
-
|
|
672
|
-
const imageFiles = imageFilesForSession(allFiles, forwardImageParts);
|
|
673
|
-
// Non-image files stay as prompt descriptions (and inlined text when possible).
|
|
674
|
-
if (!flattened.prompt && imageFiles.length === 0 && allFiles.length === 0) {
|
|
675
|
-
const error = new Error('messages must include a user turn');
|
|
676
|
-
error.code = 'validation_error';
|
|
677
|
-
throw error;
|
|
678
|
-
}
|
|
679
|
-
|
|
680
|
-
const baseUrl = buildOpenCodeUrl('/', '').replace(/\/$/, '');
|
|
681
|
-
const headers = getOpenCodeAuthHeaders() || {};
|
|
682
|
-
const client = makeClient({ baseUrl, headers, clientFactory });
|
|
683
|
-
|
|
684
|
-
const controller = new AbortController();
|
|
685
|
-
const deadlineMs = timeoutMs === 0 ? 0 : positiveMs(timeoutMs, GENERATE_TIMEOUT_MS);
|
|
686
|
-
const requestSignal = parentSignal
|
|
687
|
-
? AbortSignal.any([parentSignal, controller.signal])
|
|
688
|
-
: controller.signal;
|
|
689
|
-
const timeout = deadlineMs === 0 ? null : setTimeout(() => {
|
|
690
|
-
controller.abort(new Error(`OpenCode LLM generate timed out after ${deadlineMs}ms`));
|
|
691
|
-
}, deadlineMs);
|
|
692
|
-
timeout?.unref?.();
|
|
693
|
-
|
|
694
|
-
const sessionOptions = {
|
|
695
|
-
client,
|
|
696
|
-
providerID,
|
|
697
|
-
modelID,
|
|
698
|
-
variant,
|
|
699
|
-
signal: requestSignal,
|
|
700
|
-
persistSessionMetadata,
|
|
701
|
-
onSystemSessionPersisted,
|
|
702
|
-
};
|
|
703
|
-
|
|
704
|
-
try {
|
|
705
|
-
if (imageFiles.length > 0) {
|
|
706
|
-
const workingDirectory = await prepareGeneratorDirectory({
|
|
707
|
-
ensureTempDirectory,
|
|
708
|
-
agentName: LLM_AGENT_NAME,
|
|
709
|
-
agentMarkdown: AGENT_MARKDOWN,
|
|
710
|
-
});
|
|
711
|
-
return await generateViaAttachmentSession({
|
|
712
|
-
...sessionOptions,
|
|
713
|
-
workingDirectory,
|
|
714
|
-
agentName: LLM_AGENT_NAME,
|
|
715
|
-
system: flattened.system,
|
|
716
|
-
prompt: flattened.prompt,
|
|
717
|
-
imageFiles,
|
|
718
|
-
onTextDelta,
|
|
719
|
-
globalEventHub,
|
|
69
|
+
const onAbort = () => { clearTimeout(timer); requestSignal.removeEventListener('abort', onAbort); reject(requestSignal.reason); };
|
|
70
|
+
const timer = setTimeout(() => { requestSignal.removeEventListener('abort', onAbort); resolve(); }, Math.min(500 * (2 ** Math.min(attempt, 6)), 30_000));
|
|
71
|
+
requestSignal.addEventListener('abort', onAbort, { once: true });
|
|
72
|
+
if (requestSignal.aborted) onAbort();
|
|
720
73
|
});
|
|
721
74
|
}
|
|
722
|
-
|
|
723
|
-
// Text path: the system prompt is prepended into the single prompt string.
|
|
724
|
-
const workingDirectory = await prepareGeneratorDirectory({
|
|
725
|
-
ensureTempDirectory,
|
|
726
|
-
agentName: TEXT_AGENT_NAME,
|
|
727
|
-
agentMarkdown: TEXT_AGENT_MARKDOWN,
|
|
728
|
-
});
|
|
729
|
-
const prompt = [flattened.system, flattened.prompt].filter((part) => String(part || '').trim()).join('\n\n');
|
|
730
|
-
return await generateViaSessionGenerate({
|
|
731
|
-
...sessionOptions,
|
|
732
|
-
workingDirectory,
|
|
733
|
-
agentName: TEXT_AGENT_NAME,
|
|
734
|
-
prompt,
|
|
735
|
-
retryEmptyTextUntilCancelled,
|
|
736
|
-
textEnvelope,
|
|
737
|
-
});
|
|
738
|
-
} finally {
|
|
739
|
-
clearTimeout(timeout);
|
|
740
|
-
}
|
|
75
|
+
} finally { if (timeout) clearTimeout(timeout); }
|
|
741
76
|
}
|
|
742
|
-
|
|
743
|
-
export const _test = {
|
|
744
|
-
flattenMessages,
|
|
745
|
-
filesForPrompt,
|
|
746
|
-
imageFilesForSession,
|
|
747
|
-
describeContactFilePart,
|
|
748
|
-
assistantTextFromMessages,
|
|
749
|
-
eventPayload,
|
|
750
|
-
eventDeltaData,
|
|
751
|
-
subscribeThrowawayTextDeltas,
|
|
752
|
-
assertLlmAgentDenyAll,
|
|
753
|
-
parseDataUrl,
|
|
754
|
-
assertValidAttachmentParts,
|
|
755
|
-
LLM_AGENT_NAME,
|
|
756
|
-
AGENT_MARKDOWN,
|
|
757
|
-
TEXT_AGENT_NAME,
|
|
758
|
-
TEXT_AGENT_MARKDOWN,
|
|
759
|
-
MAX_ATTACHMENT_BYTES,
|
|
760
|
-
GENERATE_TIMEOUT_MS,
|
|
761
|
-
};
|