@yuriai/web 0.2.15 → 0.2.20-beta.3
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/dist/assets/AgentAvatar-D5KPQI1N.js +1 -0
- package/dist/assets/AssistantView-huAUB-2Y.js +3 -0
- package/dist/assets/{DiagramView-C8uoLQ35.js → DiagramView-DWV04Xws.js} +1 -1
- package/dist/assets/{FadeInOnReveal-CxIQc2_J.js → FadeInOnReveal-CdoLG8fY.js} +1 -1
- package/dist/assets/{GuiPluginSurface-CFQNrorE.js → GuiPluginSurface-DhD8BqvL.js} +1 -1
- package/dist/assets/{GuiPluginWindow-pZqqyXGs.js → GuiPluginWindow-ezsy5l_y.js} +1 -1
- package/dist/assets/Icon-DvqOB4Dx.js +1 -0
- package/dist/assets/{ImageLoadingPlaceholder-B5t9zOYn.js → ImageLoadingPlaceholder-BVlgaa2r.js} +1 -1
- package/dist/assets/{LoadingImage-ByZs_EGY.js → LoadingImage-BSG8jmn5.js} +1 -1
- package/dist/assets/MarkdownRenderer-BiRplAST.js +2 -0
- package/dist/assets/{MarkdownRendererImpl-BEFLoojj.js → MarkdownRendererImpl-CH8TUMKZ.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-BD0HFc5P.js → MarkstreamRendererImpl-Bmz56IzM.js} +1 -1
- package/dist/assets/{MobileDetailNavigation-BuQ4p5oW.js → MobileDetailNavigation-kKHM_dU3.js} +1 -1
- package/dist/assets/{MobileResizableSheet-BdOIJ61C.js → MobileResizableSheet-jHNytoyX.js} +1 -1
- package/dist/assets/{MobileShareBridge-UNsCJGaT.js → MobileShareBridge-CSDivsPk.js} +2 -2
- package/dist/assets/{MobileTabPageHeader-Bz9YF_Sc.js → MobileTabPageHeader-BkWvNBtr.js} +1 -1
- package/dist/assets/{MultiRunWindow-CNd8aJN7.js → MultiRunWindow-DbllgaJR.js} +1 -1
- package/dist/assets/{OnboardingScreen-CXIYe29y.js → OnboardingScreen-DONIcirJ.js} +1 -1
- package/dist/assets/{OverlayScrollbar-0_OUbhJe.js → OverlayScrollbar-DB2eeXFh.js} +1 -1
- package/dist/assets/{SettingsView-U_aHjrBx.js → SettingsView-6D55BNjw.js} +12 -12
- package/dist/assets/{SettingsWindow-C-FWiRJy.js → SettingsWindow-BrrnHfnR.js} +1 -1
- package/dist/assets/{TerminalView-Dl95RuIA.js → TerminalView-8JYW5f-c.js} +1 -1
- package/dist/assets/ToolOutputDialog-DZO89hKv.js +10 -0
- package/dist/assets/{YuriLogo-_lN4cqhJ.js → YuriLogo-CYdRUurL.js} +1 -1
- package/dist/assets/{appThemeRegistry-ByDzLana.js → appThemeRegistry-Nb-sUfbK.js} +1 -1
- package/dist/assets/{assistant-attachment-cache-lEUFn3mr.js → assistant-attachment-cache-C2SmtQG7.js} +1 -1
- package/dist/assets/{button-DFX-UCuQ.js → button-nola46HU.js} +1 -1
- package/dist/assets/{capgoAdapter-DB7INL7g.js → capgoAdapter-CHeo9q51.js} +1 -1
- package/dist/assets/{collapsible-CDkbWw1M.js → collapsible-BQaMLh6O.js} +1 -1
- package/dist/assets/{desktop-dp2Z0toS.js → desktop-CiqEZVr5.js} +1 -1
- package/dist/assets/{desktopHosts-CYKaLp1V.js → desktopHosts-B4HMNmrx.js} +1 -1
- package/dist/assets/{desktopRelayRestore-5yuHB356.js → desktopRelayRestore-CRl62mqn.js} +1 -1
- package/dist/assets/{device-DzWRCXhq.js → device-Coc5tapU.js} +1 -1
- package/dist/assets/{diagram-JdjLWkpD.js → diagram-COti_aKS.js} +1 -1
- package/dist/assets/{dialog-jQrYy1B7.js → dialog-B2CTTXwv.js} +1 -1
- package/dist/assets/{dropdown-menu.styles-EKni18O6.js → dropdown-menu.styles-BzpQaok_.js} +1 -1
- package/dist/assets/{es-BJGEAUsH.js → es-DklBd0ox.js} +1 -1
- package/dist/assets/{fileMentionTouchSelection-CkO5Pveg.js → fileMentionTouchSelection-CXepBNtQ.js} +1 -1
- package/dist/assets/{fileQueries-DbUx7NwP.js → fileQueries-Bd-OEFmO.js} +1 -1
- package/dist/assets/{fileReferenceActions-No7p4Kdo.js → fileReferenceActions-BnPPqYXw.js} +1 -1
- package/dist/assets/{fr-CFAAV_Hr.js → fr-CVUs46wM.js} +1 -1
- package/dist/assets/{gitApi-0Rr-brg2.js → gitApi-B7AeNXrj.js} +1 -1
- package/dist/assets/{gitApiHttp-BtI23x-7.js → gitApiHttp-CoNokuDM.js} +1 -1
- package/dist/assets/{gui-BCPFcL_m.js → gui-D3wrcUs6.js} +1 -1
- package/dist/assets/{host-BoCxB_x4.js → host-BCXyr41J.js} +1 -1
- package/dist/assets/{image-loading-FUFYiO1j.js → image-loading-DVZlFuU5.js} +1 -1
- package/dist/assets/{input-g3JXmugD.js → input-DGnhaqoc.js} +1 -1
- package/dist/assets/{insertionBoundaries-CLKaunvi.js → insertionBoundaries-Db0R1aBj.js} +1 -1
- package/dist/assets/{ja-1qFce7BA.js → ja-5reg09JK.js} +1 -1
- package/dist/assets/{ko-BDwpL-64.js → ko-DZdC6ooz.js} +1 -1
- package/dist/assets/main-DQ0F0yuL.js +169 -0
- package/dist/assets/{main-D0kTACo9.js → main-d2AaD_PZ.js} +2 -2
- package/dist/assets/{markdownHeightCache-BsFt9Iuh.js → markdownHeightCache-C_JI5qIR.js} +1 -1
- package/dist/assets/{mcpQueries-D0LNcR1q.js → mcpQueries-BgFj7wfO.js} +1 -1
- package/dist/assets/miniChat-BHdsTyJ3.js +2 -0
- package/dist/assets/mobile-BEhQq4tx.js +2 -0
- package/dist/assets/{mobileBackNavigation-DPmsYwPj.js → mobileBackNavigation-s9RsXUUH.js} +1 -1
- package/dist/assets/{multirun-BLDsdBIC.js → multirun-BZsBsBAj.js} +1 -1
- package/dist/assets/{native-config-ByqoltPf.js → native-config-BmrfOzkM.js} +1 -1
- package/dist/assets/{persistence-BfjCXjLZ.js → persistence-CNEHspb4.js} +1 -1
- package/dist/assets/{pl-COzHGIeC.js → pl-BerZSK-a.js} +1 -1
- package/dist/assets/{platform-syRnKuVU.js → platform-Q45KPuGv.js} +1 -1
- package/dist/assets/{projectMeta-UNs8fviv.js → projectMeta-BCGIXTbR.js} +1 -1
- package/dist/assets/{pt-BR-B6ps5NQH.js → pt-BR-ydmV6U49.js} +1 -1
- package/dist/assets/{queryRuntime-BuRnpVtK.js → queryRuntime-DWgXfxGx.js} +1 -1
- package/dist/assets/{readiness-Dl3hJelb.js → readiness-BxT5OBkk.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-ShVOG0Py.js → renderElectronMiniChatApp-BbfF6SjM.js} +2 -2
- package/dist/assets/{renderMobileApp-Dda4hoGA.js → renderMobileApp-ulSQxT-l.js} +6 -6
- package/dist/assets/runtime-auth-BaBM02zI.js +1 -0
- package/dist/assets/{runtime-fetch-BAN5Gnnp.js → runtime-fetch-DfALP7-b.js} +1 -1
- package/dist/assets/{runtime-file-download-BzblfnMx.js → runtime-file-download-xvItwYMc.js} +1 -1
- package/dist/assets/{runtime-file-resource-D3k0hKDj.js → runtime-file-resource-DtsKbFf3.js} +1 -1
- package/dist/assets/{runtime-switch-CAZiOV2G.js → runtime-switch-DhMY9eiB.js} +1 -1
- package/dist/assets/{runtimeConfig-CijjWK-g.js → runtimeConfig-BHRHZbwI.js} +1 -1
- package/dist/assets/{runtimeEndpointReset-CB04brBn.js → runtimeEndpointReset-H2W1kxcO.js} +4 -4
- package/dist/assets/{scheduledTaskNavigation-DPl7XI48.js → scheduledTaskNavigation-CkBcoGV4.js} +1 -1
- package/dist/assets/{sessionChangeSummary-CRPfojF7.js → sessionChangeSummary-CAU-06Bu.js} +1 -1
- package/dist/assets/{sessionLookup-7qVMN2KO.js → sessionLookup-YvkfClst.js} +1 -1
- package/dist/assets/{sortable-tabs-strip-Bp_bMUwf.js → sortable-tabs-strip-pCvZjmMt.js} +1 -1
- package/dist/assets/{speechSettingsQueries-DkLz1lXd.js → speechSettingsQueries-1LD5eEHK.js} +2 -2
- package/dist/assets/src-DGCTlpkW.css +2 -0
- package/dist/assets/{store-CKaWYiP4.js → store-ClIuNNU7.js} +2 -2
- package/dist/assets/{terminalApi-Dw1h9m3h.js → terminalApi-DFhCeMya.js} +1 -1
- package/dist/assets/{textarea-BuvlUTo2.js → textarea-DSHEMw8t.js} +1 -1
- package/dist/assets/{tooltip-Byl6nrXB.js → tooltip-BwTvgqWG.js} +1 -1
- package/dist/assets/types-CiQgQf3s.js +2 -0
- package/dist/assets/{uk-StL0Y7Ti.js → uk-BnTevguX.js} +1 -1
- package/dist/assets/{useAppFontEffects-CL3-doYG.js → useAppFontEffects-Cz9eoInx.js} +53 -53
- package/dist/assets/{useAssistantUIStore-rdsbsVts.js → useAssistantUIStore-BZt-lLlW.js} +1 -1
- package/dist/assets/{useDesktopWindowControlsLayout-BCwpHdQs.js → useDesktopWindowControlsLayout-HpOlTBoV.js} +1 -1
- package/dist/assets/{useEffectiveDirectory-D2Yehntp.js → useEffectiveDirectory-DE-YccE8.js} +1 -1
- package/dist/assets/{useFontPreferences-B4LGrKaG.js → useFontPreferences-DmeLn0t9.js} +1 -1
- package/dist/assets/{useMobileNavigationStore-uTICFg9r.js → useMobileNavigationStore-DPE5LVui.js} +22 -22
- package/dist/assets/{useUIStore-NMQx_cnG.js → useUIStore-CEingF2z.js} +1 -1
- package/dist/assets/useWorkerHighlightedLines-o-elkNrd.js +7 -0
- package/dist/assets/{vendor-framer-motion-D8hQsul-.js → vendor-framer-motion-BQ3-sJMO.js} +1 -1
- package/dist/assets/vendor-motion-B4xmxmaP.js +1 -0
- package/dist/assets/{zh-CN-CxO7ZteK.js → zh-CN-DT6qIAPJ.js} +1 -1
- package/dist/assets/{zh-TW-9MJgbinh.js → zh-TW-CtLsIcFb.js} +1 -1
- package/dist/index.html +21 -21
- package/dist/mini-chat.html +21 -21
- package/dist/mobile.html +21 -21
- package/package.json +1 -1
- package/server/lib/assistants/DOCUMENTATION.md +205 -6
- package/server/lib/assistants/assign.js +2 -1
- package/server/lib/assistants/contact-attachments.http.test.js +1 -1
- package/server/lib/assistants/contact-greeting.js +18 -0
- package/server/lib/assistants/contact-tools.js +11 -10
- package/server/lib/assistants/harness.js +23 -7
- package/server/lib/assistants/harness.test.js +35 -7
- package/server/lib/assistants/opencode-tools.js +167 -0
- package/server/lib/assistants/opencode-tools.test.js +295 -0
- package/server/lib/assistants/progressive-tools.js +33 -0
- package/server/lib/assistants/progressive-tools.test.js +66 -0
- package/server/lib/assistants/routes.js +1 -0
- package/server/lib/assistants/service.js +40 -9
- package/server/lib/assistants/service.test.js +401 -26
- package/server/lib/assistants/yuri-project.http.test.js +126 -0
- package/server/lib/assistants/yuri-tools.js +42 -0
- package/server/lib/assistants/yuri-tools.test.js +151 -0
- package/server/lib/opencode/DOCUMENTATION.md +1 -0
- package/server/lib/opencode/feature-routes-runtime.js +9 -0
- package/server/lib/opencode/feature-routes-runtime.test.js +12 -0
- package/server/lib/opencode/routes.js +4 -32
- package/server/lib/opencode/settings-runtime.js +7 -2
- package/server/lib/projects/DOCUMENTATION.md +29 -0
- package/server/lib/projects/registry.js +36 -0
- package/server/lib/projects/registry.test.js +107 -0
- package/server/lib/quota/magpie.js +2 -2
- package/server/lib/quota/providers/index.js +6 -2
- package/server/lib/quota/providers/index.test.js +6 -1
- package/server/lib/relay/DOCUMENTATION.md +3 -3
- package/server/lib/relay/host-client.js +4 -6
- package/server/lib/relay/host-client.reconnect.test.js +3 -2
- package/server/lib/relay/relay-server.e2e.test.ts +144 -1
- package/dist/assets/AgentAvatar-DJCC3Aqe.js +0 -1
- package/dist/assets/AssistantView-C4PAEb1I.js +0 -3
- package/dist/assets/Icon-C1nXIg7J.js +0 -1
- package/dist/assets/MarkdownRenderer-BYncw2H5.js +0 -2
- package/dist/assets/ToolOutputDialog-CA3uzAb9.js +0 -10
- package/dist/assets/main-RLZoG0Uv.js +0 -169
- package/dist/assets/miniChat-DBqehQQO.js +0 -2
- package/dist/assets/mobile-CZ_s2Xj0.js +0 -2
- package/dist/assets/runtime-auth-ef9W7A43.js +0 -1
- package/dist/assets/src-dSUmXLC4.css +0 -2
- package/dist/assets/types-CbUh5q3D.js +0 -2
- package/dist/assets/useWorkerHighlightedLines-BzXvnL_U.js +0 -7
- package/dist/assets/vendor-motion-DufQFNcM.js +0 -1
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { makeOpenCodeV2Client } from '../opencode/v2-client.js';
|
|
3
|
+
import { createOpenCodeContactToolGroups, createOpenCodeContactTools } from './opencode-tools.js';
|
|
4
|
+
import { runContactTurn } from './harness.js';
|
|
5
|
+
import { createYuriContactTools } from './yuri-tools.js';
|
|
6
|
+
|
|
7
|
+
const nativeCall = (name, args) => ({ completion: { choices: [{ message: { tool_calls: [{ id: `call_${name}`, type: 'function', function: { name, arguments: JSON.stringify(args) } }] } }] } });
|
|
8
|
+
|
|
9
|
+
const setup = (api, options = {}) => {
|
|
10
|
+
const resolveClient = vi.fn(() => api);
|
|
11
|
+
const tools = createOpenCodeContactTools({ resolveClient, directory: '/workspace', ...options });
|
|
12
|
+
return { tools, resolveClient, call: (name, params = {}, signal) => tools.find((tool) => tool.name === name).execute('probe', params, signal) };
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
describe('direct OpenCode contact tools', () => {
|
|
16
|
+
it('describes three deferred groups using existing tool objects without resolving a client or reading skills', () => {
|
|
17
|
+
const { tools, resolveClient } = setup({});
|
|
18
|
+
const groups = createOpenCodeContactToolGroups(tools);
|
|
19
|
+
expect(groups.map(({ id, tools: members }) => ({ id, names: members.map((tool) => tool.name) }))).toEqual([
|
|
20
|
+
{ id: 'opencode.web', names: ['list_websearch_providers', 'websearch'] },
|
|
21
|
+
{ id: 'opencode.activity', names: ['list_active_sessions'] },
|
|
22
|
+
{ id: 'opencode.catalog', names: ['list_opencode_capabilities', 'read_opencode_skill'] },
|
|
23
|
+
]);
|
|
24
|
+
for (const group of groups) {
|
|
25
|
+
for (const tool of group.tools) expect(tool).toBe(tools.find((original) => original.name === tool.name));
|
|
26
|
+
}
|
|
27
|
+
expect(groups.flatMap((group) => group.tools)).toHaveLength(tools.length);
|
|
28
|
+
expect(resolveClient).not.toHaveBeenCalled();
|
|
29
|
+
expect(createOpenCodeContactToolGroups([])).toEqual([]);
|
|
30
|
+
expect(createOpenCodeContactToolGroups(tools.filter((tool) => tool.name === 'websearch')).map((group) => group.id)).toEqual(['opencode.web']);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('executes a search through the official authenticated SDK with location and signal', async () => {
|
|
34
|
+
const fetchImpl = vi.fn(async (input, init) => {
|
|
35
|
+
const request = new Request(input, init);
|
|
36
|
+
expect(request.headers.get('authorization')).toBe('test-auth');
|
|
37
|
+
expect(new URL(request.url).origin).toBe('https://upstream.example.test');
|
|
38
|
+
expect(new URL(request.url).searchParams.get('location[directory]')).toBe('/workspace');
|
|
39
|
+
expect(await request.json()).toEqual({ query: 'site:github.com iOS client', providerID: 'exa' });
|
|
40
|
+
expect(request.signal).toBeInstanceOf(AbortSignal);
|
|
41
|
+
return Response.json({ location: { directory: '/workspace' }, data: { providerID: 'exa', results: [{ url: 'https://example.test/source', title: 'Source', content: 'Verified snippet', time: {} }] } });
|
|
42
|
+
});
|
|
43
|
+
const api = makeOpenCodeV2Client({ baseUrl: 'https://upstream.example.test', authHeaders: { authorization: 'test-auth' }, fetchImpl });
|
|
44
|
+
const { call } = setup(api);
|
|
45
|
+
const output = await call('websearch', { query: 'site:github.com iOS client', providerID: 'exa' });
|
|
46
|
+
expect(output.isError).not.toBe(true);
|
|
47
|
+
expect(output.details).toMatchObject({ providerID: 'exa', results: [{ title: 'Source', content: 'Verified snippet' }], partial: false });
|
|
48
|
+
expect(fetchImpl).toHaveBeenCalledTimes(1);
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
it('uses the current client on every call and does not replay a failed search', async () => {
|
|
52
|
+
const first = { websearch: { query: vi.fn().mockRejectedValue({ status: 503, message: 'private upstream body', headers: { authorization: 'private' } }) } };
|
|
53
|
+
const second = { websearch: { query: vi.fn().mockResolvedValue({ data: { providerID: 'exa', results: [] } }) } };
|
|
54
|
+
let current = first;
|
|
55
|
+
const tools = createOpenCodeContactTools({ resolveClient: () => current });
|
|
56
|
+
const search = tools.find((tool) => tool.name === 'websearch');
|
|
57
|
+
const failed = await search.execute('one', { query: 'research' });
|
|
58
|
+
expect(failed).toMatchObject({ isError: true, details: { error: 'opencode_failed', status: 503 }, terminate: false });
|
|
59
|
+
expect(JSON.stringify(failed)).not.toContain('private');
|
|
60
|
+
expect(first.websearch.query).toHaveBeenCalledTimes(1);
|
|
61
|
+
current = second;
|
|
62
|
+
expect((await search.execute('two', { query: 'research', providerID: 'exa' })).details.results).toEqual([]);
|
|
63
|
+
expect(second.websearch.query).toHaveBeenCalledTimes(1);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it.each([
|
|
67
|
+
[401, 'UnauthorizedError', 'authentication_required', /authentication|sign.in/i],
|
|
68
|
+
[403, 'ForbiddenError', 'permission_denied', /permission|access/i],
|
|
69
|
+
[503, 'ServiceUnavailableError', 'opencode_failed', /retry/i],
|
|
70
|
+
])('preserves SDK failure %s without exposing its private body', async (status, tag, category, guidance) => {
|
|
71
|
+
const fetchImpl = vi.fn(async () => Response.json({ _tag: tag, message: 'PRIVATE_SENTINEL', headers: { authorization: 'PRIVATE_SENTINEL' } }, { status }));
|
|
72
|
+
const api = makeOpenCodeV2Client({ baseUrl: 'https://upstream.example.test', fetchImpl });
|
|
73
|
+
const { call } = setup(api);
|
|
74
|
+
const output = await call('websearch', { query: 'research' });
|
|
75
|
+
expect(output).toMatchObject({ isError: true, details: { error: category, status } });
|
|
76
|
+
const visible = JSON.parse(output.content[0].text);
|
|
77
|
+
expect(visible).toMatchObject({ error: category, status, message: expect.stringMatching(guidance) });
|
|
78
|
+
if (status === 503) expect(visible.message).toMatch(/list_websearch_providers before.*retry/);
|
|
79
|
+
expect(JSON.stringify(output)).not.toContain('PRIVATE_SENTINEL');
|
|
80
|
+
expect(fetchImpl).toHaveBeenCalledTimes(1);
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it.each([
|
|
84
|
+
{ status: 401 }, { cause: { status: 401 } },
|
|
85
|
+
])('classifies status-only authentication errors as well as SDK tags (%j)', async (error) => {
|
|
86
|
+
const { call } = setup({ websearch: { query: async () => { throw error; } } });
|
|
87
|
+
expect(await call('websearch', { query: 'research' })).toMatchObject({ isError: true, details: { error: 'authentication_required', status: 401 } });
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it.each(['authentication', 'timeout'])('delivers %s failure and safe guidance to the model through the real Agent', async (scenario) => {
|
|
91
|
+
const fetchImpl = vi.fn(async () => scenario === 'authentication'
|
|
92
|
+
? Response.json({ _tag: 'UnauthorizedError', message: 'PRIVATE_SENTINEL' }, { status: 401 })
|
|
93
|
+
: new Promise(() => {}));
|
|
94
|
+
const api = makeOpenCodeV2Client({ baseUrl: 'https://upstream.example.test', fetchImpl });
|
|
95
|
+
const { tools } = setup(api, { timeoutMs: 20 });
|
|
96
|
+
let round = 0;
|
|
97
|
+
await runContactTurn({ assistant: { providerID: 'p', modelID: 'm' }, history: [], userText: 'Search once; if it times out, do not retry.', tools,
|
|
98
|
+
createChatCompletion: async ({ body }) => {
|
|
99
|
+
round++;
|
|
100
|
+
if (round === 1) return nativeCall('load_tools', { domain: 'opencode.web' });
|
|
101
|
+
if (round === 2) return nativeCall('websearch', { query: 'research' });
|
|
102
|
+
const message = body.messages.find((item) => item.role === 'tool' && item.tool_call_id === 'call_websearch');
|
|
103
|
+
const envelope = JSON.parse(message.content);
|
|
104
|
+
expect(envelope.isError).toBe(true);
|
|
105
|
+
const visible = JSON.parse(envelope.content);
|
|
106
|
+
expect(visible.error).toBe(scenario === 'authentication' ? 'authentication_required' : 'timeout');
|
|
107
|
+
expect(visible.message).toMatch(scenario === 'authentication' ? /authentication|sign.in/i : /timed out/i);
|
|
108
|
+
expect(visible.message).toMatch(scenario === 'authentication' ? /do not.*provider|do not.*switch/i : /user.*retry|retry.*user/i);
|
|
109
|
+
expect(message.content).not.toContain('PRIVATE_SENTINEL');
|
|
110
|
+
return { text: 'Failure acknowledged.' };
|
|
111
|
+
},
|
|
112
|
+
});
|
|
113
|
+
expect(round).toBe(3);
|
|
114
|
+
expect(fetchImpl).toHaveBeenCalledTimes(1);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it('bounds source excerpts and explicitly marks truncated results', async () => {
|
|
118
|
+
const { call } = setup({ websearch: { query: async () => ({ data: { providerID: 'exa', results: Array.from({ length: 12 }, (_, id) => ({ url: `https://example.test/${id}`, content: 'x'.repeat(4000) })) } }) } });
|
|
119
|
+
const output = await call('websearch', { query: 'research', limit: 2 });
|
|
120
|
+
expect(output.details).toMatchObject({ total: 12, partial: true });
|
|
121
|
+
expect(output.details.results).toHaveLength(2);
|
|
122
|
+
expect(output.details.results[0].content).toHaveLength(2000);
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it.each([null, { data: null }, { data: { providerID: 'exa', results: [{ url: 'file:///private/source' }] } }])('does not turn malformed search data into empty success', async (response) => {
|
|
126
|
+
const { call } = setup({ websearch: { query: async () => response } });
|
|
127
|
+
expect(await call('websearch', { query: 'research' })).toMatchObject({ isError: true, details: { error: 'opencode_failed' } });
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it('discovers providers without treating their catalog metadata as search results', async () => {
|
|
131
|
+
const { call } = setup({ websearch: { providers: async () => ({ data: [{ id: 'exa', name: 'Exa', secret: 'private' }] }) } });
|
|
132
|
+
expect((await call('list_websearch_providers')).details).toEqual({ providers: [{ id: 'exa', name: 'Exa' }] });
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it('uses authoritative live membership, not historical statuses, and paginates without identity sorting', async () => {
|
|
136
|
+
const active = vi.fn(async () => ({ ses_z: { type: 'running' }, ses_a: { type: 'running' } }));
|
|
137
|
+
const { call } = setup({ session: { active } });
|
|
138
|
+
const one = await call('list_active_sessions', { limit: 1 });
|
|
139
|
+
expect(one.details).toMatchObject({ items: [{ sessionID: 'ses_z', status: 'running' }], total: 2, nextOffset: 1, partial: true });
|
|
140
|
+
expect((await call('list_active_sessions', { limit: 1, offset: 1 })).details.items[0].sessionID).toBe('ses_a');
|
|
141
|
+
expect((await call('list_active_sessions', { sessionID: 'ses_missing' })).details.status).toBe('not_active');
|
|
142
|
+
expect((await call('list_active_sessions', { sessionID: 'ses_z' })).details.status).toBe('running');
|
|
143
|
+
active.mockResolvedValueOnce({});
|
|
144
|
+
expect((await call('list_active_sessions')).details).toMatchObject({ items: [], total: 0, partial: false });
|
|
145
|
+
active.mockRejectedValueOnce(new Error('network'));
|
|
146
|
+
expect(await call('list_active_sessions')).toMatchObject({ isError: true });
|
|
147
|
+
active.mockResolvedValueOnce({ error: 'invalid' });
|
|
148
|
+
expect(await call('list_active_sessions')).toMatchObject({ isError: true });
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
it('projects capability metadata without leaking agent prompts, request headers or MCP error bodies', async () => {
|
|
152
|
+
const { call } = setup({
|
|
153
|
+
agent: { list: async () => ({ data: [{ id: 'build', name: 'Build', description: 'Coding', system: 'private', request: { headers: { private: 'private' } } }, { id: 'hidden', hidden: true }] }) },
|
|
154
|
+
mcp: { list: async () => ({ data: [{ name: 'docs', status: { status: 'needs_auth', error: 'private body' } }] }) },
|
|
155
|
+
});
|
|
156
|
+
expect((await call('list_opencode_capabilities', { resource: 'agents' })).details.items).toEqual([{ id: 'build', name: 'Build', description: 'Coding' }]);
|
|
157
|
+
const output = await call('list_opencode_capabilities', { resource: 'mcp' });
|
|
158
|
+
expect(output.details.items).toEqual([{ id: 'docs', name: 'docs', description: '', status: 'needs_auth' }]);
|
|
159
|
+
expect(output.details.execution).toContain('assign_session');
|
|
160
|
+
expect(JSON.stringify(output)).not.toContain('private');
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it('reads built-in skills from API content, with bounded continuation, not their virtual file paths', async () => {
|
|
164
|
+
const { call } = setup({ skill: { list: async () => ({ data: [{ id: 'opencode', name: 'OpenCode', path: '/builtin/opencode.md', content: 'abcdef' }] }) } });
|
|
165
|
+
expect((await call('read_opencode_skill', { id: 'opencode', maxChars: 3 })).details).toEqual({ id: 'opencode', name: 'OpenCode', content: 'abc', nextOffset: 3, partial: true });
|
|
166
|
+
expect((await call('read_opencode_skill', { id: 'opencode', maxChars: 3, offset: 3 })).details).toMatchObject({ content: 'def', nextOffset: null, partial: false });
|
|
167
|
+
expect(await call('read_opencode_skill', { id: 'missing' })).toMatchObject({ isError: true, details: { error: 'validation_error' } });
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
it('validates arguments even when callers bypass the model schema', async () => {
|
|
171
|
+
const query = vi.fn();
|
|
172
|
+
const active = vi.fn(async () => ({}));
|
|
173
|
+
const { call } = setup({ websearch: { query }, session: { active } });
|
|
174
|
+
for (const params of [{ query: '' }, { query: 'x', limit: 11 }, { query: 'x', providerID: '' }]) {
|
|
175
|
+
expect(await call('websearch', params)).toMatchObject({ isError: true, details: { error: 'validation_error' } });
|
|
176
|
+
}
|
|
177
|
+
expect(query).not.toHaveBeenCalled();
|
|
178
|
+
expect(await call('list_opencode_capabilities', { resource: 'credentials' })).toMatchObject({ isError: true });
|
|
179
|
+
expect(await call('list_active_sessions', { offset: -1 })).toMatchObject({ isError: true });
|
|
180
|
+
expect(await call('list_active_sessions', { sessionID: 'a guessed title' })).toMatchObject({ isError: true, details: { error: 'validation_error' } });
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
it('propagates cancellation and bounds an uncooperative SDK request without retrying', async () => {
|
|
184
|
+
const query = vi.fn(() => new Promise(() => {}));
|
|
185
|
+
const { call } = setup({ websearch: { query } }, { timeoutMs: 15 });
|
|
186
|
+
const timeout = await call('websearch', { query: 'research' });
|
|
187
|
+
expect(timeout).toMatchObject({ isError: true, details: { error: 'timeout' } });
|
|
188
|
+
expect(query.mock.calls[0][1].signal.aborted).toBe(true);
|
|
189
|
+
expect(query).toHaveBeenCalledTimes(1);
|
|
190
|
+
const parent = new AbortController();
|
|
191
|
+
const pending = call('websearch', { query: 'research' }, parent.signal);
|
|
192
|
+
parent.abort(new Error('user cancelled'));
|
|
193
|
+
await expect(pending).rejects.toThrow('user cancelled');
|
|
194
|
+
expect(query).toHaveBeenCalledTimes(1);
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
it('executes native websearch calls through the real contact Agent and returns source evidence to the model', async () => {
|
|
198
|
+
const query = vi.fn(async () => ({ data: { providerID: 'exa', results: [{ url: 'https://example.test/repo', title: 'Found repository', content: 'Actual source content' }] } }));
|
|
199
|
+
const { tools } = setup({ websearch: { query } });
|
|
200
|
+
let round = 0;
|
|
201
|
+
const createChatCompletion = vi.fn(async ({ body }) => {
|
|
202
|
+
round++;
|
|
203
|
+
if (round === 1) {
|
|
204
|
+
expect(body.tools.map((tool) => tool.function.name)).toEqual(['load_tools', 'notify_user']);
|
|
205
|
+
expect(query).not.toHaveBeenCalled();
|
|
206
|
+
return { completion: { choices: [{ message: { tool_calls: [{ id: 'load-1', type: 'function', function: { name: 'load_tools', arguments: JSON.stringify({ domain: 'opencode.web' }) } }] } }] } };
|
|
207
|
+
}
|
|
208
|
+
expect(body.tools.map((tool) => tool.function.name)).toContain('websearch');
|
|
209
|
+
expect(body.tools.map((tool) => tool.function.name)).not.toContain('read_opencode_skill');
|
|
210
|
+
if (round === 2) return { completion: { choices: [{ message: { content: '', tool_calls: [{ id: 'search-1', type: 'function', function: { name: 'websearch', arguments: JSON.stringify({ query: 'site:github.com iOS', providerID: 'exa' }) } }] } }] } };
|
|
211
|
+
const evidence = body.messages.find((message) => message.role === 'tool' && message.tool_call_id === 'search-1');
|
|
212
|
+
expect(evidence.content).toContain('Actual source content');
|
|
213
|
+
expect(evidence.content).toContain('https://example.test/repo');
|
|
214
|
+
return { text: '找到了来源。' };
|
|
215
|
+
});
|
|
216
|
+
const output = await runContactTurn({ assistant: { providerID: 'p', modelID: 'm' }, history: [], userText: '帮我联网找一下', tools, createChatCompletion });
|
|
217
|
+
expect(output.bubbles).toEqual(['找到了来源。']);
|
|
218
|
+
expect(query).toHaveBeenCalledTimes(1);
|
|
219
|
+
expect(createChatCompletion).toHaveBeenCalledTimes(3);
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
it('does not offer the new execution tools to a read-only background review', async () => {
|
|
223
|
+
const { tools, resolveClient } = setup({});
|
|
224
|
+
await runContactTurn({ assistant: { providerID: 'p', modelID: 'm' }, history: [], userText: '后台复盘', tools, readOnly: true,
|
|
225
|
+
createChatCompletion: async ({ body }) => {
|
|
226
|
+
expect(body.tools).toEqual([]);
|
|
227
|
+
return { text: '结果已记录。' };
|
|
228
|
+
},
|
|
229
|
+
});
|
|
230
|
+
expect(resolveClient).not.toHaveBeenCalled();
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
it('uses one loader for Yuri and OpenCode, keeps unrelated groups hidden and resets both on the next contact turn', async () => {
|
|
234
|
+
const query = vi.fn(async () => ({ data: { providerID: 'exa', results: [] } }));
|
|
235
|
+
const list = vi.fn();
|
|
236
|
+
const { tools: openCodeTools } = setup({ websearch: { query }, skill: { list } });
|
|
237
|
+
const registerProject = vi.fn(async () => ({ project: { id: 'p', path: '/workspace' }, created: true }));
|
|
238
|
+
const tools = [...createYuriContactTools({ registerProject }), ...openCodeTools];
|
|
239
|
+
let round = 0;
|
|
240
|
+
const input = { assistant: { providerID: 'p', modelID: 'm' }, history: [], userText: 'Search, then register the requested project.', tools };
|
|
241
|
+
await runContactTurn({ ...input, createChatCompletion: async ({ body }) => {
|
|
242
|
+
round++;
|
|
243
|
+
const names = body.tools.map((item) => item.function.name);
|
|
244
|
+
expect(names.filter((name) => name.startsWith('load_'))).toEqual(['load_tools']);
|
|
245
|
+
expect(names).not.toContain('read_opencode_skill');
|
|
246
|
+
expect(names).not.toContain('list_active_sessions');
|
|
247
|
+
if (round === 1) {
|
|
248
|
+
expect(names).toEqual(['load_tools', 'notify_user']);
|
|
249
|
+
expect(body.tools[0].function.parameters.properties.domain.enum).toEqual(['yuri.projects', 'opencode.web', 'opencode.activity', 'opencode.catalog']);
|
|
250
|
+
return nativeCall('load_tools', { domain: 'opencode.web' });
|
|
251
|
+
}
|
|
252
|
+
if (round === 2) {
|
|
253
|
+
expect(names).not.toContain('register_project');
|
|
254
|
+
return nativeCall('websearch', { query: 'research' });
|
|
255
|
+
}
|
|
256
|
+
if (round === 3) return nativeCall('load_tools', { domain: 'yuri.projects' });
|
|
257
|
+
if (round === 4) {
|
|
258
|
+
expect(names).toContain('websearch');
|
|
259
|
+
expect(names).toContain('register_project');
|
|
260
|
+
return nativeCall('register_project', { path: '/workspace' });
|
|
261
|
+
}
|
|
262
|
+
return { text: 'Done.' };
|
|
263
|
+
} });
|
|
264
|
+
expect(query).toHaveBeenCalledTimes(1);
|
|
265
|
+
expect(registerProject).toHaveBeenCalledTimes(1);
|
|
266
|
+
expect(list).not.toHaveBeenCalled();
|
|
267
|
+
await runContactTurn({ ...input, createChatCompletion: async ({ body }) => {
|
|
268
|
+
expect(body.tools.map((item) => item.function.name)).toEqual(['load_tools', 'notify_user']);
|
|
269
|
+
return { text: 'New turn.' };
|
|
270
|
+
} });
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
it.each([false, true])('rejects an unloaded OpenCode call before SDK execution (batched with loader=%s)', async (batched) => {
|
|
274
|
+
const query = vi.fn(async () => ({ data: { providerID: 'exa', results: [] } }));
|
|
275
|
+
const { tools } = setup({ websearch: { query } });
|
|
276
|
+
let round = 0;
|
|
277
|
+
await runContactTurn({ assistant: { providerID: 'p', modelID: 'm' }, history: [], userText: 'Search online.', tools,
|
|
278
|
+
createChatCompletion: async () => {
|
|
279
|
+
round++;
|
|
280
|
+
if (round === 1) {
|
|
281
|
+
const response = nativeCall('websearch', { query: 'research' });
|
|
282
|
+
if (batched) response.completion.choices[0].message.tool_calls.unshift(nativeCall('load_tools', { domain: 'opencode.web' }).completion.choices[0].message.tool_calls[0]);
|
|
283
|
+
return response;
|
|
284
|
+
}
|
|
285
|
+
if (round === 2) {
|
|
286
|
+
expect(query).not.toHaveBeenCalled();
|
|
287
|
+
return nativeCall('load_tools', { domain: 'opencode.web' });
|
|
288
|
+
}
|
|
289
|
+
if (round === 3) return nativeCall('websearch', { query: 'research' });
|
|
290
|
+
return { text: 'Searched.' };
|
|
291
|
+
},
|
|
292
|
+
});
|
|
293
|
+
expect(query).toHaveBeenCalledTimes(1);
|
|
294
|
+
});
|
|
295
|
+
});
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Turn-local disclosure of already-granted tools; business execution stays with each owner. */
|
|
2
|
+
export function createProgressiveTools({ tools, groups }) {
|
|
3
|
+
const granted = new Set(tools);
|
|
4
|
+
const available = groups.map((group) => ({ ...group, tools: group.tools.filter((tool) => granted.has(tool)) }))
|
|
5
|
+
.filter((group) => group.tools.length > 0);
|
|
6
|
+
const deferred = new Set(available.flatMap((group) => group.tools));
|
|
7
|
+
const active = tools.filter((tool) => !deferred.has(tool));
|
|
8
|
+
if (available.length === 0) return { getTools: () => [...active] };
|
|
9
|
+
const loaded = new Set();
|
|
10
|
+
const result = (details, isError = false) => ({
|
|
11
|
+
content: [{ type: 'text', text: JSON.stringify(details) }], details, isError, terminate: false,
|
|
12
|
+
});
|
|
13
|
+
active.push({
|
|
14
|
+
name: 'load_tools', label: 'Load tools',
|
|
15
|
+
description: `Load a capability group for this assistant turn only, then call its tools in the next response. ${available.map(({ id, description }) => `${id}: ${description}`).join(' ')}`,
|
|
16
|
+
parameters: { type: 'object', additionalProperties: false, required: ['domain'], properties: {
|
|
17
|
+
domain: { type: 'string', enum: available.map((group) => group.id) },
|
|
18
|
+
} },
|
|
19
|
+
execute: async (_id, params, signal) => {
|
|
20
|
+
signal?.throwIfAborted();
|
|
21
|
+
const group = params && !Array.isArray(params) && Object.keys(params).length === 1
|
|
22
|
+
&& available.find((entry) => entry.id === params.domain);
|
|
23
|
+
if (!group) return result({ error: 'validation_error' }, true);
|
|
24
|
+
const alreadyLoaded = loaded.has(group.id);
|
|
25
|
+
const added = alreadyLoaded ? [] : group.tools.filter((tool) => !active.includes(tool));
|
|
26
|
+
loaded.add(group.id);
|
|
27
|
+
active.push(...added);
|
|
28
|
+
return { ...result({ domain: group.id, tools: group.tools.map((tool) => tool.name), alreadyLoaded }),
|
|
29
|
+
addedToolNames: added.map((tool) => tool.name) };
|
|
30
|
+
},
|
|
31
|
+
});
|
|
32
|
+
return { getTools: () => [...active] };
|
|
33
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { createProgressiveTools } from './progressive-tools.js';
|
|
3
|
+
|
|
4
|
+
const tool = (name) => ({ name, description: `${name} operation`, parameters: { type: 'object', properties: {} }, execute: vi.fn() });
|
|
5
|
+
|
|
6
|
+
describe('shared progressive tool disclosure', () => {
|
|
7
|
+
it('keeps base tools visible and only exposes granted group members without calling their executors', async () => {
|
|
8
|
+
const base = tool('read');
|
|
9
|
+
const granted = tool('search');
|
|
10
|
+
const forbidden = tool('delete');
|
|
11
|
+
const tools = [base, granted];
|
|
12
|
+
const progressive = createProgressiveTools({ tools, groups: [
|
|
13
|
+
{ id: 'external.web', description: 'Search online.', tools: [granted, forbidden] },
|
|
14
|
+
{ id: 'unavailable', description: 'Not granted.', tools: [forbidden] },
|
|
15
|
+
] });
|
|
16
|
+
const initial = progressive.getTools();
|
|
17
|
+
expect(initial.map((item) => item.name)).toEqual(['read', 'load_tools']);
|
|
18
|
+
const loader = initial[1];
|
|
19
|
+
expect(loader.parameters.properties.domain.enum).toEqual(['external.web']);
|
|
20
|
+
expect(JSON.stringify(loader)).not.toContain('search operation');
|
|
21
|
+
const result = await loader.execute('load', { domain: 'external.web' });
|
|
22
|
+
expect(result.addedToolNames).toEqual(['search']);
|
|
23
|
+
expect(progressive.getTools()).toEqual([base, loader, granted]);
|
|
24
|
+
for (const item of [base, granted, forbidden]) expect(item.execute).not.toHaveBeenCalled();
|
|
25
|
+
expect(tools).toEqual([base, granted]);
|
|
26
|
+
initial.length = 0;
|
|
27
|
+
expect(progressive.getTools()).toHaveLength(3);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it('isolates concurrently alive turn states and deduplicates repeat or overlapping group loads', async () => {
|
|
31
|
+
const shared = tool('shared');
|
|
32
|
+
const extra = tool('extra');
|
|
33
|
+
const options = { tools: [shared, extra], groups: [
|
|
34
|
+
{ id: 'first', description: 'First.', tools: [shared] },
|
|
35
|
+
{ id: 'second', description: 'Second.', tools: [shared, extra] },
|
|
36
|
+
] };
|
|
37
|
+
const first = createProgressiveTools(options);
|
|
38
|
+
const otherTurn = createProgressiveTools(options);
|
|
39
|
+
const loader = first.getTools()[0];
|
|
40
|
+
const results = await Promise.all([
|
|
41
|
+
loader.execute('one', { domain: 'first' }), loader.execute('two', { domain: 'second' }),
|
|
42
|
+
loader.execute('again', { domain: 'first' }),
|
|
43
|
+
]);
|
|
44
|
+
expect(results.map((item) => item.addedToolNames)).toEqual([['shared'], ['extra'], []]);
|
|
45
|
+
expect(results[2].details.alreadyLoaded).toBe(true);
|
|
46
|
+
expect(first.getTools().map((item) => item.name)).toEqual(['load_tools', 'shared', 'extra']);
|
|
47
|
+
expect(otherTurn.getTools().map((item) => item.name)).toEqual(['load_tools']);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('does not add an entrypoint without an available deferred group', () => {
|
|
51
|
+
const base = tool('read');
|
|
52
|
+
expect(createProgressiveTools({ tools: [base], groups: [] }).getTools()).toEqual([base]);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('does not activate any group after cancellation or an invalid load', async () => {
|
|
56
|
+
const member = tool('operation');
|
|
57
|
+
const progressive = createProgressiveTools({ tools: [member], groups: [{ id: 'group', description: 'Example.', tools: [member] }] });
|
|
58
|
+
const loader = progressive.getTools()[0];
|
|
59
|
+
for (const params of [null, [], {}, { domain: 'unknown' }, { domain: 'group', extra: true }]) {
|
|
60
|
+
expect((await loader.execute('bad', params)).isError).toBe(true);
|
|
61
|
+
}
|
|
62
|
+
const controller = new AbortController(); controller.abort(new Error('cancelled'));
|
|
63
|
+
await expect(loader.execute('cancelled', { domain: 'group' }, controller.signal)).rejects.toThrow('cancelled');
|
|
64
|
+
expect(progressive.getTools()).toEqual([loader]);
|
|
65
|
+
});
|
|
66
|
+
});
|
|
@@ -29,6 +29,7 @@ export const registerAssistantRoutes = (app, dependencies) => {
|
|
|
29
29
|
getServerId: dependencies.getServerId,
|
|
30
30
|
getAllowedRoots: dependencies.getAllowedRoots,
|
|
31
31
|
listProjects: dependencies.listProjects,
|
|
32
|
+
registerProject: dependencies.registerProject,
|
|
32
33
|
readModelPreferences: dependencies.readModelPreferences,
|
|
33
34
|
listScheduledTasks: dependencies.listScheduledTasks,
|
|
34
35
|
sessionIndexService: dependencies.sessionIndexService,
|
|
@@ -5,6 +5,7 @@ import path from 'node:path';
|
|
|
5
5
|
import { makeOpenCodeV2Client } from '../opencode/v2-client.js';
|
|
6
6
|
import { validAssistantDeliveryParts } from '../assistant-delivery-parts.js';
|
|
7
7
|
import { createContactMemoryReader } from './memory.js';
|
|
8
|
+
import { getContactGreeting } from './contact-greeting.js';
|
|
8
9
|
import { getWorktrees as defaultListWorktrees } from '../git/service.js';
|
|
9
10
|
import { contactCardIdentity, parseContactCard, parseContactPart } from './cards.js';
|
|
10
11
|
import {
|
|
@@ -70,6 +71,7 @@ import {
|
|
|
70
71
|
extractSessionDirectory,
|
|
71
72
|
extractSessionTitle,
|
|
72
73
|
hasAssignImageParts,
|
|
74
|
+
isManagedAssistantWorkspace,
|
|
73
75
|
mapSessionToWatchStatus,
|
|
74
76
|
resolveAssignDirectory,
|
|
75
77
|
extractAssignSessionModel,
|
|
@@ -77,6 +79,9 @@ import {
|
|
|
77
79
|
sanitizeAssignFileParts,
|
|
78
80
|
} from './assign.js';
|
|
79
81
|
import { runContactTurn as defaultRunContactTurn } from './harness.js';
|
|
82
|
+
import { createOpenCodeContactTools } from './opencode-tools.js';
|
|
83
|
+
import { createYuriContactTools } from './yuri-tools.js';
|
|
84
|
+
import { resolveAssistantCwd } from './pi-tools.js';
|
|
80
85
|
import { loadConnectedCatalog, parseModelRef } from '../llm/catalog.js';
|
|
81
86
|
import { buildAssistantSessionMetadata } from '../session-metadata/system-session.js';
|
|
82
87
|
|
|
@@ -109,6 +114,11 @@ const json = (value) => JSON.stringify(value);
|
|
|
109
114
|
const parse = (value) => JSON.parse(value);
|
|
110
115
|
const hash = (value) => crypto.createHash('sha256').update(json(value)).digest('hex');
|
|
111
116
|
const id = () => crypto.randomUUID();
|
|
117
|
+
// Plain-Node mirror of the shared UI recipe catalog; service tests enforce parity.
|
|
118
|
+
const AVATAR_COLORS = ['mint', 'orange', 'iris', 'jade', 'coral', 'blue', 'sky', 'violet', 'sand', 'rose', 'cyan', 'graphite'];
|
|
119
|
+
const RANDOM_AVATAR_SHAPES = ['round', 'soft', 'tall', 'wide', 'compact', 'large', 'drop'];
|
|
120
|
+
const randomAvatarSeed = (nonce, shape = RANDOM_AVATAR_SHAPES[crypto.randomInt(RANDOM_AVATAR_SHAPES.length)]) =>
|
|
121
|
+
`yuri-avatar:v1:${shape}:capsule:${AVATAR_COLORS[crypto.randomInt(AVATAR_COLORS.length)]}:neutral:1:${nonce}`;
|
|
112
122
|
export class AssistantError extends Error {
|
|
113
123
|
constructor(code, message) {
|
|
114
124
|
super(typeof message === 'string' && message.trim() ? message.trim() : code);
|
|
@@ -237,7 +247,7 @@ const awaitWithDeadline = async (work, ms = CONTACT_CATALOG_DEADLINE_MS, code =
|
|
|
237
247
|
}
|
|
238
248
|
};
|
|
239
249
|
|
|
240
|
-
export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, getOpenCodeAuthHeaders, getServerId = async () => null, getAllowedRoots = () => [], listProjects = async () => [], readModelPreferences = async () => null, listScheduledTasks = null, sessionIndexService = null, upsertScheduledTask = null, patchScheduledTask = null, syncScheduledTaskProject = null, globalEventHub = null, onRevisionTip = null, onContactTurnEvent = null, onContactTurnComplete = null, /** Host archive op: ({ sessionID, directory, archivedAt }) => Promise */ archiveSessionHost = null, /** Idempotent Host metadata drop after successful SDK delete */ forgetSessionHost = null, /** Host store write: (sessionId, patch) => Promise */ persistSessionMetadata = null, /** After Host isolation metadata is committed. */ onSystemSessionPersisted = null, clock = () => Date.now(), setIntervalFn = setInterval, clearIntervalFn = clearInterval, setImmediateFn = setImmediate, reconcileIntervalMs = 60_000, clientFactory, fetchImpl, createChatCompletion = null, runContactTurn = defaultRunContactTurn, listWorktrees = defaultListWorktrees } = {}) => {
|
|
250
|
+
export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, getOpenCodeAuthHeaders, getServerId = async () => null, getAllowedRoots = () => [], listProjects = async () => [], registerProject = null, readModelPreferences = async () => null, listScheduledTasks = null, sessionIndexService = null, upsertScheduledTask = null, patchScheduledTask = null, syncScheduledTaskProject = null, globalEventHub = null, onRevisionTip = null, onContactTurnEvent = null, onContactTurnComplete = null, /** Host archive op: ({ sessionID, directory, archivedAt }) => Promise */ archiveSessionHost = null, /** Idempotent Host metadata drop after successful SDK delete */ forgetSessionHost = null, /** Host store write: (sessionId, patch) => Promise */ persistSessionMetadata = null, /** After Host isolation metadata is committed. */ onSystemSessionPersisted = null, clock = () => Date.now(), setIntervalFn = setInterval, clearIntervalFn = clearInterval, setImmediateFn = setImmediate, reconcileIntervalMs = 60_000, clientFactory, fetchImpl, createChatCompletion = null, runContactTurn = defaultRunContactTurn, listWorktrees = defaultListWorktrees } = {}) => {
|
|
241
251
|
if (!dbPath || !dataDir) return null;
|
|
242
252
|
const Database = require('better-sqlite3');
|
|
243
253
|
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
|
@@ -1307,7 +1317,7 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
|
|
|
1307
1317
|
};
|
|
1308
1318
|
const unsubscribeEvents = typeof globalEventHub?.subscribeEvent === 'function' ? globalEventHub.subscribeEvent(processEvent) : null;
|
|
1309
1319
|
const updateContactAvatar = async (assistantID, seed) => {
|
|
1310
|
-
const avatarSeed = seed === undefined ? id() : string(seed, 256, true);
|
|
1320
|
+
const avatarSeed = seed === undefined ? randomAvatarSeed(id()) : string(seed, 256, true);
|
|
1311
1321
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
1312
1322
|
const current = output(editable(assistantID));
|
|
1313
1323
|
if (current.avatarSeed === avatarSeed) return { updated: false, avatarSeed, previousAvatarSeed: current.avatarSeed };
|
|
@@ -1320,8 +1330,9 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
|
|
|
1320
1330
|
}
|
|
1321
1331
|
};
|
|
1322
1332
|
const createAssistant = (input, { onlyIfEmpty = false } = {}) => {
|
|
1323
|
-
const allowed = new Set(['enabled', 'name', 'avatarSeed', 'defaultPrompt', 'providerID', 'modelID', 'agent', 'variant', 'mode', 'workspacePath']);
|
|
1333
|
+
const allowed = new Set(['enabled', 'name', 'avatarSeed', 'defaultPrompt', 'providerID', 'modelID', 'agent', 'variant', 'mode', 'workspacePath', 'language']);
|
|
1324
1334
|
if (!plainObject(input) || Object.keys(input).some((key) => !allowed.has(key))) fail('validation_error');
|
|
1335
|
+
const language = input.language == null ? 'en' : string(input.language, 64, true);
|
|
1325
1336
|
const mode = input.mode == null ? 'continuous' : input.mode === 'stateless' || input.mode === 'continuous' ? input.mode : fail('validation_error');
|
|
1326
1337
|
const assistantID = id();
|
|
1327
1338
|
const workspacePath = input.workspacePath == null ? null : workspace(input.workspacePath, assistantID);
|
|
@@ -1338,9 +1349,15 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
|
|
|
1338
1349
|
// Default every creation channel to the same face, varying only pigment.
|
|
1339
1350
|
// Persist the complete v1 recipe so future defaults cannot change this Bot.
|
|
1340
1351
|
const avatarSeed = input.avatarSeed === undefined
|
|
1341
|
-
?
|
|
1352
|
+
? randomAvatarSeed(assistantID, 'round')
|
|
1342
1353
|
: string(input.avatarSeed, 256, true);
|
|
1343
1354
|
db.prepare('INSERT INTO assistant_v2 (assistant_id,revision,enabled,name,default_prompt,workspace_path,provider_id,model_id,agent,variant,mode,current_session_id,session_generation,created_at,updated_at,tombstone_at,avatar_seed) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)').run(assistantID, 1, input.enabled === false ? 0 : 1, string(input.name, 256, true), input.defaultPrompt ? string(input.defaultPrompt, 200_000) : '', workspacePath, string(input.providerID, 256, true), string(input.modelID, 256, true), input.agent == null ? null : string(input.agent, 256), input.variant == null ? null : string(input.variant, 256), mode, null, 0, at, at, null, avatarSeed);
|
|
1355
|
+
insertContactMessage(db, {
|
|
1356
|
+
messageID: `${assistantID}:greeting`, assistantID, role: 'assistant',
|
|
1357
|
+
turnID: `${assistantID}:greeting`, bubbleIndex: 0, createdAt: at,
|
|
1358
|
+
ordinal: nextContactOrdinal(db, assistantID), status: 'complete',
|
|
1359
|
+
parts: [{ type: 'text', text: getContactGreeting(assistant(assistantID).name, language) }],
|
|
1360
|
+
});
|
|
1344
1361
|
bump();
|
|
1345
1362
|
db.exec('COMMIT');
|
|
1346
1363
|
return output(assistant(assistantID));
|
|
@@ -2931,7 +2948,7 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
|
|
|
2931
2948
|
steerSession: (params) => mutateSessionWork('steer', params),
|
|
2932
2949
|
archiveSession: (params) => mutateSessionWork('archive', params),
|
|
2933
2950
|
deleteSession: (params) => mutateSessionWork('delete', params),
|
|
2934
|
-
|
|
2951
|
+
createAssistant: (toolInput) => createAssistant({ ...toolInput, avatarSeed: randomAvatarSeed(id()), language: contactTurnLanguages.get(assistantID) || 'en' }),
|
|
2935
2952
|
scheduleTask: (params) => scheduleWork(live, params),
|
|
2936
2953
|
listScheduledTasks: (params) => listScheduledTaskWork(params),
|
|
2937
2954
|
updateScheduledTask: (params) => updateScheduledTaskWork(live, params, controller.signal),
|
|
@@ -3290,7 +3307,7 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
|
|
|
3290
3307
|
steerSession: (params) => mutateSessionWork('steer', params),
|
|
3291
3308
|
archiveSession: (params) => mutateSessionWork('archive', params),
|
|
3292
3309
|
deleteSession: (params) => mutateSessionWork('delete', params),
|
|
3293
|
-
|
|
3310
|
+
createAssistant: (toolInput) => createAssistant({ ...toolInput, avatarSeed: randomAvatarSeed(id()), language: language || 'en' }),
|
|
3294
3311
|
scheduleTask: (params) => scheduleWork(row, params),
|
|
3295
3312
|
listScheduledTasks: (params) => listScheduledTaskWork(params),
|
|
3296
3313
|
updateScheduledTask: (params) => updateScheduledTaskWork(row, params, controller.signal),
|
|
@@ -3380,6 +3397,19 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
|
|
|
3380
3397
|
turnFileParts,
|
|
3381
3398
|
turnAttachmentScope,
|
|
3382
3399
|
});
|
|
3400
|
+
tools.push(...createYuriContactTools({
|
|
3401
|
+
registerProject: typeof registerProject === 'function' ? async (input, signal) => {
|
|
3402
|
+
signal?.throwIfAborted();
|
|
3403
|
+
if (!path.isAbsolute(input.path)) {
|
|
3404
|
+
throw new AssignError(ASSIGN_CODES.WORKSPACE_FORBIDDEN, 'Choose an existing absolute workspace outside assistant-workspaces.');
|
|
3405
|
+
}
|
|
3406
|
+
const directory = fs.realpathSync(input.path);
|
|
3407
|
+
if (isManagedAssistantWorkspace(directory, path.resolve(dataDir, 'assistant-workspaces'))) {
|
|
3408
|
+
throw new AssignError(ASSIGN_CODES.WORKSPACE_FORBIDDEN, 'Choose an existing workspace outside assistant-workspaces.');
|
|
3409
|
+
}
|
|
3410
|
+
return registerProject({ ...input, path: directory });
|
|
3411
|
+
} : null,
|
|
3412
|
+
}));
|
|
3383
3413
|
controller.signal.throwIfAborted();
|
|
3384
3414
|
const generated = await runContactTurn({
|
|
3385
3415
|
signal: controller.signal,
|
|
@@ -3389,7 +3419,7 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
|
|
|
3389
3419
|
userParts: executionParts,
|
|
3390
3420
|
language,
|
|
3391
3421
|
createChatCompletion,
|
|
3392
|
-
tools,
|
|
3422
|
+
tools: [...tools, ...createOpenCodeContactTools({ resolveClient: client, directory: resolveAssistantCwd(assistantSnapshot) })],
|
|
3393
3423
|
projects: registeredProjects,
|
|
3394
3424
|
...modelContext,
|
|
3395
3425
|
globalEventHub,
|
|
@@ -3847,7 +3877,7 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
|
|
|
3847
3877
|
)),
|
|
3848
3878
|
};
|
|
3849
3879
|
};
|
|
3850
|
-
|
|
3880
|
+
const removeAssistant = (assistantID, expectedRevision) => {
|
|
3851
3881
|
db.exec('BEGIN IMMEDIATE');
|
|
3852
3882
|
try {
|
|
3853
3883
|
const result = db.prepare('UPDATE assistant_v2 SET tombstone_at=?,revision=revision+1,updated_at=? WHERE assistant_id=? AND revision=? AND tombstone_at IS NULL').run(now(), now(), assistantID, expectedRevision);
|
|
@@ -3869,7 +3899,8 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
|
|
|
3869
3899
|
db.exec('ROLLBACK');
|
|
3870
3900
|
throw error;
|
|
3871
3901
|
}
|
|
3872
|
-
}
|
|
3902
|
+
};
|
|
3903
|
+
return { capability: async () => ({ supported: true, enabled: enabled(), revision: revision(), serverInstanceID: await getServerId(), sharingAvailable: false, archiveMetadataAvailable: typeof archiveSessionHost === 'function', sessionMetadataAvailable: false }), snapshot, ensureDefaultAssistant, createAssistant, updateAssistant, setEnabled: (input) => { if (!plainObject(input) || typeof input.enabled !== 'boolean' || input.expectedRevision !== revision()) fail('revision_conflict'); return { enabled: true, revision: revision() }; }, removeAssistant, ensure, createNew, compact, send, whenContactTurnSettled, abort, captureQueueDeliveryTarget, sendWithCapturedConfig, share, shareOperation, historicalMessages, contactMessages, clearContactMemory, resetContact, markContactRead, appendContactCard, deliverPeerMessage, listAssistantScheduledTasks, reportScheduledTaskResult, putAssistantContactAttachment, getAssistantContactAttachment, migrateContactAttachments, processEvent, reportAssignedSessionSettle: reportAssignedSession, reconcile, close: () => {
|
|
3873
3904
|
cancelAssignedResumes({});
|
|
3874
3905
|
sessionAbortInflight.clear();
|
|
3875
3906
|
pendingAssignMessageIDs.clear();
|