@yuriai/web 0.2.4 → 0.2.7
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/bin/lib/DOCUMENTATION.md +1 -0
- package/dist/assets/{AgentAvatar-BeM4lXfE.js → AgentAvatar-MzDm6uBf.js} +1 -1
- package/dist/assets/AssistantView-Be0OKo5o.js +3 -0
- package/dist/assets/DiagramView-Rpb6oenk.js +1 -0
- package/dist/assets/{FadeInOnReveal-B8BCjwPb.js → FadeInOnReveal-DkmfVoTO.js} +1 -1
- package/dist/assets/{GuiPluginSurface-BTmJlTp9.js → GuiPluginSurface-DTH9jNDf.js} +1 -1
- package/dist/assets/{GuiPluginWindow-jUuZl9JF.js → GuiPluginWindow-dDG5Uyqb.js} +1 -1
- package/dist/assets/{Icon-DofI60x2.js → Icon-BjiyvtB2.js} +1 -1
- package/dist/assets/{ImageLoadingPlaceholder-7jM-y96Q.js → ImageLoadingPlaceholder-CUKFQTAG.js} +1 -1
- package/dist/assets/{LoadingImage-DV6Neoja.js → LoadingImage-B7cT_4Oe.js} +1 -1
- package/dist/assets/MarkdownRenderer-Dk1A4sLM.js +2 -0
- package/dist/assets/{MarkdownRendererImpl-DNDAYS1N.js → MarkdownRendererImpl-CZ9lU4VJ.js} +2 -2
- package/dist/assets/{MarkstreamRendererImpl-D5Gf8Fja.js → MarkstreamRendererImpl-DastQdu7.js} +1 -1
- package/dist/assets/{MobileDetailNavigation-BxOYRnDk.js → MobileDetailNavigation-CittPDZ0.js} +1 -1
- package/dist/assets/{MobileResizableSheet-CuRgnS-k.js → MobileResizableSheet-C9YzOQis.js} +1 -1
- package/dist/assets/MobileShareBridge-BxsoZnUJ.js +4 -0
- package/dist/assets/MobileTabPageHeader-BEgQ3L4u.js +2 -0
- package/dist/assets/{MultiRunWindow-CaHNOGs2.js → MultiRunWindow-1o528NZE.js} +1 -1
- package/dist/assets/OnboardingScreen-D6iQ5qjF.js +1 -0
- package/dist/assets/{OverlayScrollbar-Bi17Olmj.js → OverlayScrollbar-Dbx1atD-.js} +1 -1
- package/dist/assets/SettingsView-BGEaQC4R.js +26 -0
- package/dist/assets/{SettingsWindow-Bbq4v4yl.js → SettingsWindow-MuJFADe3.js} +1 -1
- package/dist/assets/TerminalView-CHDyibi_.js +8 -0
- package/dist/assets/{ToolOutputDialog-BoAGzjT3.js → ToolOutputDialog-Bcry3eoE.js} +3 -3
- package/dist/assets/{YuriLogo-D9cfwLdW.js → YuriLogo-DvRSd5NN.js} +1 -1
- package/dist/assets/appThemeRegistry-CJoBy_eP.js +1 -0
- package/dist/assets/{assistant-attachment-cache-Ul88TuFO.js → assistant-attachment-cache-lEUFn3mr.js} +1 -1
- package/dist/assets/button-BSFWH-Ok.js +1 -0
- package/dist/assets/{capgoAdapter-CrBccKXY.js → capgoAdapter-_oWtDrgf.js} +1 -1
- package/dist/assets/{collapsible-UDWFNcbF.js → collapsible-DaevjAvt.js} +1 -1
- package/dist/assets/{desktop-CfMDfs6c.js → desktop-dp2Z0toS.js} +1 -1
- package/dist/assets/desktopHosts-CYKaLp1V.js +1 -0
- package/dist/assets/{desktopRelayRestore-aNSNYVEB.js → desktopRelayRestore-5yuHB356.js} +1 -1
- package/dist/assets/device-B7GyZCPd.js +2 -0
- package/dist/assets/{diagram-BxF_wECt.js → diagram-7OgmyecX.js} +1 -1
- package/dist/assets/dialog-D1pXn_b9.js +1 -0
- package/dist/assets/dropdown-menu.styles-CGHPvEgD.js +1 -0
- package/dist/assets/{es-iuy57SFI.js → es-DJzbuYpv.js} +1 -1
- package/dist/assets/{fileMentionTouchSelection-C4zBwV8-.js → fileMentionTouchSelection-7KLhnK1O.js} +1 -1
- package/dist/assets/{fileQueries-voABZL1r.js → fileQueries-DbUx7NwP.js} +1 -1
- package/dist/assets/{fileReferenceActions-ui8464r-.js → fileReferenceActions-No7p4Kdo.js} +1 -1
- package/dist/assets/{fr-LyrJa2Qb.js → fr-YDYbYIZQ.js} +1 -1
- package/dist/assets/gitApi-BEXddXMX.js +10 -0
- package/dist/assets/gui-BCPFcL_m.js +1 -0
- package/dist/assets/{host-1RDqqL9w.js → host--4S0vJsG.js} +1 -1
- package/dist/assets/{image-loading-Bqi69xpy.js → image-loading-FUFYiO1j.js} +1 -1
- package/dist/assets/{input-D86Oqf3B.js → input-BhHXFla6.js} +1 -1
- package/dist/assets/insertionBoundaries-HkddYmJd.js +1 -0
- package/dist/assets/{ja-QqNYiTeY.js → ja-SjX3NBJz.js} +1 -1
- package/dist/assets/{ko-CL-s2hwZ.js → ko-BxcUEWjB.js} +1 -1
- package/dist/assets/main-BKkCvf3L.js +2 -0
- package/dist/assets/main-CXE9lij2.js +169 -0
- package/dist/assets/{markdownHeightCache-DB_NzPGt.js → markdownHeightCache-DV2j4PlS.js} +1 -1
- package/dist/assets/mcpQueries-xfKOWrAa.js +1 -0
- package/dist/assets/miniChat-BKr-HXzy.js +2 -0
- package/dist/assets/mobile-CGL4wWLz.js +2 -0
- package/dist/assets/{mobileBackNavigation-Dq7VGDkh.js → mobileBackNavigation-VzxRWLxN.js} +1 -1
- package/dist/assets/multirun-BmF58wXR.js +3 -0
- package/dist/assets/native-config-CYjStyIM.js +1 -0
- package/dist/assets/{persistence-Ck0wskDR.js → persistence-BfjCXjLZ.js} +1 -1
- package/dist/assets/{pl-AKGY_sFU.js → pl-vh0XFuDb.js} +1 -1
- package/dist/assets/platform-DXeTzJHG.js +7 -0
- package/dist/assets/{projectMeta-Bouw3u_q.js → projectMeta-DhdEWvmC.js} +1 -1
- package/dist/assets/{pt-BR-BFRFGU_b.js → pt-BR-Cv5tssQz.js} +1 -1
- package/dist/assets/{queryRuntime-CpsVmMzy.js → queryRuntime-BuRnpVtK.js} +1 -1
- package/dist/assets/{readiness--FInk_Rv.js → readiness-uM7foMQ8.js} +1 -1
- package/dist/assets/renderElectronMiniChatApp-CYjZYsCZ.js +2 -0
- package/dist/assets/renderMobileApp-Dy2bPXrM.js +28 -0
- package/dist/assets/runtime-fetch-BAN5Gnnp.js +1 -0
- package/dist/assets/{runtime-file-download-J_Vcm3tT.js → runtime-file-download-BzblfnMx.js} +1 -1
- package/dist/assets/{runtime-file-resource-Disaet9c.js → runtime-file-resource-D3k0hKDj.js} +1 -1
- package/dist/assets/runtime-switch-CAZiOV2G.js +1 -0
- package/dist/assets/runtimeConfig-Cjjf4017.js +2 -0
- package/dist/assets/runtimeEndpointReset-CNyugOcU.js +149 -0
- package/dist/assets/{scheduledTaskNavigation-C6FKpwPD.js → scheduledTaskNavigation-BZ3B5bpN.js} +1 -1
- package/dist/assets/{sessionChangeSummary-DS-Su8YI.js → sessionChangeSummary-5npOjhNG.js} +1 -1
- package/dist/assets/sessionLookup-ClhS_rqE.js +1 -0
- package/dist/assets/{sortable-tabs-strip-CSXgXPyP.js → sortable-tabs-strip-BnTV_KYG.js} +1 -1
- package/dist/assets/speechSettingsQueries-CpOY2X9w.js +4 -0
- package/dist/assets/src-NlrSCyPZ.css +2 -0
- package/dist/assets/{store-CGMD02tA.js → store-CgQdmzpX.js} +2 -2
- package/dist/assets/terminalApi-CIbkfDkE.js +1 -0
- package/dist/assets/{textarea-CMvxcQhR.js → textarea-Deh9E1KP.js} +1 -1
- package/dist/assets/{tooltip-CnIKZ6bg.js → tooltip-DygQ-2xe.js} +1 -1
- package/dist/assets/{types-Cjsqoaj2.js → types-C2ml30_A.js} +1 -1
- package/dist/assets/{uk-C21_nQhw.js → uk-3a9vdLJ-.js} +1 -1
- package/dist/assets/{useAppFontEffects-DzyOIRw0.js → useAppFontEffects-BMXDDJtn.js} +27 -27
- package/dist/assets/{useAssistantUIStore-4a569vpy.js → useAssistantUIStore-D7JZlg_Q.js} +1 -1
- package/dist/assets/useDesktopWindowControlsLayout-l2q0zXMx.js +1 -0
- package/dist/assets/useEffectiveDirectory-rDw8BJo1.js +1 -0
- package/dist/assets/{useFontPreferences-BPTEYhfn.js → useFontPreferences-51P_6ZRi.js} +1 -1
- package/dist/assets/useMobileNavigationStore-EmnPOl61.js +417 -0
- package/dist/assets/useUIStore-NMQx_cnG.js +1 -0
- package/dist/assets/{useWorkerHighlightedLines-BNm0Snzz.js → useWorkerHighlightedLines-up7t7cwh.js} +1 -1
- package/dist/assets/{zh-CN-C7PVNr9_.js → zh-CN-kwaUr5W5.js} +1 -1
- package/dist/assets/{zh-TW-DLLoB3-e.js → zh-TW-BBs44W7l.js} +1 -1
- package/dist/index.html +19 -21
- package/dist/mini-chat.html +19 -21
- package/dist/mobile.html +19 -21
- package/package.json +1 -1
- package/server/index.d.ts +17 -0
- package/server/index.js +22 -1
- package/server/lib/assistants/DOCUMENTATION.md +17 -1
- package/server/lib/assistants/contact-tools.js +2 -2
- package/server/lib/assistants/harness.js +5 -2
- package/server/lib/assistants/harness.test.js +48 -1
- package/server/lib/host-update/DOCUMENTATION.md +97 -0
- package/server/lib/host-update/cli-worker.js +132 -0
- package/server/lib/host-update/cli.js +62 -0
- package/server/lib/host-update/cli.test.js +59 -0
- package/server/lib/host-update/releases.js +44 -0
- package/server/lib/host-update/routes.js +33 -0
- package/server/lib/host-update/routes.test.js +104 -0
- package/server/lib/host-update/runtime.js +140 -0
- package/server/lib/host-update/runtime.test.js +141 -0
- package/server/lib/llm/DOCUMENTATION.md +24 -5
- package/server/lib/llm/completions.js +6 -0
- package/server/lib/llm/completions.test.js +14 -0
- package/server/lib/llm/generate.js +30 -10
- package/server/lib/llm/generate.test.js +64 -1
- package/server/lib/opencode/bootstrap-runtime.js +2 -0
- package/server/lib/opencode/yuri-routes.js +7 -206
- package/server/lib/opencode/yuri-routes.test.js +6 -6
- package/server/lib/package-manager.js +1 -1
- package/server/lib/projects/project-config.js +5 -1
- package/server/lib/projects/project-config.test.js +26 -0
- package/server/lib/scheduled-tasks/DOCUMENTATION.md +19 -5
- package/server/lib/scheduled-tasks/SESSION_SKILL.md +21 -3
- package/server/lib/scheduled-tasks/routes.js +22 -4
- package/server/lib/scheduled-tasks/routes.test.js +3 -0
- package/server/lib/scheduled-tasks/session-skill-client.mjs +20 -16
- package/server/lib/scheduled-tasks/session-skill.js +55 -12
- package/server/lib/scheduled-tasks/session-skill.test.js +64 -0
- package/server/sse-routes.test.js +3 -0
- package/dist/assets/AssistantView-B1-ZOPte.js +0 -3
- package/dist/assets/DiagramView-byPKPO9k.js +0 -1
- package/dist/assets/GuiPluginLoadingNotice-Ctwyj_6m.js +0 -1
- package/dist/assets/MarkdownRenderer-dWW52CAV.js +0 -2
- package/dist/assets/MobileShareBridge-CXqDXHZG.js +0 -4
- package/dist/assets/MobileTabPageHeader-C7cX5eld.js +0 -2
- package/dist/assets/OnboardingScreen-hvLlaoKt.js +0 -1
- package/dist/assets/SettingsView-DNNscLOq.js +0 -26
- package/dist/assets/TerminalView-LW5vUwDA.js +0 -8
- package/dist/assets/appThemeRegistry-BzU8zJgk.js +0 -1
- package/dist/assets/button-CT7WL0lp.js +0 -1
- package/dist/assets/clipboard-Bj6jZiuP.js +0 -1
- package/dist/assets/desktopHosts-BEzVZGiW.js +0 -1
- package/dist/assets/device-BDrEmxBm.js +0 -2
- package/dist/assets/dialog-BpsbJk8Y.js +0 -1
- package/dist/assets/download-progress-MobTWf23.js +0 -1
- package/dist/assets/dropdown-menu.styles-MkqoyFTv.js +0 -1
- package/dist/assets/gitApi-DqX-QV_L.js +0 -10
- package/dist/assets/gitApiHttp-BhcxUxqo.js +0 -7
- package/dist/assets/gui-CTKa6rbU.js +0 -1
- package/dist/assets/insertionBoundaries-C1W-RfK6.js +0 -1
- package/dist/assets/main-CqoNDCJj.js +0 -2
- package/dist/assets/main-UG2rPfaK.js +0 -169
- package/dist/assets/mcpQueries-DXYEazhg.js +0 -1
- package/dist/assets/miniChat-DaI0JRe4.js +0 -2
- package/dist/assets/mobile-BMlE5RBZ.js +0 -2
- package/dist/assets/multirun-CPqjkmDv.js +0 -3
- package/dist/assets/native-config-CbLOUYef.js +0 -1
- package/dist/assets/platform-kv0OsX45.js +0 -1
- package/dist/assets/reasoning-projection-client-BEhVknv9.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-DR2wc2oc.js +0 -2
- package/dist/assets/renderMobileApp-CaBsjJFs.js +0 -28
- package/dist/assets/runtime-fetch-BclMrQHc.js +0 -1
- package/dist/assets/runtime-switch-WzPG6NMR.js +0 -1
- package/dist/assets/runtimeConfig-DO1kqEsE.js +0 -2
- package/dist/assets/runtimeEndpointReset-D5q3N28H.js +0 -149
- package/dist/assets/sessionLookup-DBlBJhz5.js +0 -1
- package/dist/assets/speechSettingsQueries-BB9b5zyK.js +0 -4
- package/dist/assets/src-hVfg6BZK.css +0 -2
- package/dist/assets/terminalApi-B_oHorrS.js +0 -1
- package/dist/assets/useDesktopWindowControlsLayout-DtdFMwzW.js +0 -1
- package/dist/assets/useEffectiveDirectory-DC4oSzha.js +0 -1
- package/dist/assets/useMobileNavigationStore-DDIFIAUa.js +0 -417
- package/dist/assets/useUIStore-DqtgX2FB.js +0 -1
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { compareVersions, releaseParts } from './releases.js';
|
|
5
|
+
|
|
6
|
+
const ACTIVE = new Set(['checking', 'downloading', 'installing', 'restarting']);
|
|
7
|
+
const CHANNELS = new Set(['stable', 'beta']);
|
|
8
|
+
const failure = (status, code) => Object.assign(new Error(code), { status, code });
|
|
9
|
+
|
|
10
|
+
export async function writeUpdateState(file, value) {
|
|
11
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
12
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
13
|
+
await writeFile(temporary, JSON.stringify(value), { mode: 0o600 });
|
|
14
|
+
await rename(temporary, file);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** One Host-owned plan/operation authority shared by direct and Relay callers. */
|
|
18
|
+
export function createHostUpdateRuntime({ adapter, stateFile, getServerId, currentVersion, now = Date.now }) {
|
|
19
|
+
let state = { channel: null, operation: null };
|
|
20
|
+
let initialized;
|
|
21
|
+
let queue = Promise.resolve();
|
|
22
|
+
const plans = new Map();
|
|
23
|
+
const serial = (work) => {
|
|
24
|
+
const pending = queue.then(work, work);
|
|
25
|
+
queue = pending.catch(() => {});
|
|
26
|
+
return pending;
|
|
27
|
+
};
|
|
28
|
+
const version = () => typeof currentVersion === 'function' ? currentVersion() : currentVersion;
|
|
29
|
+
const statePath = () => typeof stateFile === 'function' ? stateFile() : stateFile;
|
|
30
|
+
const persist = () => writeUpdateState(statePath(), state);
|
|
31
|
+
const initialize = () => initialized ??= (async () => {
|
|
32
|
+
try {
|
|
33
|
+
const saved = JSON.parse(await readFile(statePath(), 'utf8'));
|
|
34
|
+
if (!saved || ![null, 'stable', 'beta'].includes(saved.channel) || (saved.operation && typeof saved.operation.id !== 'string')) throw new Error('Invalid update state');
|
|
35
|
+
state = saved;
|
|
36
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
37
|
+
if (state.operation && ACTIVE.has(state.operation.status)) {
|
|
38
|
+
// A detached CLI worker remains authoritative while installing; only a
|
|
39
|
+
// restarting operation can be verified by the newly running Host.
|
|
40
|
+
if (state.operation.status === 'restarting') {
|
|
41
|
+
const sameHost = !state.operation.serverId || state.operation.serverId === await getServerId();
|
|
42
|
+
state.operation.status = sameHost && state.operation.version === version() ? 'succeeded' : 'failed';
|
|
43
|
+
state.operation.error = state.operation.status === 'failed' ? 'version_mismatch_after_restart' : null;
|
|
44
|
+
state.operation.updatedAt = now();
|
|
45
|
+
await persist();
|
|
46
|
+
} else {
|
|
47
|
+
state.operation.status = 'failed';
|
|
48
|
+
state.operation.error = 'update_interrupted';
|
|
49
|
+
await persist();
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
})();
|
|
53
|
+
const ownBusy = () => Boolean(state.operation && ACTIVE.has(state.operation.status));
|
|
54
|
+
const busy = () => ownBusy() || Boolean(adapter.operation?.() && ACTIVE.has(adapter.operation().status));
|
|
55
|
+
const effectiveChannel = () => adapter.channel?.() ?? state.channel ?? (version().includes('-') ? 'beta' : 'stable');
|
|
56
|
+
const readState = async () => {
|
|
57
|
+
await initialize();
|
|
58
|
+
// The CLI helper owns state after handoff, including failures while offline.
|
|
59
|
+
if (adapter.external && ownBusy()) {
|
|
60
|
+
const saved = JSON.parse(await readFile(statePath(), 'utf8'));
|
|
61
|
+
if (saved.operation?.id === state.operation.id) state = saved;
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
const fingerprint = (release, channel, serverId) => createHash('sha256').update(JSON.stringify({
|
|
65
|
+
release: release && { version: release.version, kind: release.kind, rollback: release.rollback, integrity: release.integrity, artifact: release.artifact },
|
|
66
|
+
channel, serverId, currentVersion: version(), host: adapter.host, platform: process.platform, arch: process.arch,
|
|
67
|
+
})).digest('hex');
|
|
68
|
+
const snapshot = async (channel, update = null, checkError = null) => ({
|
|
69
|
+
serverId: await getServerId(), host: adapter.host, currentVersion: version(), channel,
|
|
70
|
+
supported: adapter.supported !== false, reason: adapter.reason ?? null,
|
|
71
|
+
available: checkError || busy() ? null : Boolean(update),
|
|
72
|
+
update, operation: ownBusy() ? state.operation : adapter.operation?.() ?? state.operation, checkError,
|
|
73
|
+
});
|
|
74
|
+
const inspect = async (requestedChannel) => {
|
|
75
|
+
await readState();
|
|
76
|
+
const channel = requestedChannel ?? effectiveChannel();
|
|
77
|
+
if (!CHANNELS.has(channel)) throw failure(400, 'invalid_update_channel');
|
|
78
|
+
if (busy()) return snapshot(channel);
|
|
79
|
+
await adapter.refreshSupport?.();
|
|
80
|
+
if (adapter.supported === false) return snapshot(channel);
|
|
81
|
+
const cached = plans.get(channel);
|
|
82
|
+
if (cached && cached.checkedAt + 60_000 > now()) return snapshot(channel, {
|
|
83
|
+
...cached.release, integrity: undefined, artifact: undefined, planId: cached.id, expiresAt: cached.expiresAt,
|
|
84
|
+
});
|
|
85
|
+
const release = await adapter.inspect(channel);
|
|
86
|
+
if (!release) return snapshot(channel);
|
|
87
|
+
if (!releaseParts(release.version) || (channel === 'stable' && release.version.includes('-'))) throw failure(502, 'invalid_update_release');
|
|
88
|
+
const serverId = await getServerId();
|
|
89
|
+
const key = fingerprint(release, channel, serverId);
|
|
90
|
+
let plan = plans.get(channel);
|
|
91
|
+
if (!plan || plan.key !== key || plan.expiresAt <= now()) {
|
|
92
|
+
plan = { id: randomUUID(), key, release, channel, checkedAt: now(), expiresAt: now() + 10 * 60_000 };
|
|
93
|
+
plans.set(channel, plan);
|
|
94
|
+
}
|
|
95
|
+
return snapshot(channel, { ...release, integrity: undefined, artifact: undefined, planId: plan.id, expiresAt: plan.expiresAt });
|
|
96
|
+
};
|
|
97
|
+
const get = (channel) => serial(async () => {
|
|
98
|
+
try { return await inspect(channel); }
|
|
99
|
+
catch (error) {
|
|
100
|
+
if (error.status === 400) throw error;
|
|
101
|
+
// Keep task state observable even when release discovery is unavailable.
|
|
102
|
+
return { ...await snapshot(channel ?? effectiveChannel(), null, 'update_check_failed'), checkFailed: true };
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
const start = (request) => serial(async () => {
|
|
106
|
+
await readState();
|
|
107
|
+
if (!request || !releaseParts(request.version) || !CHANNELS.has(request.channel) || typeof request.planId !== 'string') throw failure(400, 'invalid_update_request');
|
|
108
|
+
const previous = state.operation;
|
|
109
|
+
if (previous?.version === request.version && previous.channel === request.channel && previous.planId === request.planId && previous.status !== 'failed') return previous;
|
|
110
|
+
if (busy()) throw failure(409, 'update_in_progress');
|
|
111
|
+
if (adapter.supported === false) throw failure(501, 'host_update_unsupported');
|
|
112
|
+
const plan = plans.get(request.channel);
|
|
113
|
+
if (!plan || plan.id !== request.planId || plan.expiresAt <= now() || plan.release.version !== request.version) throw failure(409, 'update_plan_expired');
|
|
114
|
+
const release = await adapter.inspect(request.channel);
|
|
115
|
+
const serverId = await getServerId();
|
|
116
|
+
if (!release || fingerprint(release, request.channel, serverId) !== plan.key) throw failure(409, 'update_plan_changed');
|
|
117
|
+
if (compareVersions(release.version, version()) < 0 && !(release.rollback && request.channel === 'stable' && version().includes('-') && request.allowDowngrade === true)) throw failure(409, 'update_downgrade_requires_confirmation');
|
|
118
|
+
await adapter.assertReady?.();
|
|
119
|
+
const saved = state;
|
|
120
|
+
state = { channel: request.channel, operation: {
|
|
121
|
+
id: randomUUID(), planId: plan.id, serverId, version: request.version, channel: request.channel,
|
|
122
|
+
kind: release.kind, status: 'checking', progress: null, error: null, updatedAt: now(),
|
|
123
|
+
} };
|
|
124
|
+
try { await persist(); } catch (error) { state = saved; throw error; }
|
|
125
|
+
const operation = { ...state.operation };
|
|
126
|
+
// Do not shut down before the accepted HTTP response has flushed.
|
|
127
|
+
setTimeout(() => {
|
|
128
|
+
const report = async (patch) => {
|
|
129
|
+
Object.assign(state.operation, patch, { updatedAt: now() });
|
|
130
|
+
await persist();
|
|
131
|
+
};
|
|
132
|
+
void Promise.resolve().then(() => adapter.execute({ release, channel: request.channel, stateFile: statePath(), state: structuredClone(state), report }))
|
|
133
|
+
.catch(() => report({ status: 'failed', error: 'update_execution_failed' })).catch(() => {});
|
|
134
|
+
}, 500);
|
|
135
|
+
return operation;
|
|
136
|
+
});
|
|
137
|
+
return { get, start, isBusy: busy, progress(percent) {
|
|
138
|
+
if (state.operation?.status === 'downloading' && Number.isFinite(percent)) state.operation.progress = Math.max(0, Math.min(100, percent));
|
|
139
|
+
} };
|
|
140
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
|
|
2
|
+
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { createHostUpdateRuntime, writeUpdateState } from './runtime.js';
|
|
6
|
+
import { discoverCliRelease, compareVersions } from './releases.js';
|
|
7
|
+
|
|
8
|
+
let directory;
|
|
9
|
+
let stateFile;
|
|
10
|
+
let adapter;
|
|
11
|
+
let clock;
|
|
12
|
+
const release = () => ({ version: '2.1.1', kind: 'ota', rollback: false, releaseNotes: 'Fixes', artifact: { checksum: 'a' } });
|
|
13
|
+
const runtime = (currentVersion = '2.1.0') => createHostUpdateRuntime({ adapter, stateFile: () => stateFile, currentVersion, getServerId: async () => 'host-a', now: () => clock });
|
|
14
|
+
const request = (snapshot) => ({ version: snapshot.update.version, channel: snapshot.channel, planId: snapshot.update.planId });
|
|
15
|
+
beforeEach(async () => {
|
|
16
|
+
directory = await mkdtemp(path.join(tmpdir(), 'host-update-'));
|
|
17
|
+
stateFile = path.join(directory, 'state.json');
|
|
18
|
+
clock = Date.now();
|
|
19
|
+
adapter = { host: 'electron', supported: true, inspect: vi.fn(async () => release()), execute: vi.fn(async () => {}) };
|
|
20
|
+
});
|
|
21
|
+
afterEach(async () => { vi.useRealTimers(); await rm(directory, { recursive: true, force: true }); });
|
|
22
|
+
|
|
23
|
+
it('checks without mutating the selected channel and shares bounded discovery across repeated reads', async () => {
|
|
24
|
+
const host = runtime();
|
|
25
|
+
const plan = await host.get('beta');
|
|
26
|
+
expect(plan).toMatchObject({ serverId: 'host-a', channel: 'beta', update: { version: '2.1.1', kind: 'ota', releaseNotes: 'Fixes' }, operation: null });
|
|
27
|
+
expect(plan.update.artifact).toBeUndefined();
|
|
28
|
+
for (let i = 0; i < 50; i++) expect((await host.get('beta')).update.planId).toBe(plan.update.planId);
|
|
29
|
+
expect(adapter.inspect).toHaveBeenCalledTimes(1);
|
|
30
|
+
await expect(readFile(stateFile)).rejects.toMatchObject({ code: 'ENOENT' });
|
|
31
|
+
expect((await host.get()).channel).toBe('stable');
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('atomically accepts one exact plan, returns it on retries and rejects conflicting versions/channels', async () => {
|
|
35
|
+
vi.useFakeTimers();
|
|
36
|
+
const host = runtime();
|
|
37
|
+
const plan = await host.get('stable');
|
|
38
|
+
const submissions = await Promise.all(Array.from({ length: 10 }, () => host.start(request(plan))));
|
|
39
|
+
expect(new Set(submissions.map((operation) => operation.id)).size).toBe(1);
|
|
40
|
+
const active = await host.get('beta');
|
|
41
|
+
expect(active.operation.status).toBe('checking');
|
|
42
|
+
expect(active.update).toBeNull();
|
|
43
|
+
await expect(host.start({ ...request(plan), channel: 'beta' })).rejects.toMatchObject({ status: 409, code: 'update_in_progress' });
|
|
44
|
+
expect(adapter.inspect).toHaveBeenCalledTimes(2);
|
|
45
|
+
await vi.advanceTimersByTimeAsync(501);
|
|
46
|
+
expect(adapter.execute).toHaveBeenCalledTimes(1);
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it('rejects tampering, changed artifacts and plans issued by another Host', async () => {
|
|
50
|
+
const a = runtime();
|
|
51
|
+
const plan = await a.get();
|
|
52
|
+
await expect(a.start({ ...request(plan), version: '9.9.9' })).rejects.toMatchObject({ status: 409 });
|
|
53
|
+
await expect(runtime().start(request(plan))).rejects.toMatchObject({ code: 'update_plan_expired' });
|
|
54
|
+
adapter.inspect.mockResolvedValue({ ...release(), artifact: { checksum: 'changed' } });
|
|
55
|
+
await expect(a.start(request(plan))).rejects.toMatchObject({ code: 'update_plan_changed' });
|
|
56
|
+
expect(adapter.execute).not.toHaveBeenCalled();
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it('rejects expired plans and invalid channels without executing', async () => {
|
|
60
|
+
const host = runtime();
|
|
61
|
+
const plan = await host.get();
|
|
62
|
+
clock += 10 * 60_000 + 1;
|
|
63
|
+
await expect(host.start(request(plan))).rejects.toMatchObject({ code: 'update_plan_expired' });
|
|
64
|
+
await expect(host.get('nightly')).rejects.toMatchObject({ status: 400 });
|
|
65
|
+
expect(adapter.execute).not.toHaveBeenCalled();
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('reports local desktop activity through GET and blocks a conflicting remote start', async () => {
|
|
69
|
+
const host = runtime();
|
|
70
|
+
const plan = await host.get();
|
|
71
|
+
adapter.operation = () => ({ id: 'local', status: 'downloading', progress: 25 });
|
|
72
|
+
expect(await host.get('beta')).toMatchObject({ available: null, operation: { id: 'local', progress: 25 } });
|
|
73
|
+
await expect(host.start(request(plan))).rejects.toMatchObject({ code: 'update_in_progress' });
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('does not execute or leave an active task when durable admission cannot be written', async () => {
|
|
77
|
+
const host = runtime();
|
|
78
|
+
const plan = await host.get();
|
|
79
|
+
const blocker = path.join(directory, 'not-a-directory');
|
|
80
|
+
await writeFile(blocker, 'block');
|
|
81
|
+
stateFile = path.join(blocker, 'state.json');
|
|
82
|
+
await expect(host.start(request(plan))).rejects.toThrow();
|
|
83
|
+
expect((await host.get()).operation).toBeNull();
|
|
84
|
+
expect(adapter.execute).not.toHaveBeenCalled();
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it('persists execution failure and allows a freshly validated retry', async () => {
|
|
88
|
+
const host = runtime();
|
|
89
|
+
const plan = await host.get();
|
|
90
|
+
adapter.execute.mockRejectedValue(new Error('download failed'));
|
|
91
|
+
await host.start(request(plan));
|
|
92
|
+
await new Promise((resolve) => setTimeout(resolve, 650));
|
|
93
|
+
expect((await host.get()).operation).toMatchObject({ status: 'failed', error: 'update_execution_failed' });
|
|
94
|
+
expect(JSON.parse(await readFile(stateFile, 'utf8')).operation.status).toBe('failed');
|
|
95
|
+
vi.useFakeTimers();
|
|
96
|
+
expect((await host.start(request(plan))).status).toBe('checking');
|
|
97
|
+
expect(adapter.inspect).toHaveBeenCalledTimes(3);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it('only permits an explicitly confirmed beta-to-stable rollback', async () => {
|
|
101
|
+
vi.useFakeTimers();
|
|
102
|
+
adapter.inspect.mockResolvedValue({ ...release(), version: '2.0.9', rollback: true });
|
|
103
|
+
const host = runtime('2.1.0-beta.2');
|
|
104
|
+
const plan = await host.get('stable');
|
|
105
|
+
await expect(host.start(request(plan))).rejects.toMatchObject({ code: 'update_downgrade_requires_confirmation' });
|
|
106
|
+
expect((await host.start({ ...request(plan), allowDowngrade: true })).channel).toBe('stable');
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it('exposes check failure separately from an authoritative empty release', async () => {
|
|
110
|
+
adapter.inspect.mockRejectedValue(new Error('offline'));
|
|
111
|
+
expect(await runtime().get()).toMatchObject({ checkFailed: true, checkError: 'update_check_failed', operation: null });
|
|
112
|
+
adapter.inspect.mockResolvedValue(null);
|
|
113
|
+
expect(await runtime().get()).toMatchObject({ update: null, checkError: null });
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it.each(['2.1.1', '2.1.0'])('verifies durable restarting state against running version %s', async (current) => {
|
|
117
|
+
await writeUpdateState(stateFile, { channel: 'beta', operation: { id: 'op', version: '2.1.1', status: 'restarting' } });
|
|
118
|
+
adapter.inspect.mockResolvedValue(null);
|
|
119
|
+
const result = await runtime(current).get();
|
|
120
|
+
expect(result.operation.status).toBe(current === '2.1.1' ? 'succeeded' : 'failed');
|
|
121
|
+
expect(JSON.parse(await readFile(stateFile, 'utf8')).operation.status).toBe(result.operation.status);
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
it('does not offer an update when the owning adapter is unavailable', async () => {
|
|
125
|
+
adapter.supported = false;
|
|
126
|
+
expect(await runtime().get()).toMatchObject({ supported: false, update: null });
|
|
127
|
+
expect(adapter.inspect).not.toHaveBeenCalled();
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it('compares beta sequence numbers and never selects beta in the stable channel', async () => {
|
|
131
|
+
expect(compareVersions('2.1.0-beta.10', '2.1.0-beta.2')).toBe(1);
|
|
132
|
+
const fetch = vi.fn(async (url) => String(url).includes('registry') ? Response.json({
|
|
133
|
+
'dist-tags': { latest: '2.1.0', beta: '2.1.1-beta.10' }, versions: {
|
|
134
|
+
'2.1.0': { version: '2.1.0', dist: { integrity: 'sha512-stable' } },
|
|
135
|
+
'2.1.1-beta.10': { version: '2.1.1-beta.10', dist: { integrity: 'sha512-beta' } },
|
|
136
|
+
},
|
|
137
|
+
}) : Response.json({ body: 'Notes' }));
|
|
138
|
+
expect(await discoverCliRelease('stable', '2.0.0', fetch)).toMatchObject({ version: '2.1.0', releaseNotes: 'Notes' });
|
|
139
|
+
expect(await discoverCliRelease('beta', '2.0.0', fetch)).toMatchObject({ version: '2.1.1-beta.10' });
|
|
140
|
+
await expect(discoverCliRelease('stable', '2.0.0', async () => new Response('', { status: 503 }))).rejects.toThrow('registry');
|
|
141
|
+
});
|
|
@@ -47,13 +47,32 @@ call Anthropic/OpenAI/plugin SDKs, and does not use the `openai` npm package.
|
|
|
47
47
|
text is prepended into `prompt`.
|
|
48
48
|
4. Always `session.remove` in `finally` (interrupt first on abort/timeout).
|
|
49
49
|
|
|
50
|
-
|
|
51
|
-
same throwaway session with the same prompt. All attempts and
|
|
52
|
-
original generation deadline (90s by default)
|
|
53
|
-
|
|
54
|
-
|
|
50
|
+
By default, empty text responses are retried at most twice, after 500ms and
|
|
51
|
+
1000ms, in the same throwaway session with the same prompt. All attempts and
|
|
52
|
+
backoff share the original generation deadline (90s by default).
|
|
53
|
+
|
|
54
|
+
Internal callers may pass `timeoutMs: 0` to disable that deadline and
|
|
55
|
+
`retryEmptyTextUntilCancelled: true` to recover empty text without an attempt
|
|
56
|
+
limit. Backoff doubles from 500ms to a maximum of 30s. Contact turns use both
|
|
57
|
+
options, including tool follow-ups and terminal-operation summaries. Cancellation
|
|
58
|
+
interrupts requests and backoff immediately, then interrupts/removes the
|
|
59
|
+
throwaway session. Thrown upstream errors still surface; authentication/config
|
|
60
|
+
errors are not silently retried. This does not remove provider-owned deadlines.
|
|
55
61
|
Application tools execute outside this text-only call and are not replayed.
|
|
56
62
|
|
|
63
|
+
Contacts also pass `textEnvelope: true`: the text-only prompt requests a JSON
|
|
64
|
+
object with one `text` string containing the full application response. Decode
|
|
65
|
+
that exact envelope (optionally in a `json` fence) before contact protocol
|
|
66
|
+
validation. Preserve unwrapped responses for the existing contact parser, since
|
|
67
|
+
live models sometimes ignore the transport envelope. Do not unwrap arbitrary
|
|
68
|
+
objects or recursively parse tool arguments. This avoids depending solely on
|
|
69
|
+
bare tool-like text surviving a text-only generation endpoint; real DeepSeek
|
|
70
|
+
multi-tool runs previously returned empty text or only progress at this boundary.
|
|
71
|
+
The attachment path retains its existing streaming protocol.
|
|
72
|
+
|
|
73
|
+
These three options are in-process arguments, never read from HTTP request
|
|
74
|
+
bodies. Other utility/public gateway calls retain their bounded defaults.
|
|
75
|
+
|
|
57
76
|
`generate.text` (sessionless) is not used: session-scoped providers such as
|
|
58
77
|
OpenCode Go reject calls without a session (`x-opencode-session`).
|
|
59
78
|
`onTextDelta` is skipped honestly (no fake typewriter).
|
|
@@ -99,6 +99,9 @@ export async function createChatCompletion({
|
|
|
99
99
|
persistSessionMetadata = null,
|
|
100
100
|
onSystemSessionPersisted = null,
|
|
101
101
|
signal = null,
|
|
102
|
+
timeoutMs,
|
|
103
|
+
retryEmptyTextUntilCancelled = false,
|
|
104
|
+
textEnvelope = false,
|
|
102
105
|
}) {
|
|
103
106
|
signal?.throwIfAborted();
|
|
104
107
|
if (!isRecord(body)) throw new LlmError('validation_error', 400, 'JSON body is required');
|
|
@@ -153,6 +156,9 @@ export async function createChatCompletion({
|
|
|
153
156
|
persistSessionMetadata,
|
|
154
157
|
onSystemSessionPersisted,
|
|
155
158
|
signal,
|
|
159
|
+
timeoutMs,
|
|
160
|
+
retryEmptyTextUntilCancelled,
|
|
161
|
+
textEnvelope,
|
|
156
162
|
});
|
|
157
163
|
} catch (error) {
|
|
158
164
|
if (error instanceof LlmError) throw error;
|
|
@@ -2,6 +2,20 @@ import { describe, expect, it, vi } from 'vitest'
|
|
|
2
2
|
import { LlmError, createChatCompletion } from './completions.js'
|
|
3
3
|
|
|
4
4
|
describe('createChatCompletion', () => {
|
|
5
|
+
it('forwards internal long-running generation options without accepting them from HTTP bodies', async () => {
|
|
6
|
+
const generateText = vi.fn(async () => ({ text: 'done' }))
|
|
7
|
+
const base = {
|
|
8
|
+
generateText,
|
|
9
|
+
loadCatalog: async () => ({ models: [{ providerID: 'p', modelID: 'm' }] }),
|
|
10
|
+
body: { model: 'p/m', messages: [{ role: 'user', content: 'hi' }], timeoutMs: 0, retryEmptyTextUntilCancelled: true, textEnvelope: true },
|
|
11
|
+
}
|
|
12
|
+
await createChatCompletion(base)
|
|
13
|
+
expect(generateText.mock.calls[0][0].timeoutMs).toBeUndefined()
|
|
14
|
+
expect(generateText.mock.calls[0][0].retryEmptyTextUntilCancelled).not.toBe(true)
|
|
15
|
+
expect(generateText.mock.calls[0][0].textEnvelope).not.toBe(true)
|
|
16
|
+
await createChatCompletion({ ...base, timeoutMs: 0, retryEmptyTextUntilCancelled: true, textEnvelope: true })
|
|
17
|
+
expect(generateText.mock.calls[1][0]).toMatchObject({ timeoutMs: 0, retryEmptyTextUntilCancelled: true, textEnvelope: true })
|
|
18
|
+
})
|
|
5
19
|
it.each(['high', 'medium', null, ''])('forwards variant %s with default compatibility', async (variant) => {
|
|
6
20
|
const generateText = vi.fn(async () => ({ text: 'done' }));
|
|
7
21
|
await createChatCompletion({
|
|
@@ -8,6 +8,7 @@ const GENERATE_TIMEOUT_MS = 90_000;
|
|
|
8
8
|
const AGENT_READY_WAIT_MS = 5_000;
|
|
9
9
|
const AGENT_READY_POLL_MS = 250;
|
|
10
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.';
|
|
11
12
|
/** Single attachment payload cap (decoded bytes). Composer UI allows larger drafts; gateway enforces this. */
|
|
12
13
|
export const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024;
|
|
13
14
|
const MAX_INLINE_FILE_CHARS = 100_000;
|
|
@@ -480,29 +481,44 @@ async function withThrowawaySession({
|
|
|
480
481
|
}
|
|
481
482
|
|
|
482
483
|
/**
|
|
483
|
-
* Text-only generation through `session.generate`: one model call with the
|
|
484
|
+
* Text-only generation through `session.generate`: one model call per attempt with the
|
|
484
485
|
* session's provider context (so session-scoped providers such as OpenCode Go
|
|
485
486
|
* work), no tool loop, and no messages written to the session.
|
|
486
487
|
*/
|
|
487
|
-
async function generateViaSessionGenerate({ client, prompt, signal, ...sessionOptions }) {
|
|
488
|
+
async function generateViaSessionGenerate({ client, prompt, signal, retryEmptyTextUntilCancelled, textEnvelope, ...sessionOptions }) {
|
|
489
|
+
const requestPrompt = textEnvelope ? `${prompt}\n\n${TEXT_ENVELOPE_INSTRUCTION}` : prompt;
|
|
488
490
|
return withThrowawaySession({ client, signal, ...sessionOptions }, async (sessionID) => {
|
|
489
491
|
for (let attempt = 0; ; attempt += 1) {
|
|
490
492
|
signal?.throwIfAborted();
|
|
491
493
|
let result;
|
|
492
494
|
try {
|
|
493
|
-
result = await client.session.generate({ sessionID, prompt }, { signal });
|
|
495
|
+
result = await client.session.generate({ sessionID, prompt: requestPrompt }, { signal });
|
|
494
496
|
} catch (error) {
|
|
495
497
|
rethrowIfAborted(error, signal);
|
|
496
498
|
failGenerate(clientErrorMessage(error, 'OpenCode session.generate failed'));
|
|
497
499
|
}
|
|
498
500
|
signal?.throwIfAborted();
|
|
499
|
-
|
|
501
|
+
let text = typeof result?.text === 'string'
|
|
500
502
|
? result.text.trim()
|
|
501
503
|
: typeof result?.data?.text === 'string'
|
|
502
504
|
? result.data.text.trim()
|
|
503
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
|
+
}
|
|
504
518
|
if (text) return { text, source: 'session.generate' };
|
|
505
|
-
const delayMs =
|
|
519
|
+
const delayMs = retryEmptyTextUntilCancelled
|
|
520
|
+
? Math.min(500 * (2 ** Math.min(attempt, 6)), 30_000)
|
|
521
|
+
: EMPTY_TEXT_RETRY_DELAYS_MS[attempt];
|
|
506
522
|
if (delayMs === undefined) failGenerate('OpenCode session.generate returned no text');
|
|
507
523
|
// This call produces text only; retrying it cannot replay application tools.
|
|
508
524
|
await new Promise((resolve, reject) => {
|
|
@@ -613,7 +629,7 @@ async function promptAttachmentSession({ client, sessionID, prompt, imageFiles,
|
|
|
613
629
|
*
|
|
614
630
|
* Both paths run in a throwaway session owned by a verified deny-all agent in
|
|
615
631
|
* the LLM temp directory, and the session is removed afterwards.
|
|
616
|
-
* - Pure text: `session.generate` (
|
|
632
|
+
* - Pure text: `session.generate` (one model call per attempt, nothing written).
|
|
617
633
|
* - Vision image attachments: `session.prompt` + wait + message list.
|
|
618
634
|
* - Non-vision: keep `[image: …]` descriptions; never forward image bytes.
|
|
619
635
|
*
|
|
@@ -622,7 +638,7 @@ async function promptAttachmentSession({ client, sessionID, prompt, imageFiles,
|
|
|
622
638
|
* `session.generate` cannot emit live deltas (no fake typewriter).
|
|
623
639
|
*
|
|
624
640
|
* Optional `signal` from the contact continuation is combined with the generator
|
|
625
|
-
* deadline. Cancellation still runs throwaway-session cleanup.
|
|
641
|
+
* deadline (`timeoutMs: 0` disables it). Cancellation still runs throwaway-session cleanup.
|
|
626
642
|
*/
|
|
627
643
|
export async function generateOpenCodeText({
|
|
628
644
|
buildOpenCodeUrl,
|
|
@@ -640,6 +656,8 @@ export async function generateOpenCodeText({
|
|
|
640
656
|
onSystemSessionPersisted = null,
|
|
641
657
|
signal: parentSignal = null,
|
|
642
658
|
timeoutMs = GENERATE_TIMEOUT_MS,
|
|
659
|
+
retryEmptyTextUntilCancelled = false,
|
|
660
|
+
textEnvelope = false,
|
|
643
661
|
}) {
|
|
644
662
|
parentSignal?.throwIfAborted?.();
|
|
645
663
|
if (!providerID || !modelID) {
|
|
@@ -664,14 +682,14 @@ export async function generateOpenCodeText({
|
|
|
664
682
|
const client = makeClient({ baseUrl, headers, clientFactory });
|
|
665
683
|
|
|
666
684
|
const controller = new AbortController();
|
|
667
|
-
const deadlineMs = positiveMs(timeoutMs, GENERATE_TIMEOUT_MS);
|
|
685
|
+
const deadlineMs = timeoutMs === 0 ? 0 : positiveMs(timeoutMs, GENERATE_TIMEOUT_MS);
|
|
668
686
|
const requestSignal = parentSignal
|
|
669
687
|
? AbortSignal.any([parentSignal, controller.signal])
|
|
670
688
|
: controller.signal;
|
|
671
|
-
const timeout = setTimeout(() => {
|
|
689
|
+
const timeout = deadlineMs === 0 ? null : setTimeout(() => {
|
|
672
690
|
controller.abort(new Error(`OpenCode LLM generate timed out after ${deadlineMs}ms`));
|
|
673
691
|
}, deadlineMs);
|
|
674
|
-
timeout
|
|
692
|
+
timeout?.unref?.();
|
|
675
693
|
|
|
676
694
|
const sessionOptions = {
|
|
677
695
|
client,
|
|
@@ -714,6 +732,8 @@ export async function generateOpenCodeText({
|
|
|
714
732
|
workingDirectory,
|
|
715
733
|
agentName: TEXT_AGENT_NAME,
|
|
716
734
|
prompt,
|
|
735
|
+
retryEmptyTextUntilCancelled,
|
|
736
|
+
textEnvelope,
|
|
717
737
|
});
|
|
718
738
|
} finally {
|
|
719
739
|
clearTimeout(timeout);
|
|
@@ -127,6 +127,68 @@ function textSessionClient({ generate = vi.fn(async () => ({ text: 'reply' })),
|
|
|
127
127
|
}
|
|
128
128
|
|
|
129
129
|
describe('generateOpenCodeText — text path', () => {
|
|
130
|
+
it.each(['json', 'fenced', 'plain'])('decodes the contact text envelope (%s) without changing tool arguments', async (format) => {
|
|
131
|
+
const text = '```yuri-tool\n' + JSON.stringify({ name: 'edit', arguments: { path: 'task.json', edits: [{ oldText: '"model": "old"', newText: '"model": "new"' }] } }) + '\n```'
|
|
132
|
+
const json = JSON.stringify({ text })
|
|
133
|
+
const { client, generate } = textSessionClient({ generate: vi.fn(async () => ({ text: format === 'plain' ? text : format === 'fenced' ? `\`\`\`json\n${json}\n\`\`\`` : json })) })
|
|
134
|
+
const result = await generateOpenCodeText({
|
|
135
|
+
buildOpenCodeUrl: () => 'http://127.0.0.1:4096', getOpenCodeAuthHeaders: () => ({}),
|
|
136
|
+
providerID: 'p', modelID: 'm', messages: [{ role: 'user', content: 'update' }],
|
|
137
|
+
clientFactory: () => client, ensureTempDirectory: async () => '/tmp/yuri-text', textEnvelope: true,
|
|
138
|
+
})
|
|
139
|
+
expect(result.text).toBe(text)
|
|
140
|
+
expect(generate.mock.calls[0][0].prompt).toContain('Transport requirement:')
|
|
141
|
+
})
|
|
142
|
+
|
|
143
|
+
it('keeps a contact generation alive past 90s and repeated empty replies until it recovers', async () => {
|
|
144
|
+
vi.useFakeTimers()
|
|
145
|
+
try {
|
|
146
|
+
const times = []
|
|
147
|
+
const { client, generate, remove } = textSessionClient({ generate: vi.fn(async () => {
|
|
148
|
+
times.push(Date.now())
|
|
149
|
+
return { text: times.length <= 9 ? (times.length % 2 ? '' : JSON.stringify({ text: ' ' })) : 'recovered' }
|
|
150
|
+
}) })
|
|
151
|
+
const outcome = generateOpenCodeText({
|
|
152
|
+
buildOpenCodeUrl: () => 'http://127.0.0.1:4096',
|
|
153
|
+
getOpenCodeAuthHeaders: () => ({}), providerID: 'p', modelID: 'm',
|
|
154
|
+
messages: [{ role: 'user', content: 'continue' }],
|
|
155
|
+
clientFactory: () => client, ensureTempDirectory: async () => '/tmp/yuri-text',
|
|
156
|
+
timeoutMs: 0, retryEmptyTextUntilCancelled: true, textEnvelope: true,
|
|
157
|
+
}).then(value => ({ value }), error => ({ error }))
|
|
158
|
+
await vi.advanceTimersByTimeAsync(180_000)
|
|
159
|
+
expect(await outcome).toMatchObject({ value: { text: 'recovered' } })
|
|
160
|
+
expect(generate).toHaveBeenCalledTimes(10)
|
|
161
|
+
expect(times.slice(1).map((time, i) => time-times[i])).toEqual([500, 1000, 2000, 4000, 8000, 16000, 30000, 30000, 30000])
|
|
162
|
+
expect(remove).toHaveBeenCalledTimes(1)
|
|
163
|
+
expect(vi.getTimerCount()).toBe(0)
|
|
164
|
+
} finally { vi.useRealTimers() }
|
|
165
|
+
})
|
|
166
|
+
|
|
167
|
+
it('can cancel persistent empty-text recovery after the old deadline', async () => {
|
|
168
|
+
vi.useFakeTimers()
|
|
169
|
+
try {
|
|
170
|
+
const controller = new AbortController()
|
|
171
|
+
const { client, generate, remove, interrupt } = textSessionClient({ generate: vi.fn(async () => ({ text: '' })) })
|
|
172
|
+
const outcome = generateOpenCodeText({
|
|
173
|
+
buildOpenCodeUrl: () => 'http://127.0.0.1:4096',
|
|
174
|
+
getOpenCodeAuthHeaders: () => ({}), providerID: 'p', modelID: 'm',
|
|
175
|
+
messages: [{ role: 'user', content: 'continue' }],
|
|
176
|
+
clientFactory: () => client, ensureTempDirectory: async () => '/tmp/yuri-text',
|
|
177
|
+
timeoutMs: 0, retryEmptyTextUntilCancelled: true, signal: controller.signal,
|
|
178
|
+
}).then(value => ({ value }), error => ({ error }))
|
|
179
|
+
await vi.advanceTimersByTimeAsync(100_000)
|
|
180
|
+
expect(remove).not.toHaveBeenCalled()
|
|
181
|
+
const count = generate.mock.calls.length
|
|
182
|
+
controller.abort()
|
|
183
|
+
expect(await outcome).toMatchObject({ error: { name: 'AbortError' } })
|
|
184
|
+
await vi.advanceTimersByTimeAsync(60_000)
|
|
185
|
+
expect(generate).toHaveBeenCalledTimes(count)
|
|
186
|
+
expect(remove).toHaveBeenCalledTimes(1)
|
|
187
|
+
expect(interrupt).toHaveBeenCalledTimes(1)
|
|
188
|
+
expect(vi.getTimerCount()).toBe(0)
|
|
189
|
+
} finally { vi.useRealTimers() }
|
|
190
|
+
})
|
|
191
|
+
|
|
130
192
|
it.each([
|
|
131
193
|
{ name: 'deny-all alone', suffix: [] },
|
|
132
194
|
{ name: 'appended browser deny', suffix: [{ action: 'browser', resource: '*', effect: 'deny' }] },
|
|
@@ -258,7 +320,7 @@ describe('generateOpenCodeText — text path', () => {
|
|
|
258
320
|
expect(agentGet).toHaveBeenCalledTimes(1)
|
|
259
321
|
})
|
|
260
322
|
|
|
261
|
-
it('surfaces session.generate errors and still removes the session', async () => {
|
|
323
|
+
it.each([false, true])('surfaces session.generate errors and still removes the session (persistent=%s)', async (retryEmptyTextUntilCancelled) => {
|
|
262
324
|
const { client, remove, generate } = textSessionClient({
|
|
263
325
|
generate: vi.fn(async () => { throw new Error('Request is missing x-opencode-session') }),
|
|
264
326
|
})
|
|
@@ -268,6 +330,7 @@ describe('generateOpenCodeText — text path', () => {
|
|
|
268
330
|
providerID: 'opencode-go',
|
|
269
331
|
modelID: 'deepseek-v4-flash',
|
|
270
332
|
messages: [{ role: 'user', content: 'hi' }],
|
|
333
|
+
retryEmptyTextUntilCancelled,
|
|
271
334
|
clientFactory: () => client,
|
|
272
335
|
ensureTempDirectory: async () => '/tmp/yuri-text',
|
|
273
336
|
})).rejects.toMatchObject({ code: 'upstream_error', message: 'Request is missing x-opencode-session' })
|