@yuriai/web 0.2.19 → 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-HNaj_sVG.js → DiagramView-DWV04Xws.js} +1 -1
- package/dist/assets/{FadeInOnReveal-Dq1IuEQp.js → FadeInOnReveal-CdoLG8fY.js} +1 -1
- package/dist/assets/{GuiPluginSurface-N-iK-MeX.js → GuiPluginSurface-DhD8BqvL.js} +1 -1
- package/dist/assets/{GuiPluginWindow-ClutFX_h.js → GuiPluginWindow-ezsy5l_y.js} +1 -1
- package/dist/assets/{Icon-tnX3bel1.js → Icon-DvqOB4Dx.js} +1 -1
- package/dist/assets/{ImageLoadingPlaceholder-IE6JO3WM.js → ImageLoadingPlaceholder-BVlgaa2r.js} +1 -1
- package/dist/assets/{LoadingImage-DNZmZRZS.js → LoadingImage-BSG8jmn5.js} +1 -1
- package/dist/assets/MarkdownRenderer-BiRplAST.js +2 -0
- package/dist/assets/{MarkdownRendererImpl-BwZ91PA5.js → MarkdownRendererImpl-CH8TUMKZ.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-kgBwH_VF.js → MarkstreamRendererImpl-Bmz56IzM.js} +1 -1
- package/dist/assets/{MobileDetailNavigation-sm5MbnK3.js → MobileDetailNavigation-kKHM_dU3.js} +1 -1
- package/dist/assets/{MobileResizableSheet-Cw6rRBR2.js → MobileResizableSheet-jHNytoyX.js} +1 -1
- package/dist/assets/{MobileShareBridge-BjpB1cz1.js → MobileShareBridge-CSDivsPk.js} +2 -2
- package/dist/assets/{MobileTabPageHeader-CEsc9PYV.js → MobileTabPageHeader-BkWvNBtr.js} +1 -1
- package/dist/assets/{MultiRunWindow-pslncrAh.js → MultiRunWindow-DbllgaJR.js} +1 -1
- package/dist/assets/{OnboardingScreen-o9e7j2Lk.js → OnboardingScreen-DONIcirJ.js} +1 -1
- package/dist/assets/{OverlayScrollbar-BA6KEyhj.js → OverlayScrollbar-DB2eeXFh.js} +1 -1
- package/dist/assets/{SettingsView-20rmUHhk.js → SettingsView-6D55BNjw.js} +1 -1
- package/dist/assets/{SettingsWindow-D-Vjsme7.js → SettingsWindow-BrrnHfnR.js} +1 -1
- package/dist/assets/{TerminalView-B4bliT5i.js → TerminalView-8JYW5f-c.js} +1 -1
- package/dist/assets/{ToolOutputDialog-D1rZbaHo.js → ToolOutputDialog-DZO89hKv.js} +1 -1
- package/dist/assets/{YuriLogo-CDmH1ycw.js → YuriLogo-CYdRUurL.js} +1 -1
- package/dist/assets/{appThemeRegistry-DyTPt9Uq.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-BEOJB042.js → button-nola46HU.js} +1 -1
- package/dist/assets/{capgoAdapter-BrU-ms8F.js → capgoAdapter-CHeo9q51.js} +1 -1
- package/dist/assets/{collapsible-DrQlDm15.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-DyQPPDKS.js → diagram-COti_aKS.js} +1 -1
- package/dist/assets/{dialog-CooVl0xA.js → dialog-B2CTTXwv.js} +1 -1
- package/dist/assets/{dropdown-menu.styles-Bj4YEb3T.js → dropdown-menu.styles-BzpQaok_.js} +1 -1
- package/dist/assets/{fileMentionTouchSelection-8I9u8H6l.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/{gitApi-BVMvxPtG.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-B-4VixoV.js → input-DGnhaqoc.js} +1 -1
- package/dist/assets/{insertionBoundaries-YVc2e3H2.js → insertionBoundaries-Db0R1aBj.js} +1 -1
- package/dist/assets/{main-Cs5VJerX.js → main-DQ0F0yuL.js} +21 -21
- package/dist/assets/{main-DZ5HVH-j.js → main-d2AaD_PZ.js} +2 -2
- package/dist/assets/{markdownHeightCache-SdaL8x58.js → markdownHeightCache-C_JI5qIR.js} +1 -1
- package/dist/assets/{mcpQueries-B1ZULr7c.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-D-cRdrKd.js → mobileBackNavigation-s9RsXUUH.js} +1 -1
- package/dist/assets/{multirun-D6bNScic.js → multirun-BZsBsBAj.js} +1 -1
- package/dist/assets/{native-config-obwt8WA1.js → native-config-BmrfOzkM.js} +1 -1
- package/dist/assets/{persistence-BfjCXjLZ.js → persistence-CNEHspb4.js} +1 -1
- package/dist/assets/{platform-syRnKuVU.js → platform-Q45KPuGv.js} +1 -1
- package/dist/assets/{projectMeta-LtQkG8fN.js → projectMeta-BCGIXTbR.js} +1 -1
- package/dist/assets/{queryRuntime-BuRnpVtK.js → queryRuntime-DWgXfxGx.js} +1 -1
- package/dist/assets/{readiness-BWBtf7Am.js → readiness-BxT5OBkk.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-EL2J2wQd.js → renderElectronMiniChatApp-BbfF6SjM.js} +2 -2
- package/dist/assets/{renderMobileApp-DOCWKmuC.js → renderMobileApp-ulSQxT-l.js} +4 -4
- 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-D577Rc9x.js → runtimeConfig-BHRHZbwI.js} +1 -1
- package/dist/assets/{runtimeEndpointReset-C5EiiaQf.js → runtimeEndpointReset-H2W1kxcO.js} +3 -3
- package/dist/assets/{scheduledTaskNavigation-CJEzv5Zr.js → scheduledTaskNavigation-CkBcoGV4.js} +1 -1
- package/dist/assets/{sessionChangeSummary-DAV313F8.js → sessionChangeSummary-CAU-06Bu.js} +1 -1
- package/dist/assets/{sessionLookup-CN_iYfk5.js → sessionLookup-YvkfClst.js} +1 -1
- package/dist/assets/{sortable-tabs-strip-9okrTn1K.js → sortable-tabs-strip-pCvZjmMt.js} +1 -1
- package/dist/assets/{speechSettingsQueries-BvJCYdR_.js → speechSettingsQueries-1LD5eEHK.js} +2 -2
- package/dist/assets/{src-nJdn6EvY.css → src-DGCTlpkW.css} +1 -1
- package/dist/assets/{terminalApi-Dw1h9m3h.js → terminalApi-DFhCeMya.js} +1 -1
- package/dist/assets/{textarea-9sBs8Uld.js → textarea-DSHEMw8t.js} +1 -1
- package/dist/assets/{tooltip-BkcQKx-p.js → tooltip-BwTvgqWG.js} +1 -1
- package/dist/assets/types-CiQgQf3s.js +2 -0
- package/dist/assets/{useAppFontEffects-D9c0mG1P.js → useAppFontEffects-Cz9eoInx.js} +9 -9
- package/dist/assets/{useAssistantUIStore-rdsbsVts.js → useAssistantUIStore-BZt-lLlW.js} +1 -1
- package/dist/assets/{useDesktopWindowControlsLayout-Dx-zWLPl.js → useDesktopWindowControlsLayout-HpOlTBoV.js} +1 -1
- package/dist/assets/{useEffectiveDirectory-DPvKdopQ.js → useEffectiveDirectory-DE-YccE8.js} +1 -1
- package/dist/assets/{useFontPreferences-B4LGrKaG.js → useFontPreferences-DmeLn0t9.js} +1 -1
- package/dist/assets/{useMobileNavigationStore-9pGm6Lkc.js → useMobileNavigationStore-DPE5LVui.js} +4 -4
- package/dist/assets/{useUIStore-NMQx_cnG.js → useUIStore-CEingF2z.js} +1 -1
- package/dist/assets/{useWorkerHighlightedLines-DSzghYUI.js → useWorkerHighlightedLines-o-elkNrd.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 +188 -16
- package/server/lib/assistants/assign.js +2 -1
- package/server/lib/assistants/contact-tools.js +11 -10
- package/server/lib/assistants/harness.js +23 -9
- package/server/lib/assistants/harness.test.js +34 -10
- 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 +24 -35
- package/server/lib/assistants/service.test.js +208 -21
- 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-CVIpaYPU.js +0 -1
- package/dist/assets/AssistantView-D5vJW3gp.js +0 -3
- package/dist/assets/MarkdownRenderer-DuA1vlFT.js +0 -2
- package/dist/assets/miniChat-DUSGfEUO.js +0 -2
- package/dist/assets/mobile-CMXtTX1x.js +0 -2
- package/dist/assets/runtime-auth-ef9W7A43.js +0 -1
- package/dist/assets/types-BcumvHrl.js +0 -2
|
@@ -71,6 +71,7 @@ import {
|
|
|
71
71
|
extractSessionDirectory,
|
|
72
72
|
extractSessionTitle,
|
|
73
73
|
hasAssignImageParts,
|
|
74
|
+
isManagedAssistantWorkspace,
|
|
74
75
|
mapSessionToWatchStatus,
|
|
75
76
|
resolveAssignDirectory,
|
|
76
77
|
extractAssignSessionModel,
|
|
@@ -78,6 +79,9 @@ import {
|
|
|
78
79
|
sanitizeAssignFileParts,
|
|
79
80
|
} from './assign.js';
|
|
80
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';
|
|
81
85
|
import { loadConnectedCatalog, parseModelRef } from '../llm/catalog.js';
|
|
82
86
|
import { buildAssistantSessionMetadata } from '../session-metadata/system-session.js';
|
|
83
87
|
|
|
@@ -243,7 +247,7 @@ const awaitWithDeadline = async (work, ms = CONTACT_CATALOG_DEADLINE_MS, code =
|
|
|
243
247
|
}
|
|
244
248
|
};
|
|
245
249
|
|
|
246
|
-
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 } = {}) => {
|
|
247
251
|
if (!dbPath || !dataDir) return null;
|
|
248
252
|
const Database = require('better-sqlite3');
|
|
249
253
|
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
|
@@ -444,34 +448,6 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
|
|
|
444
448
|
baseUrl: buildOpenCodeUrl('/', '').replace(/\/$/, ''),
|
|
445
449
|
authHeaders: getOpenCodeAuthHeaders(),
|
|
446
450
|
});
|
|
447
|
-
const loadContactOpenCodeContext = async (signal) => {
|
|
448
|
-
const url = new URL(buildOpenCodeUrl('/', ''));
|
|
449
|
-
url.username = '';
|
|
450
|
-
url.password = '';
|
|
451
|
-
url.search = '';
|
|
452
|
-
url.hash = '';
|
|
453
|
-
const context = [
|
|
454
|
-
'OpenCode capabilities are available through your existing bash tool and the OpenCode CLI/API; no additional native tool names are needed.',
|
|
455
|
-
`Connected OpenCode server: ${JSON.stringify(url.href.replace(/\/$/, ''))}. Target this server with opencode api --server <url>, using the existing authentication context. Do not fall back to a different local service if connection or authentication fails. Never expose credentials.`,
|
|
456
|
-
'Read the OpenCode skill below before using OpenCode capabilities. Use opencode api --help and the connected server OpenAPI contract to discover operations and arguments, rather than guessing.',
|
|
457
|
-
'For current work, GET /api/session/active provides live activity; inspect the relevant sessions and messages for progress. Session-index titles, update times and historical messages alone do not prove that a session is running or finished. A failed live read means unknown, not idle.',
|
|
458
|
-
'OpenCode capabilities are not limited to the Yuri contact tool list. Use the documented CLI/API for other requested operations, retaining user authorization, permission confirmations and this turn\'s constraints. Prefer the existing Yuri tools for assignment, watches and other contact-owned operations so their cards and follow-up stay intact.',
|
|
459
|
-
];
|
|
460
|
-
try {
|
|
461
|
-
const result = await client().skill.list(undefined, {
|
|
462
|
-
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(CONTACT_CATALOG_DEADLINE_MS)]) : AbortSignal.timeout(CONTACT_CATALOG_DEADLINE_MS),
|
|
463
|
-
});
|
|
464
|
-
if (!Array.isArray(result?.data)) throw new Error('skill_catalog_unavailable');
|
|
465
|
-
const skill = result.data.find((item) => item?.id === 'opencode' && item?.path === '<built-in>');
|
|
466
|
-
context.push(typeof skill?.content === 'string' && skill.content.trim()
|
|
467
|
-
? `Connected OpenCode built-in skill:\n${skill.content.trim()}`
|
|
468
|
-
: 'The connected catalog did not include the built-in OpenCode skill. Consult https://opencode.ai/v2/docs/ and discover the current CLI/API contract before use.');
|
|
469
|
-
} catch {
|
|
470
|
-
signal?.throwIfAborted();
|
|
471
|
-
context.push('The built-in OpenCode skill could not be loaded this turn (unknown, not an empty capability catalog). Consult https://opencode.ai/v2/docs/ and verify CLI/API availability before use.');
|
|
472
|
-
}
|
|
473
|
-
return context.join('\n\n');
|
|
474
|
-
};
|
|
475
451
|
const metadata = (row) => buildAssistantSessionMetadata({
|
|
476
452
|
assistantID: row.assistant_id,
|
|
477
453
|
name: row.name,
|
|
@@ -2972,7 +2948,7 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
|
|
|
2972
2948
|
steerSession: (params) => mutateSessionWork('steer', params),
|
|
2973
2949
|
archiveSession: (params) => mutateSessionWork('archive', params),
|
|
2974
2950
|
deleteSession: (params) => mutateSessionWork('delete', params),
|
|
2975
|
-
|
|
2951
|
+
createAssistant: (toolInput) => createAssistant({ ...toolInput, avatarSeed: randomAvatarSeed(id()), language: contactTurnLanguages.get(assistantID) || 'en' }),
|
|
2976
2952
|
scheduleTask: (params) => scheduleWork(live, params),
|
|
2977
2953
|
listScheduledTasks: (params) => listScheduledTaskWork(params),
|
|
2978
2954
|
updateScheduledTask: (params) => updateScheduledTaskWork(live, params, controller.signal),
|
|
@@ -3331,7 +3307,7 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
|
|
|
3331
3307
|
steerSession: (params) => mutateSessionWork('steer', params),
|
|
3332
3308
|
archiveSession: (params) => mutateSessionWork('archive', params),
|
|
3333
3309
|
deleteSession: (params) => mutateSessionWork('delete', params),
|
|
3334
|
-
|
|
3310
|
+
createAssistant: (toolInput) => createAssistant({ ...toolInput, avatarSeed: randomAvatarSeed(id()), language: language || 'en' }),
|
|
3335
3311
|
scheduleTask: (params) => scheduleWork(row, params),
|
|
3336
3312
|
listScheduledTasks: (params) => listScheduledTaskWork(params),
|
|
3337
3313
|
updateScheduledTask: (params) => updateScheduledTaskWork(row, params, controller.signal),
|
|
@@ -3421,17 +3397,29 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
|
|
|
3421
3397
|
turnFileParts,
|
|
3422
3398
|
turnAttachmentScope,
|
|
3423
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
|
+
}));
|
|
3424
3413
|
controller.signal.throwIfAborted();
|
|
3425
3414
|
const generated = await runContactTurn({
|
|
3426
3415
|
signal: controller.signal,
|
|
3427
3416
|
assistant: assistantSnapshot,
|
|
3428
|
-
openCodeContext: await loadContactOpenCodeContext(controller.signal),
|
|
3429
3417
|
history: executionHistory,
|
|
3430
3418
|
userText,
|
|
3431
3419
|
userParts: executionParts,
|
|
3432
3420
|
language,
|
|
3433
3421
|
createChatCompletion,
|
|
3434
|
-
tools,
|
|
3422
|
+
tools: [...tools, ...createOpenCodeContactTools({ resolveClient: client, directory: resolveAssistantCwd(assistantSnapshot) })],
|
|
3435
3423
|
projects: registeredProjects,
|
|
3436
3424
|
...modelContext,
|
|
3437
3425
|
globalEventHub,
|
|
@@ -3889,7 +3877,7 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
|
|
|
3889
3877
|
)),
|
|
3890
3878
|
};
|
|
3891
3879
|
};
|
|
3892
|
-
|
|
3880
|
+
const removeAssistant = (assistantID, expectedRevision) => {
|
|
3893
3881
|
db.exec('BEGIN IMMEDIATE');
|
|
3894
3882
|
try {
|
|
3895
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);
|
|
@@ -3911,7 +3899,8 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
|
|
|
3911
3899
|
db.exec('ROLLBACK');
|
|
3912
3900
|
throw error;
|
|
3913
3901
|
}
|
|
3914
|
-
}
|
|
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: () => {
|
|
3915
3904
|
cancelAssignedResumes({});
|
|
3916
3905
|
sessionAbortInflight.clear();
|
|
3917
3906
|
pendingAssignMessageIDs.clear();
|
|
@@ -93,6 +93,7 @@ const createV2Client = (overrides = {}) => {
|
|
|
93
93
|
provider: { list: providerList, ...(provider || {}) },
|
|
94
94
|
model: { list: modelList, ...(overrides.model || {}) },
|
|
95
95
|
...(overrides.skill ? { skill: overrides.skill } : {}),
|
|
96
|
+
...(overrides.websearch ? { websearch: overrides.websearch } : {}),
|
|
96
97
|
...(config ? { config } : {}),
|
|
97
98
|
};
|
|
98
99
|
};
|
|
@@ -2324,6 +2325,70 @@ describe('assistants service', () => {
|
|
|
2324
2325
|
service.close();
|
|
2325
2326
|
});
|
|
2326
2327
|
|
|
2328
|
+
it('registers a discovered workspace and opens its session in the same native-tool turn', async () => {
|
|
2329
|
+
const directory = root();
|
|
2330
|
+
const workspace = path.join(directory, 'cloned-repository');
|
|
2331
|
+
fs.mkdirSync(workspace);
|
|
2332
|
+
const projects = [];
|
|
2333
|
+
const creates = [];
|
|
2334
|
+
const prompts = [];
|
|
2335
|
+
const registerProject = vi.fn(async ({ path: projectPath }) => {
|
|
2336
|
+
const project = { id: 'new-project', path: fs.realpathSync(projectPath) };
|
|
2337
|
+
projects.push(project);
|
|
2338
|
+
return { project, created: true };
|
|
2339
|
+
});
|
|
2340
|
+
const replies = [
|
|
2341
|
+
toolBatch([['load_tools', { domain: 'yuri.projects' }]]),
|
|
2342
|
+
toolBatch([['register_project', { path: workspace }]]),
|
|
2343
|
+
toolBatch([['assign_session', { projectPath: workspace, prompt: 'hello' }]]),
|
|
2344
|
+
];
|
|
2345
|
+
const service = setup(directory, {
|
|
2346
|
+
create: async (input) => { creates.push(input); return { id: 'ses_registered' }; },
|
|
2347
|
+
prompt: async (input) => { prompts.push(input); return { id: 'inbox_hello', type: 'user' }; },
|
|
2348
|
+
}, {
|
|
2349
|
+
getAllowedRoots: () => projects.map((project) => project.path),
|
|
2350
|
+
listProjects: async () => projects,
|
|
2351
|
+
registerProject,
|
|
2352
|
+
runContactTurn: (input) => realRunContactTurn({ ...input,
|
|
2353
|
+
createChatCompletion: async () => replies.shift() ?? { text: 'Opened.' },
|
|
2354
|
+
}),
|
|
2355
|
+
});
|
|
2356
|
+
try {
|
|
2357
|
+
const assistant = service.createAssistant(assistantInput);
|
|
2358
|
+
const sent = await settleSend(service, assistant.id, { messageID: 'register_then_assign', parts: [{ type: 'text', text: `Add ${workspace} as a project, open a session and say hello` }] });
|
|
2359
|
+
expect(sent.settled.status).toBe('complete');
|
|
2360
|
+
expect(registerProject).toHaveBeenCalledTimes(1);
|
|
2361
|
+
expect(creates).toHaveLength(1);
|
|
2362
|
+
expect(creates[0].location.directory).toBe(fs.realpathSync(workspace));
|
|
2363
|
+
expect(prompts).toHaveLength(1);
|
|
2364
|
+
expect(JSON.stringify(prompts[0])).toContain('hello');
|
|
2365
|
+
expect(service.contactMessages(assistant.id).messages.flatMap((message) => message.cards).some((card) => card.cardType === 'session')).toBe(true);
|
|
2366
|
+
} finally { service.close(); fs.rmSync(directory, { recursive: true, force: true }); }
|
|
2367
|
+
});
|
|
2368
|
+
|
|
2369
|
+
it('rejects assistant-workspaces registration even through a symlink before registry mutation', async () => {
|
|
2370
|
+
const directory = root();
|
|
2371
|
+
const managed = path.join(directory, 'assistant-workspaces');
|
|
2372
|
+
fs.mkdirSync(managed);
|
|
2373
|
+
const alias = path.join(directory, 'alias');
|
|
2374
|
+
fs.symlinkSync(managed, alias);
|
|
2375
|
+
const registerProject = vi.fn();
|
|
2376
|
+
const results = [];
|
|
2377
|
+
const service = setup(directory, {}, { registerProject,
|
|
2378
|
+
runContactTurn: async ({ tools }) => {
|
|
2379
|
+
const tool = tools.find((item) => item.name === 'register_project');
|
|
2380
|
+
for (const target of [managed, alias, 'relative/path']) results.push(await tool.execute('bad', { path: target }));
|
|
2381
|
+
return { text: 'Rejected', bubbles: ['Rejected'] };
|
|
2382
|
+
},
|
|
2383
|
+
});
|
|
2384
|
+
try {
|
|
2385
|
+
const host = service.createAssistant(assistantInput);
|
|
2386
|
+
await settleSend(service, host.id, { messageID: 'bad-registration', text: 'Register workspace' });
|
|
2387
|
+
expect(results.every((result) => result.details.error === 'workspace_forbidden')).toBe(true);
|
|
2388
|
+
expect(registerProject).not.toHaveBeenCalled();
|
|
2389
|
+
} finally { service.close(); fs.rmSync(directory, { recursive: true, force: true }); }
|
|
2390
|
+
});
|
|
2391
|
+
|
|
2327
2392
|
it('assigns a registered project session and persists the session card', async () => {
|
|
2328
2393
|
const directory = root();
|
|
2329
2394
|
const project = path.join(directory, 'app');
|
|
@@ -3173,6 +3238,45 @@ describe('assistants service', () => {
|
|
|
3173
3238
|
service.close();
|
|
3174
3239
|
});
|
|
3175
3240
|
|
|
3241
|
+
it('gives tool-created assistants random shapes and pigments without changing manual defaults or existing faces', async () => {
|
|
3242
|
+
const directory = root();
|
|
3243
|
+
let result;
|
|
3244
|
+
let service = setup(directory, {}, {
|
|
3245
|
+
runContactTurn: async ({ tools }) => {
|
|
3246
|
+
result = await tools.find((tool) => tool.name === 'create_assistant').execute('create', { name: 'New Bot' });
|
|
3247
|
+
return { text: 'Created.', bubbles: ['Created.'] };
|
|
3248
|
+
},
|
|
3249
|
+
});
|
|
3250
|
+
const host = service.createAssistant(assistantInput);
|
|
3251
|
+
const peer = service.createAssistant({ ...assistantInput, avatarSeed: 'existing-face' });
|
|
3252
|
+
const random = vi.spyOn(crypto, 'randomInt');
|
|
3253
|
+
const created = [];
|
|
3254
|
+
try {
|
|
3255
|
+
for (const [index, color] of AVATAR_COLORS.entries()) {
|
|
3256
|
+
random.mockImplementation((max) => max === AVATAR_COLORS.length ? index : 1);
|
|
3257
|
+
await settleSend(service, host.id, { messageID: `create-${color}`, parts: [{ type: 'text', text: '创建一个助理' }] });
|
|
3258
|
+
expect(result.isError).not.toBe(true);
|
|
3259
|
+
const bot = result.details.assistant;
|
|
3260
|
+
expect(resolveAssistantAvatar(bot.avatarSeed)).toMatchObject({ shape: 'soft', color, eyes: 'capsule', expression: 'neutral', animate: true });
|
|
3261
|
+
expect(service.snapshot().assistants.find((item) => item.id === bot.id)?.avatarSeed).toBe(bot.avatarSeed);
|
|
3262
|
+
created.push(bot);
|
|
3263
|
+
}
|
|
3264
|
+
expect(new Set(created.map((bot) => bot.avatarSeed)).size).toBe(AVATAR_COLORS.length);
|
|
3265
|
+
const manual = service.createAssistant(assistantInput);
|
|
3266
|
+
expect(resolveAssistantAvatar(manual.avatarSeed)).toMatchObject({ shape: 'round' });
|
|
3267
|
+
service.close();
|
|
3268
|
+
service = setup(directory);
|
|
3269
|
+
const restored = service.snapshot().assistants;
|
|
3270
|
+
for (const bot of [...created, manual, host, peer]) {
|
|
3271
|
+
expect(restored.find((item) => item.id === bot.id)?.avatarSeed).toBe(bot.avatarSeed);
|
|
3272
|
+
}
|
|
3273
|
+
} finally {
|
|
3274
|
+
random.mockRestore();
|
|
3275
|
+
service.close();
|
|
3276
|
+
fs.rmSync(directory, { recursive: true, force: true });
|
|
3277
|
+
}
|
|
3278
|
+
});
|
|
3279
|
+
|
|
3176
3280
|
it('reads and persists defaultPrompt via get_assistant_settings / update_default_prompt', async () => {
|
|
3177
3281
|
const directory = root();
|
|
3178
3282
|
const tips = [];
|
|
@@ -3459,6 +3563,7 @@ describe('assistants service', () => {
|
|
|
3459
3563
|
const backgroundTurns = [];
|
|
3460
3564
|
const runContactTurn = async (input) => {
|
|
3461
3565
|
if (input.readOnly) {
|
|
3566
|
+
expect(input.tools.some((tool) => ['register_project', 'update_project', 'remove_project', 'update_assistant', 'delete_assistant', 'run_scheduled_task', 'delete_scheduled_task', 'rename_session'].includes(tool.name))).toBe(false);
|
|
3462
3567
|
backgroundTurns.push(input);
|
|
3463
3568
|
return realRunContactTurn({
|
|
3464
3569
|
...input,
|
|
@@ -3506,29 +3611,101 @@ describe('assistants service', () => {
|
|
|
3506
3611
|
}
|
|
3507
3612
|
});
|
|
3508
3613
|
|
|
3509
|
-
it('
|
|
3614
|
+
it('does not fetch OpenCode catalogs or expose deferred schemas on an ordinary contact turn', async () => {
|
|
3615
|
+
const directory = root();
|
|
3616
|
+
const list = vi.fn(() => new Promise(() => {}));
|
|
3617
|
+
const query = vi.fn();
|
|
3618
|
+
const service = setup(directory, { skill: { list }, websearch: { query } }, {
|
|
3619
|
+
runContactTurn: realRunContactTurn,
|
|
3620
|
+
createChatCompletion: async ({ body }) => {
|
|
3621
|
+
const names = body.tools.map((tool) => tool.function.name);
|
|
3622
|
+
expect(names.filter((name) => name.startsWith('load_'))).toEqual(['load_tools']);
|
|
3623
|
+
for (const name of ['websearch', 'list_websearch_providers', 'list_active_sessions', 'list_opencode_capabilities', 'read_opencode_skill']) expect(names).not.toContain(name);
|
|
3624
|
+
const prompt = body.messages.find((message) => message.role === 'system').content;
|
|
3625
|
+
expect(prompt).not.toContain('Connected OpenCode built-in skill:');
|
|
3626
|
+
expect(prompt).not.toContain('opencode api --help');
|
|
3627
|
+
return { text: '你好。' };
|
|
3628
|
+
},
|
|
3629
|
+
});
|
|
3630
|
+
try {
|
|
3631
|
+
const assistant = service.createAssistant(assistantInput);
|
|
3632
|
+
expect((await settleSend(service, assistant.id, { messageID: 'no-eager-catalog', text: '你好' })).settled.status).toBe('complete');
|
|
3633
|
+
expect(list).not.toHaveBeenCalled();
|
|
3634
|
+
expect(query).not.toHaveBeenCalled();
|
|
3635
|
+
} finally { service.close(); fs.rmSync(directory, { recursive: true, force: true }); }
|
|
3636
|
+
});
|
|
3637
|
+
|
|
3638
|
+
it('runs direct search and live-status tools end to end through contact send without opening a worker', async () => {
|
|
3639
|
+
const directory = root();
|
|
3640
|
+
const query = vi.fn(async () => ({ data: { providerID: 'exa', results: [{ url: 'https://example.test/repository', title: 'Repository evidence', content: 'Actual online findings' }] } }));
|
|
3641
|
+
const active = vi.fn(async () => ({ ses_running: { type: 'running' } }));
|
|
3642
|
+
const create = vi.fn();
|
|
3643
|
+
let round = 0;
|
|
3644
|
+
const service = setup(directory, { create, active, websearch: { query } }, {
|
|
3645
|
+
runContactTurn: realRunContactTurn,
|
|
3646
|
+
createChatCompletion: async ({ body }) => {
|
|
3647
|
+
round++;
|
|
3648
|
+
if (round === 1) return toolBatch([['load_tools', { domain: 'opencode.web' }]]);
|
|
3649
|
+
if (round === 2) return toolBatch([['websearch', { query: 'site:github.com client', providerID: 'exa' }, 'search-live']]);
|
|
3650
|
+
if (round === 3) {
|
|
3651
|
+
expect(body.messages.find((message) => message.tool_call_id === 'search-live')?.content).toContain('Actual online findings');
|
|
3652
|
+
return toolBatch([['load_tools', { domain: 'opencode.activity' }]]);
|
|
3653
|
+
}
|
|
3654
|
+
if (round === 4) return toolBatch([['list_active_sessions', {}, 'status-live']]);
|
|
3655
|
+
expect(body.messages.find((message) => message.tool_call_id === 'status-live')?.content).toContain('ses_running');
|
|
3656
|
+
return { text: '已检索来源并查询实时任务。' };
|
|
3657
|
+
},
|
|
3658
|
+
});
|
|
3659
|
+
try {
|
|
3660
|
+
const assistant = service.createAssistant({ ...assistantInput, workspacePath: directory });
|
|
3661
|
+
const sent = await settleSend(service, assistant.id, { messageID: 'direct-tools', text: '联网查一下,并看看任务是否仍在运行' });
|
|
3662
|
+
expect(sent.settled.status).toBe('complete');
|
|
3663
|
+
expect(service.contactMessages(assistant.id).messages.at(-1).text).toBe('已检索来源并查询实时任务。');
|
|
3664
|
+
expect(query).toHaveBeenCalledWith({ location: { directory: fs.realpathSync(directory) }, query: 'site:github.com client', providerID: 'exa' }, expect.objectContaining({ signal: expect.any(AbortSignal) }));
|
|
3665
|
+
expect(active).toHaveBeenCalledTimes(1);
|
|
3666
|
+
expect(create).not.toHaveBeenCalled();
|
|
3667
|
+
expect(round).toBe(5);
|
|
3668
|
+
} finally {
|
|
3669
|
+
service.close();
|
|
3670
|
+
fs.rmSync(directory, { recursive: true, force: true });
|
|
3671
|
+
}
|
|
3672
|
+
});
|
|
3673
|
+
|
|
3674
|
+
it.each(['/builtin/opencode.md', '<built-in>'])('reads the connected built-in OpenCode skill at %s only after loading and requesting it', async (builtinPath) => {
|
|
3510
3675
|
const directory = root();
|
|
3511
3676
|
let skillContent = 'Use the existing OpenCode API for live execution status.';
|
|
3512
|
-
let server = 'upstream.example.test';
|
|
3513
3677
|
const list = vi.fn(async () => ({ data: [
|
|
3514
3678
|
{ id: 'other', path: '<built-in>', content: 'Unrelated skill content' },
|
|
3515
|
-
{ id: 'opencode', path: '/custom/SKILL.md', content: 'Not the built-in skill' },
|
|
3516
|
-
{ id: 'opencode', path:
|
|
3679
|
+
{ id: 'custom-opencode', path: '/custom/SKILL.md', content: 'Not the built-in skill' },
|
|
3680
|
+
{ id: 'opencode', path: builtinPath, content: skillContent },
|
|
3517
3681
|
] }));
|
|
3682
|
+
let round = 0;
|
|
3518
3683
|
const createChatCompletion = vi.fn(async ({ body }) => {
|
|
3684
|
+
round++;
|
|
3519
3685
|
const system = body.messages.find((message) => message.role === 'system').content;
|
|
3520
|
-
expect(system).toContain(
|
|
3521
|
-
expect(system).toContain('opencode api --server');
|
|
3522
|
-
expect(system).toContain(`https://${server}/prefix`);
|
|
3523
|
-
expect(system).toContain('GET /api/session/active');
|
|
3686
|
+
expect(system).not.toContain(skillContent);
|
|
3687
|
+
expect(system).not.toContain('opencode api without --server');
|
|
3524
3688
|
expect(system).not.toContain('Unrelated skill content');
|
|
3525
3689
|
expect(system).not.toContain('Not the built-in skill');
|
|
3526
3690
|
expect(system).not.toContain('secret');
|
|
3527
|
-
|
|
3691
|
+
const names = body.tools.map((tool) => tool.function.name);
|
|
3692
|
+
if (round === 1) {
|
|
3693
|
+
for (const name of ['websearch', 'list_websearch_providers', 'list_active_sessions', 'list_opencode_capabilities', 'read_opencode_skill']) expect(names).not.toContain(name);
|
|
3694
|
+
expect(list).not.toHaveBeenCalled();
|
|
3695
|
+
return toolBatch([['load_tools', { domain: 'opencode.catalog' }]]);
|
|
3696
|
+
}
|
|
3697
|
+
expect(names).toContain('read_opencode_skill');
|
|
3698
|
+
expect(names).not.toContain('websearch');
|
|
3699
|
+
if (round === 2) {
|
|
3700
|
+
expect(list).not.toHaveBeenCalled();
|
|
3701
|
+
return toolBatch([['read_opencode_skill', { id: 'opencode' }, 'read-skill']]);
|
|
3702
|
+
}
|
|
3703
|
+
const evidence = body.messages.find((message) => message.tool_call_id === 'read-skill');
|
|
3704
|
+
expect(evidence.content).toContain(skillContent);
|
|
3528
3705
|
return { text: 'Checked the available OpenCode context.' };
|
|
3529
3706
|
});
|
|
3530
3707
|
const service = setup(directory, { skill: { list } }, {
|
|
3531
|
-
buildOpenCodeUrl: () =>
|
|
3708
|
+
buildOpenCodeUrl: () => 'https://user:secret@upstream.example.test/prefix/?token=secret#secret',
|
|
3532
3709
|
runContactTurn: realRunContactTurn,
|
|
3533
3710
|
createChatCompletion,
|
|
3534
3711
|
});
|
|
@@ -3537,12 +3714,13 @@ describe('assistants service', () => {
|
|
|
3537
3714
|
const first = await settleSend(service, assistant.id, { messageID: 'context-1', text: '看看正在运行的任务' });
|
|
3538
3715
|
expect(first.settled.status).toBe('complete');
|
|
3539
3716
|
skillContent = 'Updated upstream skill instructions.';
|
|
3540
|
-
|
|
3717
|
+
round = 0;
|
|
3718
|
+
list.mockClear();
|
|
3541
3719
|
const second = await settleSend(service, assistant.id, { messageID: 'context-2', text: '再看看' });
|
|
3542
3720
|
expect(second.settled.status).toBe('complete');
|
|
3543
|
-
expect(list).toHaveBeenCalledTimes(
|
|
3721
|
+
expect(list).toHaveBeenCalledTimes(1);
|
|
3544
3722
|
expect(list.mock.calls[0][1].signal).toBeInstanceOf(AbortSignal);
|
|
3545
|
-
expect(createChatCompletion).toHaveBeenCalledTimes(
|
|
3723
|
+
expect(createChatCompletion).toHaveBeenCalledTimes(6);
|
|
3546
3724
|
} finally {
|
|
3547
3725
|
service.close();
|
|
3548
3726
|
fs.rmSync(directory, { recursive: true, force: true });
|
|
@@ -3555,19 +3733,28 @@ describe('assistants service', () => {
|
|
|
3555
3733
|
if (kind === 'failed') throw new Error('secret upstream detail');
|
|
3556
3734
|
return { data: kind === 'malformed' ? null : [] };
|
|
3557
3735
|
});
|
|
3558
|
-
|
|
3559
|
-
|
|
3560
|
-
|
|
3561
|
-
|
|
3562
|
-
|
|
3563
|
-
|
|
3736
|
+
let round = 0;
|
|
3737
|
+
const service = setup(directory, { skill: { list } }, { runContactTurn: realRunContactTurn,
|
|
3738
|
+
createChatCompletion: async ({ body }) => {
|
|
3739
|
+
round++;
|
|
3740
|
+
if (round === 1) {
|
|
3741
|
+
expect(list).not.toHaveBeenCalled();
|
|
3742
|
+
return toolBatch([['load_tools', { domain: 'opencode.catalog' }]]);
|
|
3743
|
+
}
|
|
3744
|
+
if (round === 2) return toolBatch([['read_opencode_skill', { id: 'opencode' }, 'missing-skill']]);
|
|
3745
|
+
const evidence = body.messages.find((message) => message.tool_call_id === 'missing-skill');
|
|
3746
|
+
expect(evidence.content).toContain('isError');
|
|
3747
|
+
expect(evidence.content).not.toContain('secret upstream detail');
|
|
3748
|
+
expect(body.tools.some((tool) => tool.function.name === 'list_opencode_capabilities')).toBe(true);
|
|
3749
|
+
return { text: 'Skill unavailable; discovery can still be requested.' };
|
|
3750
|
+
},
|
|
3564
3751
|
});
|
|
3565
|
-
const service = setup(directory, { skill: { list } }, { runContactTurn });
|
|
3566
3752
|
try {
|
|
3567
3753
|
const assistant = service.createAssistant(assistantInput);
|
|
3568
3754
|
const sent = await settleSend(service, assistant.id, { messageID: 'context-fallback', text: '任务进度如何' });
|
|
3569
3755
|
expect(sent.settled.status).toBe('complete');
|
|
3570
|
-
expect(
|
|
3756
|
+
expect(list).toHaveBeenCalledTimes(1);
|
|
3757
|
+
expect(round).toBe(3);
|
|
3571
3758
|
} finally {
|
|
3572
3759
|
service.close();
|
|
3573
3760
|
fs.rmSync(directory, { recursive: true, force: true });
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import http from 'node:http';
|
|
6
|
+
import express from 'express';
|
|
7
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
8
|
+
|
|
9
|
+
const external = vi.hoisted(() => ({ complete: null, client: null }));
|
|
10
|
+
vi.mock('../llm/completions.js', () => ({ createChatCompletion: (input) => external.complete(input) }));
|
|
11
|
+
vi.mock('../opencode/v2-client.js', () => ({ makeOpenCodeV2Client: () => external.client }));
|
|
12
|
+
vi.mock('@opencode/client', () => ({ OpenCode: { make: () => external.client } }));
|
|
13
|
+
import { registerAssistantRoutes } from './routes.js';
|
|
14
|
+
import { registerConversationRoutes } from '../conversations/routes.js';
|
|
15
|
+
import { registerOpenCodeRoutes } from '../opencode/routes.js';
|
|
16
|
+
import { createSettingsRuntime } from '../opencode/settings-runtime.js';
|
|
17
|
+
import { createSettingsNormalizationRuntime } from '../opencode/settings-normalization-runtime.js';
|
|
18
|
+
import { createProjectDirectoryRuntime } from '../opencode/project-directory-runtime.js';
|
|
19
|
+
import { createProjectRegistry } from '../projects/registry.js';
|
|
20
|
+
|
|
21
|
+
const call = (name, args) => ({ completion: { choices: [{ message: { content: '', tool_calls: [{ id: `call_${name}`, type: 'function', function: { name, arguments: JSON.stringify(args) } }] } }] } });
|
|
22
|
+
|
|
23
|
+
describe('HTTP → real contact Agent → project registry → worker admission', () => {
|
|
24
|
+
it('registers a cloned directory, sends hello and persists a real session card without manual Settings', async () => {
|
|
25
|
+
const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yuri-project-http-'));
|
|
26
|
+
const workspace = path.join(directory, 'cloned-app');
|
|
27
|
+
await fs.mkdir(workspace);
|
|
28
|
+
const canonical = await fs.realpath(workspace);
|
|
29
|
+
const normalization = createSettingsNormalizationRuntime({ os, path, processLike: process });
|
|
30
|
+
const settings = createSettingsRuntime({ fsPromises: fs, path, crypto, SETTINGS_FILE_PATH: path.join(directory, 'settings.json'), ...normalization,
|
|
31
|
+
sanitizeSettingsUpdate: (patch) => patch, mergePersistedSettings: (current, patch) => ({ ...current, ...patch }),
|
|
32
|
+
formatSettingsResponse: (value) => value, resolveDirectoryCandidate: (value) => value,
|
|
33
|
+
});
|
|
34
|
+
const { validateDirectoryPath } = createProjectDirectoryRuntime({ fsPromises: fs, path, normalizeDirectoryPath: normalization.normalizeDirectoryPath });
|
|
35
|
+
const registry = createProjectRegistry({ persistSettings: settings.persistSettings, validateDirectoryPath });
|
|
36
|
+
const creates = vi.fn(async () => ({ id: 'ses_hello' }));
|
|
37
|
+
const prompts = vi.fn(async () => ({ id: 'inbox_hello', type: 'user' }));
|
|
38
|
+
external.client = {
|
|
39
|
+
provider: { list: async () => ({ data: [{ id: 'p' }] }) },
|
|
40
|
+
model: { list: async () => ({ data: [{ id: 'm', providerID: 'p' }] }) },
|
|
41
|
+
skill: { list: async () => ({ data: [] }) },
|
|
42
|
+
session: { create: creates, prompt: prompts, active: async () => ({}) },
|
|
43
|
+
};
|
|
44
|
+
const roots = [];
|
|
45
|
+
const refresh = async () => {
|
|
46
|
+
const current = await settings.readSettingsFromDiskStrict();
|
|
47
|
+
roots.splice(0, roots.length, ...(current.projects || []).map((project) => project.path));
|
|
48
|
+
};
|
|
49
|
+
let round = 0;
|
|
50
|
+
external.complete = async ({ body }) => {
|
|
51
|
+
round++;
|
|
52
|
+
if (round === 1) {
|
|
53
|
+
expect(body.tools.some((tool) => tool.function.name === 'register_project')).toBe(false);
|
|
54
|
+
expect(body.tools.some((tool) => tool.function.name === 'websearch')).toBe(false);
|
|
55
|
+
return call('load_tools', { domain: 'opencode.web' });
|
|
56
|
+
}
|
|
57
|
+
if (round === 2) {
|
|
58
|
+
expect(body.tools.some((tool) => tool.function.name === 'websearch')).toBe(true);
|
|
59
|
+
return call('load_tools', { domain: 'yuri.projects' });
|
|
60
|
+
}
|
|
61
|
+
if (round === 3) {
|
|
62
|
+
expect(body.tools.some((tool) => tool.function.name === 'register_project')).toBe(true);
|
|
63
|
+
return call('register_project', { path: workspace, label: 'Cloned App' });
|
|
64
|
+
}
|
|
65
|
+
if (round === 4) {
|
|
66
|
+
expect(body.messages.find((message) => message.name === 'register_project')?.content).toContain(canonical);
|
|
67
|
+
return call('assign_session', { projectPath: canonical, prompt: 'hello' });
|
|
68
|
+
}
|
|
69
|
+
return { text: '已在这个项目里创建会话并发送 hello。' };
|
|
70
|
+
};
|
|
71
|
+
const app = express(); app.use(express.json());
|
|
72
|
+
const runtime = registerAssistantRoutes(app, {
|
|
73
|
+
dbPath: path.join(directory, 'assistants.sqlite'), yuriDataDir: directory,
|
|
74
|
+
getAllowedRoots: () => roots, refreshAllowedRoots: refresh,
|
|
75
|
+
listProjects: async () => (await settings.readSettingsFromDiskStrict()).projects || [],
|
|
76
|
+
registerProject: async (input) => { const result = await registry.register(input); await refresh(); return result; },
|
|
77
|
+
buildOpenCodeUrl: (pathname) => `http://upstream.invalid${pathname}`, getOpenCodeAuthHeaders: () => ({}),
|
|
78
|
+
});
|
|
79
|
+
registerOpenCodeRoutes(app, { ...settings, validateDirectoryPath, formatSettingsResponse: (value) => value });
|
|
80
|
+
registerConversationRoutes(app, { buildOpenCodeUrl: (pathname) => `http://upstream.invalid${pathname}`, getOpenCodeAuthHeaders: () => ({}) });
|
|
81
|
+
const server = http.createServer(app);
|
|
82
|
+
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
83
|
+
const base = `http://127.0.0.1:${server.address().port}`;
|
|
84
|
+
const request = async (route, body) => {
|
|
85
|
+
const response = await fetch(`${base}${route}`, { method: body ? 'POST' : 'GET', headers: { 'content-type': 'application/json' }, ...(body ? { body: JSON.stringify(body) } : {}) });
|
|
86
|
+
expect(response.ok).toBe(true);
|
|
87
|
+
return response.json();
|
|
88
|
+
};
|
|
89
|
+
try {
|
|
90
|
+
const assistant = await request('/api/yuri/assistants', { name: 'Test Bot', providerID: 'p', modelID: 'm' });
|
|
91
|
+
const admitted = await request(`/api/yuri/assistants/${assistant.id}/messages`, { messageID: 'create-project-chat', text: `Add ${workspace} and open a session saying hello` });
|
|
92
|
+
expect(admitted.admitted).toBe(true);
|
|
93
|
+
expect((await runtime.service.whenContactTurnSettled(admitted.messageID)).status).toBe('complete');
|
|
94
|
+
expect(creates).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ location: { directory: canonical } }));
|
|
95
|
+
expect(prompts).toHaveBeenCalledWith(expect.objectContaining({ sessionID: 'ses_hello', text: 'hello' }));
|
|
96
|
+
expect(prompts.mock.calls[0][0]).not.toHaveProperty('skills');
|
|
97
|
+
expect(prompts.mock.calls[0][0]).not.toHaveProperty('tools');
|
|
98
|
+
expect(JSON.stringify(creates.mock.calls[0][0])).not.toContain('load_tools');
|
|
99
|
+
expect(JSON.stringify(creates.mock.calls[0][0])).not.toContain('opencode.web');
|
|
100
|
+
const page = await request(`/api/yuri/assistants/${assistant.id}/contact/messages`);
|
|
101
|
+
expect(page.messages.flatMap((message) => message.parts)).toContainEqual(expect.objectContaining({ type: 'card', cardType: 'session', sessionID: 'ses_hello', directory: canonical }));
|
|
102
|
+
const persisted = await settings.readSettingsFromDiskStrict();
|
|
103
|
+
expect(persisted.projects).toHaveLength(1);
|
|
104
|
+
expect(persisted.projects[0]).toMatchObject({ path: canonical, label: 'Cloned App' });
|
|
105
|
+
// The pre-existing UI API uses the same registration owner and identity.
|
|
106
|
+
const ui = await request('/api/opencode/directory', { path: workspace });
|
|
107
|
+
expect(ui.settings.projects).toHaveLength(1);
|
|
108
|
+
expect(ui.path).toBe(canonical);
|
|
109
|
+
expect(ui.settings.activeProjectId).toBe(persisted.projects[0].id);
|
|
110
|
+
// Ordinary Session admission after a contact load still receives only its own prompt.
|
|
111
|
+
const modelRounds = round;
|
|
112
|
+
const session = await request('/api/yuri/conversations', {
|
|
113
|
+
input: { type: 'prompt' }, directory: canonical, messageID: 'ordinary-session',
|
|
114
|
+
model: { providerID: 'p', modelID: 'm' }, parts: [{ type: 'text', text: 'ordinary hello' }],
|
|
115
|
+
});
|
|
116
|
+
expect(session.ok).toBe(true);
|
|
117
|
+
expect(prompts.mock.calls.at(-1)[0]).toEqual({ sessionID: 'ses_hello', id: 'ordinary-session', text: 'ordinary hello', delivery: 'steer' });
|
|
118
|
+
expect(round).toBe(modelRounds);
|
|
119
|
+
} finally {
|
|
120
|
+
runtime.close(); server.closeAllConnections();
|
|
121
|
+
await new Promise((resolve) => server.close(resolve));
|
|
122
|
+
external.complete = null; external.client = null;
|
|
123
|
+
await fs.rm(directory, { recursive: true, force: true });
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
});
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
export function createYuriContactToolGroups(tools) {
|
|
2
|
+
return [
|
|
3
|
+
{ id: 'yuri.projects', description: 'Register an existing workspace before opening a coding session.', names: ['register_project'] },
|
|
4
|
+
{ id: 'yuri.assistants', description: 'Create a Bot or change its avatar.', names: ['create_assistant', 'update_avatar'] },
|
|
5
|
+
{ id: 'yuri.tasks', description: 'Create or update scheduled tasks (including pause/resume).', names: ['schedule_task', 'update_scheduled_task'] },
|
|
6
|
+
].map(({ id, description, names }) => ({ id, description, tools: tools.filter((tool) => names.includes(tool.name)) }))
|
|
7
|
+
.filter((group) => group.tools.length > 0);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const result = (details, isError = false) => ({
|
|
11
|
+
content: [{ type: 'text', text: JSON.stringify(details) }], details, isError, terminate: false,
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
/** Assistant-local business capability; never registered with OpenCode or its skills catalog. */
|
|
15
|
+
export function createYuriContactTools({ registerProject } = {}) {
|
|
16
|
+
if (typeof registerProject !== 'function') return [];
|
|
17
|
+
return [{
|
|
18
|
+
name: 'register_project', label: 'Register project',
|
|
19
|
+
description: 'Register an existing user-requested absolute Host directory as a Yuri project, then call assign_session with the returned project.path in the same turn. Does not clone/create files or switch an existing active project. Never register a guessed directory or assistant-workspaces.',
|
|
20
|
+
parameters: { type: 'object', additionalProperties: false, required: ['path'], properties: {
|
|
21
|
+
path: { type: 'string', minLength: 1, maxLength: 4096, description: 'Existing absolute Host directory resolved from the user request or filesystem discovery.' },
|
|
22
|
+
label: { type: 'string', minLength: 1, maxLength: 80, description: 'Optional project display name.' },
|
|
23
|
+
} },
|
|
24
|
+
execute: async (_id, params, signal) => {
|
|
25
|
+
signal?.throwIfAborted();
|
|
26
|
+
if (!params || Array.isArray(params) || typeof params !== 'object'
|
|
27
|
+
|| Object.keys(params).some((key) => !['path', 'label'].includes(key))
|
|
28
|
+
|| typeof params.path !== 'string' || !params.path.trim() || params.path.length > 4096
|
|
29
|
+
|| (params.label !== undefined && (typeof params.label !== 'string' || !params.label.trim() || params.label.length > 80))) {
|
|
30
|
+
return result({ error: 'validation_error' }, true);
|
|
31
|
+
}
|
|
32
|
+
try {
|
|
33
|
+
const { project, created } = await registerProject(params, signal);
|
|
34
|
+
return result({ project: { id: project.id, path: project.path, ...(project.label ? { label: project.label } : {}) }, created });
|
|
35
|
+
} catch (error) {
|
|
36
|
+
signal?.throwIfAborted();
|
|
37
|
+
const code = ['validation_error', 'workspace_forbidden', 'project_unavailable'].includes(error?.code) ? error.code : 'yuri_operation_failed';
|
|
38
|
+
return result({ error: code, message: 'Registration failed. Check the project catalog before retrying; do not claim success.' }, true);
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
}];
|
|
42
|
+
}
|