@yuriai/web 0.2.7 → 0.2.8-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +7 -0
  2. package/dist/assets/{AssistantView-Be0OKo5o.js → AssistantView-BjpY2u0c.js} +3 -3
  3. package/dist/assets/{DiagramView-Rpb6oenk.js → DiagramView-7j0sZC_P.js} +1 -1
  4. package/dist/assets/{GuiPluginSurface-DTH9jNDf.js → GuiPluginSurface-D_TK-2vZ.js} +1 -1
  5. package/dist/assets/MarkdownRenderer-B8zgOCfr.js +2 -0
  6. package/dist/assets/{MarkdownRendererImpl-CZ9lU4VJ.js → MarkdownRendererImpl-Dh7XVDLd.js} +1 -1
  7. package/dist/assets/{MarkstreamRendererImpl-DastQdu7.js → MarkstreamRendererImpl-D-qtRrvg.js} +1 -1
  8. package/dist/assets/{MobileDetailNavigation-CittPDZ0.js → MobileDetailNavigation-LkTVYLZX.js} +1 -1
  9. package/dist/assets/{MobileShareBridge-BxsoZnUJ.js → MobileShareBridge-CsTyKMtN.js} +1 -1
  10. package/dist/assets/{MobileTabPageHeader-BEgQ3L4u.js → MobileTabPageHeader-xz9RMXg4.js} +1 -1
  11. package/dist/assets/{MultiRunWindow-1o528NZE.js → MultiRunWindow-hMpjV7so.js} +1 -1
  12. package/dist/assets/{SettingsView-BGEaQC4R.js → SettingsView-D8qpss-X.js} +1 -1
  13. package/dist/assets/{SettingsWindow-MuJFADe3.js → SettingsWindow-B1VuFkFq.js} +1 -1
  14. package/dist/assets/{TerminalView-CHDyibi_.js → TerminalView-CLcaJh2M.js} +1 -1
  15. package/dist/assets/{ToolOutputDialog-Bcry3eoE.js → ToolOutputDialog-BuZo3XvN.js} +1 -1
  16. package/dist/assets/{appThemeRegistry-CJoBy_eP.js → appThemeRegistry-B7sp1Hw8.js} +1 -1
  17. package/dist/assets/{capgoAdapter-_oWtDrgf.js → capgoAdapter-vxOdqloD.js} +1 -1
  18. package/dist/assets/{fileMentionTouchSelection-7KLhnK1O.js → fileMentionTouchSelection-DspnKU8D.js} +1 -1
  19. package/dist/assets/{gitApi-BEXddXMX.js → gitApi-BLYdWaG8.js} +1 -1
  20. package/dist/assets/{insertionBoundaries-HkddYmJd.js → insertionBoundaries-DqlfZVY9.js} +1 -1
  21. package/dist/assets/{main-BKkCvf3L.js → main-DA7z198b.js} +2 -2
  22. package/dist/assets/{main-CXE9lij2.js → main-Qw23QJ7L.js} +4 -4
  23. package/dist/assets/{mcpQueries-xfKOWrAa.js → mcpQueries-C6Tu2cF3.js} +1 -1
  24. package/dist/assets/{miniChat-BKr-HXzy.js → miniChat-HafcB3H-.js} +2 -2
  25. package/dist/assets/{mobile-CGL4wWLz.js → mobile-DwXoGpxm.js} +2 -2
  26. package/dist/assets/{mobileBackNavigation-VzxRWLxN.js → mobileBackNavigation-9MR5h5K6.js} +1 -1
  27. package/dist/assets/{multirun-BmF58wXR.js → multirun-D-je_w02.js} +1 -1
  28. package/dist/assets/{native-config-CYjStyIM.js → native-config-Bb3pPQPD.js} +1 -1
  29. package/dist/assets/{projectMeta-DhdEWvmC.js → projectMeta-DaCyZW_D.js} +1 -1
  30. package/dist/assets/{readiness-uM7foMQ8.js → readiness-BHqz_NPS.js} +1 -1
  31. package/dist/assets/{renderElectronMiniChatApp-CYjZYsCZ.js → renderElectronMiniChatApp-COaMALRh.js} +2 -2
  32. package/dist/assets/{renderMobileApp-Dy2bPXrM.js → renderMobileApp-BOGntDSu.js} +4 -4
  33. package/dist/assets/{runtimeConfig-Cjjf4017.js → runtimeConfig-BiSluBXe.js} +1 -1
  34. package/dist/assets/{runtimeEndpointReset-CNyugOcU.js → runtimeEndpointReset-CJwlI_R-.js} +3 -3
  35. package/dist/assets/{sessionChangeSummary-5npOjhNG.js → sessionChangeSummary-BAv8zzro.js} +1 -1
  36. package/dist/assets/{sessionLookup-ClhS_rqE.js → sessionLookup-DOw7g15p.js} +1 -1
  37. package/dist/assets/{speechSettingsQueries-CpOY2X9w.js → speechSettingsQueries-B8zEN5QM.js} +1 -1
  38. package/dist/assets/types-BiP0jssb.js +2 -0
  39. package/dist/assets/{useAppFontEffects-BMXDDJtn.js → useAppFontEffects-De1qI6c-.js} +5 -5
  40. package/dist/assets/{useDesktopWindowControlsLayout-l2q0zXMx.js → useDesktopWindowControlsLayout-BzXi6Wf1.js} +1 -1
  41. package/dist/assets/{useEffectiveDirectory-rDw8BJo1.js → useEffectiveDirectory-BcbBl_6y.js} +1 -1
  42. package/dist/assets/{useMobileNavigationStore-EmnPOl61.js → useMobileNavigationStore-DqDCVXO1.js} +3 -3
  43. package/dist/assets/{useWorkerHighlightedLines-up7t7cwh.js → useWorkerHighlightedLines-CDVleuma.js} +1 -1
  44. package/dist/index.html +5 -5
  45. package/dist/mini-chat.html +5 -5
  46. package/dist/mobile.html +5 -5
  47. package/package.json +9 -4
  48. package/server/index.js +3 -3
  49. package/server/lib/assistants/DOCUMENTATION.md +14 -0
  50. package/server/lib/assistants/contact-tools.js +145 -10
  51. package/server/lib/assistants/contact-tools.test.js +11 -2
  52. package/server/lib/assistants/harness.js +23 -16
  53. package/server/lib/assistants/harness.test.js +76 -23
  54. package/server/lib/assistants/memory.http.test.js +2 -2
  55. package/server/lib/assistants/routes.js +2 -3
  56. package/server/lib/assistants/service.js +66 -1
  57. package/server/lib/assistants/service.test.js +37 -0
  58. package/server/lib/llm/DOCUMENTATION.md +119 -161
  59. package/server/lib/llm/bridge-client.js +60 -0
  60. package/server/lib/llm/bridge-client.test.js +35 -0
  61. package/server/lib/llm/bridge-contract.js +24 -0
  62. package/server/lib/llm/bridge-plugin.bundle.js +1136 -0
  63. package/server/lib/llm/bridge-plugin.js +127 -0
  64. package/server/lib/llm/bridge-plugin.test.js +164 -0
  65. package/server/lib/llm/completions.js +43 -18
  66. package/server/lib/llm/completions.test.js +17 -4
  67. package/server/lib/llm/generate.js +43 -728
  68. package/server/lib/llm/generate.test.js +62 -1063
  69. package/server/lib/llm/routes.js +0 -2
  70. package/server/lib/opencode/feature-routes-runtime.js +1 -0
  71. package/server/lib/small-model/DOCUMENTATION.md +11 -17
  72. package/server/lib/small-model/index.js +5 -4
  73. package/dist/assets/MarkdownRenderer-Dk1A4sLM.js +0 -2
  74. package/dist/assets/types-C2ml30_A.js +0 -2
  75. package/server/lib/llm/temp-directory.js +0 -58
  76. package/server/lib/llm/temp-directory.test.js +0 -57
@@ -1,4 +1,5 @@
1
1
  import { Agent } from '@earendil-works/pi-agent-core';
2
+ import { randomUUID } from 'node:crypto';
2
3
  import { isContactSpokenPreamble, splitContactBubbles } from './bubbles.js';
3
4
  import {
4
5
  contactTurnClearedChatHistory,
@@ -11,6 +12,7 @@ import {
11
12
  formatRegisteredProjectsPrompt,
12
13
  MISSED_FENCE_RETRY_USER_TEXT,
13
14
  parseContactToolCalls,
15
+ parseContactNativeToolCalls,
14
16
  stripContactToolFences,
15
17
  } from './contact-tools.js';
16
18
  import {
@@ -107,6 +109,7 @@ export const CONTACT_SYSTEM_PROMPT = [
107
109
  'Send a progress message when it tells the user something they do not already know: a direction they may want to correct, a finding that matters, a blocker, or that the work will take a while. Skip messages that would only repeat the plan or narrate a step. Keep the final answer to the remaining outcome instead of repeating earlier updates.',
108
110
  'Public message protocol: put each user-facing progress message at the START of your response in its own yuri-message JSON fence, with a single-line JSON object {"text":"Your short message"}. Then emit the next tool call or final answer. A closed message fence is delivered immediately while you are still generating. Include only text intended for the user. Tool results are evidence for you to summarize in your own words; never copy their stock confirmation wording into your reply.',
109
111
  'Do not expose tool traces, Activity, or editor actions.',
112
+ 'To view, change, enable, or pause existing scheduled tasks (查看/修改/暂停定时任务), use list_scheduled_tasks and then update_scheduled_task with the returned projectID/taskID. schedule_task only creates new tasks.',
110
113
  'You have bash, read, write, and edit in the working directory. Use them for pwd, files, and shell. Never say you have no terminal or cannot read files. Ignore any temporary generator workspace in the environment.',
111
114
  'Understand natural language in any language, including Chinese: 开新对话 / 清除记忆 means new_conversation (LLM memory only, chat history stays), 清空聊天记录 means clear_chat_history (delete transcript), 找项目 means list_projects, 现有对话 means list_sessions, 查看助手设定 / 默认提示词 means get_assistant_settings (pass to="Name" for another assistant), 改默认提示词 / 设置人设 / 改某助手的默认提示词 means update_default_prompt (persists that assistant\'s settings, later turns only; pass to="OpenCode 配置助手" to edit another contact without changing this one), 建助理 means create_assistant, 建会话 / 开个新会话 / 继续会话 means assign_session, 监听会话 means watch_session, 停止/取消/打断会话 means stop_session, 插话 means steer_session, 归档会话 means archive_session, 删除会话 means delete_session, 排定时任务 means schedule_task, 给 X 说一声 means message_assistant, 发卡片 means emit a card via those tools — never ask the user to type /card or /dm.',
112
115
  'You receive the registered project catalog every turn. Match the user goal against project labels and paths and existing OpenCode conversations via list_sessions. Start in the user-configured working directory; managed contacts start in the current server user home directory and can inspect user-global directories with read/bash. When the starting directory has no relevant session, walk its parent directories to find the nearest relevant existing OpenCode workspace using session directory metadata, then search that workspace for the requested project or conversation. Use an unscoped list_sessions lookup when broader context is needed. Prefer the user-configured directory and explicit session context; ask a short question when several relevant targets remain. Keep discovery bounded and use actual tool results as evidence.',
@@ -369,6 +372,7 @@ export function createContactStreamFn(createChatCompletion, {
369
372
  turnMessageStart = 0,
370
373
  variant = null,
371
374
  allowSilent = false,
375
+ cacheKey = randomUUID(),
372
376
  } = {}) {
373
377
  let callSequence = 0;
374
378
  const turnStart = Number.isFinite(Number(turnMessageStart)) ? Math.max(0, Number(turnMessageStart)) : 0;
@@ -403,14 +407,9 @@ export function createContactStreamFn(createChatCompletion, {
403
407
  }];
404
408
  }
405
409
  if (message.role === 'assistant') {
406
- const content = (message.content || []).map((part) => {
407
- if (part?.type === 'text') return part.text;
408
- if (part?.type !== 'toolCall') return '';
409
- return '```yuri-tool\n' + JSON.stringify({
410
- id: part.id, name: part.name, arguments: part.arguments,
411
- }) + '\n```';
412
- }).filter(Boolean).join('\n\n');
413
- return content ? [{ role: 'assistant', content }] : [];
410
+ const content = (message.content || []).filter(part => part?.type === 'text').map(part => part.text).join('\n\n');
411
+ const calls = (message.content || []).filter(part => part?.type === 'toolCall').map(part => ({ id: part.id, type: 'function', function: { name: part.name, arguments: JSON.stringify(part.arguments) } }));
412
+ return content || calls.length ? [{ role: 'assistant', content, ...(calls.length ? { tool_calls: calls } : {}) }] : [];
414
413
  }
415
414
  if (message.role === 'toolResult') {
416
415
  const content = (message.content || [])
@@ -423,10 +422,7 @@ export function createContactStreamFn(createChatCompletion, {
423
422
  const callId = typeof message.toolCallId === 'string' && message.toolCallId.trim()
424
423
  ? message.toolCallId.trim()
425
424
  : (typeof message.id === 'string' && message.id.trim() ? message.id.trim() : '');
426
- const label = callId
427
- ? `Yuri tool result name=${toolName} call=${callId}`
428
- : `Yuri tool result name=${toolName}`;
429
- return [{ role: 'user', content: `${label}: ${JSON.stringify({ isError: message.isError === true, content })}` }];
425
+ return [{ role: 'tool', name: toolName, tool_call_id: callId, content: JSON.stringify({ isError: message.isError === true, content }) }];
430
426
  }
431
427
  return [];
432
428
  });
@@ -455,7 +451,7 @@ export function createContactStreamFn(createChatCompletion, {
455
451
  signal,
456
452
  timeoutMs: 0,
457
453
  retryEmptyTextUntilCancelled: true,
458
- textEnvelope: true,
454
+ cacheKey,
459
455
  body: {
460
456
  model: `${model.provider === 'yuri' ? '' : `${model.provider}/`}${model.id}`.replace(/^\//, '') || model.name,
461
457
  providerID: typeof model.name === 'string' && model.name.includes('/')
@@ -464,6 +460,7 @@ export function createContactStreamFn(createChatCompletion, {
464
460
  modelID: model.id,
465
461
  ...(variant ? { variant } : {}),
466
462
  messages: [...messages],
463
+ tools: (context.tools || []).map(tool => ({ type: 'function', function: { name: tool.name, description: tool.description || tool.name, parameters: JSON.parse(JSON.stringify(tool.parameters ?? { type: 'object', properties: {} })) } })),
467
464
  },
468
465
  onTextDelta: (delta) => {
469
466
  if (signal?.aborted) return;
@@ -473,6 +470,7 @@ export function createContactStreamFn(createChatCompletion, {
473
470
  if (typeof delta === 'string' && delta && typeof onTextDelta === 'function') onTextDelta(delta);
474
471
  },
475
472
  globalEventHub,
473
+ validateToolCalls: false,
476
474
  });
477
475
  signal?.throwIfAborted();
478
476
  text = result?.completion?.choices?.[0]?.message?.content ?? result?.text ?? '';
@@ -488,7 +486,12 @@ export function createContactStreamFn(createChatCompletion, {
488
486
  silent = finalResponse?.status === 'silent';
489
487
  finalText = finalResponse?.text ?? null;
490
488
  // A final answer is opaque text; quoted tool examples in it cannot run.
491
- parsed = finalText === null ? parseContactToolCalls(text, allowedNames) : { toolCalls: [], chatText: finalText };
489
+ const nativeCalls = result?.completion?.choices?.[0]?.message?.tool_calls ?? [];
490
+ parsed = nativeCalls.length ? {
491
+ ...parseContactNativeToolCalls(nativeCalls, allowedNames),
492
+ chatText: text,
493
+ ...(finalText !== null ? { protocolError: 'Do not mix native tool calls with a final declaration.' } : {}),
494
+ } : finalText === null ? parseContactToolCalls(text, allowedNames) : { toolCalls: [], chatText: finalText };
492
495
  const mixedBatch = parsed.toolCalls.length > 1 && parsed.toolCalls.some((call) => !isPiCodingToolName(call.name));
493
496
  const malformedFinal = finalText === null && /```yuri-final/u.test(parsed.chatText);
494
497
  const skippedRejectedWork = rejectedCodingCalls.length > 0 && finalResponse?.status === 'complete';
@@ -517,7 +520,7 @@ export function createContactStreamFn(createChatCompletion, {
517
520
  if (parsed.toolCalls.length > 0) {
518
521
  const toolCalls = parsed.toolCalls.map((call) => ({
519
522
  type: 'toolCall',
520
- id: `call_${Date.now().toString(36)}_${++callSequence}`,
523
+ id: call.id || `call_${Date.now().toString(36)}_${++callSequence}`,
521
524
  name: call.name,
522
525
  arguments: call.arguments,
523
526
  }));
@@ -659,7 +662,7 @@ export async function runContactTurn({
659
662
  const modelID = assistant.modelID;
660
663
  const cwd = resolveAssistantCwd(assistant);
661
664
  const contactTools = Array.isArray(tools)
662
- ? tools.filter((tool) => tool && typeof tool.name === 'string' && !isPiCodingToolName(tool.name) && (!readOnly || ['list_projects', 'list_sessions', 'read_session', 'get_assistant_settings', 'search_memory', 'read_memory'].includes(tool.name)))
665
+ ? tools.filter((tool) => tool && typeof tool.name === 'string' && !isPiCodingToolName(tool.name) && (!readOnly || ['list_projects', 'list_sessions', 'read_session', 'list_scheduled_tasks', 'get_assistant_settings', 'search_memory', 'read_memory'].includes(tool.name)))
663
666
  : [];
664
667
  let runtime = null;
665
668
  let removeAbortListener = null;
@@ -682,6 +685,7 @@ export async function runContactTurn({
682
685
  formatContactToolsPrompt(contactTools),
683
686
  assistant.defaultPrompt,
684
687
  codingTools.length > 0 ? WORKSPACE_RESPONSE_PROTOCOL : '',
688
+ 'Tool transport: invoke the provided native function tools. Do not encode tool calls as yuri-tool fences; those examples describe arguments only. Keep yuri-message progress and yuri-final declarations as text. Actual tool results arrive in tool-role messages, never manufacture them.',
685
689
  ].filter((value) => typeof value === 'string' && value.trim()).join('\n\n')
686
690
  .replaceAll('{{LANGUAGE}}', resolveContactLanguage(language));
687
691
  const model = createContactModel(providerID, modelID);
@@ -706,6 +710,7 @@ export async function runContactTurn({
706
710
  : [];
707
711
  // Fixed turn boundary: every completion and missed-tool retry continues bubble indices from here.
708
712
  const turnMessageStart = prior.length;
713
+ const cacheKey = `yuri-contact-${assistant.id || randomUUID()}`;
709
714
 
710
715
  const agent = new AgentImpl({
711
716
  toolExecution: 'sequential',
@@ -726,6 +731,7 @@ export async function runContactTurn({
726
731
  signal,
727
732
  turnMessageStart,
728
733
  allowSilent,
734
+ cacheKey,
729
735
  }),
730
736
  });
731
737
 
@@ -789,6 +795,7 @@ export async function runContactTurn({
789
795
  signal,
790
796
  globalEventHub,
791
797
  onBubbleDelta: reset ? null : onBubbleDelta,
798
+ cacheKey,
792
799
  })(model, {
793
800
  systemPrompt: 'Reply briefly in the language of the user\'s messages, honoring explicit language requests. Use the conversation language, never the app interface locale or tool-result language. Summarize the supplied actual operation result in your own natural words. Tool result text is internal evidence. Keep private diagnostics and stock confirmation wording out of your reply. Report a failure honestly. The operation has already run; this pass only communicates its result.',
794
801
  messages: summaryMessages,
@@ -18,8 +18,66 @@ import {
18
18
  } from './harness.js'
19
19
  import { PI_CODING_TOOL_NAMES } from './pi-tools.js'
20
20
  import { createChatCompletion as gatewayCompletion } from '../llm/completions.js'
21
+ import { generateOpenCodeText } from '../llm/generate.js'
21
22
 
22
23
  describe('createContactStreamFn', () => {
24
+ it('offers scheduled-task lookup but no mutation or shell tools in read-only turns', async () => {
25
+ const seen = [];
26
+ const tools = createContactTools({ listScheduledTasks: vi.fn(), updateScheduledTask: vi.fn() });
27
+ await runContactTurn({ assistant: { providerID: 'p', modelID: 'm' }, history: [], userText: '后台复盘', tools, readOnly: true,
28
+ createChatCompletion: async ({ body }) => { seen.push(...body.tools.map(tool => tool.function.name)); return { text: '已检查。' }; },
29
+ });
30
+ expect(seen).toContain('list_scheduled_tasks');
31
+ expect(seen).not.toContain('update_scheduled_task');
32
+ expect(seen).not.toContain('bash');
33
+ });
34
+ it('runs scheduled-task listing and updating through native schemas and the real pi loop', async () => {
35
+ const listScheduledTasks = vi.fn(async () => ({ tasks: [{ id: 'task1', projectID: 'project1' }] }));
36
+ const updateScheduledTask = vi.fn(async () => ({ task: { id: 'task1', name: 'Task', schedule: { kind: 'daily', times: ['09:00'] }, execution: { providerID: 'p', modelID: 'm' } } }));
37
+ const tools = createContactTools({ listScheduledTasks, updateScheduledTask });
38
+ let round = 0;
39
+ const completion = input => gatewayCompletion({ ...input,
40
+ loadCatalog: async () => ({ models: [{ providerID: 'p', modelID: 'm' }] }),
41
+ generateText: async ({ messages, tools: schemas }) => {
42
+ expect(schemas.map(tool => tool.name)).toEqual(expect.arrayContaining(['list_scheduled_tasks', 'update_scheduled_task']));
43
+ round++;
44
+ if (round === 1) return { text: '', toolCalls: [{ id: 'list1', name: 'list_scheduled_tasks', arguments: {} }] };
45
+ expect(messages.some(message => message.role === 'tool' && message.tool_call_id === 'list1')).toBe(true);
46
+ if (round === 2) return { text: '', toolCalls: [{ id: 'update1', name: 'update_scheduled_task', arguments: { taskID: 'task1', projectID: 'project1', model: 'p/m' } }] };
47
+ return { text: '```yuri-final\n{"status":"complete","text":"任务已更新。"}\n```', toolCalls: [] };
48
+ },
49
+ });
50
+ const result = await runContactTurn({ assistant: { providerID: 'p', modelID: 'm' }, history: [], userText: '修改定时任务的模型', tools, createChatCompletion: completion });
51
+ expect(result.text).toBe('任务已更新。');
52
+ expect(listScheduledTasks).toHaveBeenCalledTimes(1);
53
+ expect(updateScheduledTask).toHaveBeenCalledExactlyOnceWith({ taskID: 'task1', projectID: 'project1', model: 'p/m' });
54
+ expect(round).toBe(3);
55
+ });
56
+ it('normalizes native shell aliases through the production gateway and preserves call identity', async () => {
57
+ const completion = input => gatewayCompletion({ ...input,
58
+ loadCatalog: async () => ({ models: [{ providerID: 'p', modelID: 'm' }] }),
59
+ generateText: async () => ({ text: '', toolCalls: [{ id: 'native_alias', name: 'grep', arguments: { pattern: 'needle', path: 'src' } }] }),
60
+ });
61
+ const result = await createContactStreamFn(completion)(
62
+ { name: 'p/m', id: 'm', provider: 'yuri', api: 'openai-completions' },
63
+ { messages: [{ role: 'user', content: 'Find needle in src' }], tools: [{ name: 'bash', parameters: { type: 'object', properties: { command: { type: 'string' } } } }] },
64
+ ).result();
65
+ expect(result.content.at(-1)).toMatchObject({ type: 'toolCall', id: 'native_alias', name: 'bash', arguments: { command: expect.stringContaining("-e 'needle' 'src'") } });
66
+ });
67
+
68
+ it('corrects unavailable native tools with actionable tool names', async () => {
69
+ const completion = vi.fn()
70
+ .mockResolvedValueOnce({ completion: { choices: [{ message: { content: '', tool_calls: [{ id: 'bad', function: { name: 'list_cron', arguments: '{}' } }] } }] } })
71
+ .mockResolvedValueOnce({ completion: { choices: [{ message: { content: '', tool_calls: [{ id: 'good', function: { name: 'list_scheduled_tasks', arguments: '{}' } }] } }] } });
72
+ const result = await createContactStreamFn(completion)(
73
+ { name: 'p/m', id: 'm', provider: 'yuri', api: 'openai-completions' },
74
+ { messages: [], tools: [{ name: 'list_scheduled_tasks' }] },
75
+ ).result();
76
+ expect(completion).toHaveBeenCalledTimes(2);
77
+ expect(JSON.stringify(completion.mock.calls[1][0].body.messages)).toContain('list_cron');
78
+ expect(JSON.stringify(completion.mock.calls[1][0].body.messages)).toContain('list_scheduled_tasks');
79
+ expect(result.content.at(-1)).toMatchObject({ type: 'toolCall', id: 'good', name: 'list_scheduled_tasks' });
80
+ });
23
81
  it('continues eight real Agent tool rounds through gateway recovery without replaying completed tools', async () => {
24
82
  vi.useFakeTimers()
25
83
  try {
@@ -27,26 +85,21 @@ describe('createContactStreamFn', () => {
27
85
  const tools = createContactTools({ readAssistantSettings: getAssistantSettings, currentAssistant: { id: 'a', name: 'Fixture' } })
28
86
  let round = 0
29
87
  const attempts = new Map()
30
- const remove = vi.fn(async () => {})
31
- const generate = vi.fn(async ({ sessionID, prompt }) => {
32
- const index = Number(sessionID.slice(4))
88
+ const generate = vi.fn(async ({ messages }) => {
89
+ const index = messages.filter(message => message.role === 'tool').length + 1
90
+ round = Math.max(round, index)
33
91
  const attempt = (attempts.get(index) || 0) + 1
34
92
  attempts.set(index, attempt)
35
- expect((prompt.match(/Yuri tool result name=get_assistant_settings call=/g) || []).length).toBe(index - 1)
93
+ expect(messages.filter(message => message.role === 'tool' && message.name === 'get_assistant_settings')).toHaveLength(index - 1)
36
94
  // More than the old three-attempt limit, and longer than its 90s deadline.
37
95
  if ((index === 3 && attempt <= 9) || (index === 4 && attempt <= 3)) return { text: '' }
38
- const text = index <= 8
39
- ? '```yuri-tool\n{"name":"get_assistant_settings","arguments":{}}\n```'
40
- : '```yuri-final\n{"status":"complete","text":"Verified all eight steps."}\n```'
41
- return { text: JSON.stringify({ text }) }
96
+ return index <= 8
97
+ ? { text: '', toolCalls: [{ id: `call_${index}`, name: 'get_assistant_settings', arguments: {} }], finishReason: 'tool-calls' }
98
+ : { text: '```yuri-final\n{"status":"complete","text":"Verified all eight steps."}\n```', toolCalls: [], finishReason: 'stop' }
42
99
  })
43
- const client = {
44
- agent: { get: async () => ({ data: { id: 'yuri-text', permissions: [{ action: '*', resource: '*', effect: 'deny' }] } }) },
45
- session: { create: async () => ({ id: `ses_${++round}` }), generate, remove, interrupt: vi.fn() },
46
- }
47
100
  const completion = (input) => gatewayCompletion({
48
101
  ...input, buildOpenCodeUrl: () => 'http://127.0.0.1:4096', getOpenCodeAuthHeaders: () => ({}),
49
- clientFactory: () => client, ensureTempDirectory: async () => '/tmp/yuri-text',
102
+ generateText: (input) => generateOpenCodeText({ ...input, generateCompletion: generate }),
50
103
  loadCatalog: async () => ({ models: [{ providerID: 'p', modelID: 'm' }] }),
51
104
  })
52
105
  const outcome = runContactTurn({
@@ -58,7 +111,6 @@ describe('createContactStreamFn', () => {
58
111
  expect(getAssistantSettings).toHaveBeenCalledTimes(8)
59
112
  expect(round).toBe(9)
60
113
  expect(generate).toHaveBeenCalledTimes(21)
61
- expect(remove).toHaveBeenCalledTimes(9)
62
114
  expect(vi.getTimerCount()).toBe(0)
63
115
  } finally { vi.useRealTimers() }
64
116
  })
@@ -76,7 +128,8 @@ describe('createContactStreamFn', () => {
76
128
  expect(completion.mock.calls.length).toBeGreaterThan(0);
77
129
  for (const [request] of completion.mock.calls) {
78
130
  expect(request.body.variant).toBe('high');
79
- expect(request).toMatchObject({ timeoutMs: 0, retryEmptyTextUntilCancelled: true, textEnvelope: true });
131
+ expect(request).toMatchObject({ timeoutMs: 0, retryEmptyTextUntilCancelled: true });
132
+ expect(typeof request.cacheKey).toBe('string');
80
133
  }
81
134
  expect(result.bubbles).toEqual(['已完成。']);
82
135
  expect(JSON.stringify(onBubbleDelta.mock.calls)).not.toContain('Private reasoning');
@@ -128,7 +181,7 @@ describe('createContactStreamFn', () => {
128
181
  currentAssistant: { id: 'a', name: 'Config' },
129
182
  })
130
183
  const completion = vi.fn(async ({ body }) => {
131
- const result = body.messages.find((m) => m.content.includes('Yuri tool result name=update_default_prompt'))
184
+ const result = body.messages.find((m) => m.role === 'tool' && m.name === 'update_default_prompt')
132
185
  if (result) {
133
186
  expect(result.content).toContain('Default prompt saved.')
134
187
  return { text: '```yuri-final\n{"status":"complete","text":"提示词已保存,接下来的对话会按这个设置回复。"}\n```' }
@@ -233,7 +286,7 @@ describe('createContactStreamFn', () => {
233
286
  expect(system).toContain('small, clearly scoped configuration changes directly')
234
287
  expect(system).toContain('walk its parent directories')
235
288
  expect(system).toContain('Look up existing OpenCode conversations with list_sessions')
236
- const result = body.messages.find((message) => typeof message.content === 'string' && message.content.includes('tool result name=read'))
289
+ const result = body.messages.find((message) => message.role === 'tool' && message.name === 'read')
237
290
  if (result) {
238
291
  expect(result.content).toContain('configured value')
239
292
  return { completion: { choices: [{ message: { content: '```yuri-final\n{"status":"complete","text":"configured value"}\n```' } }] } }
@@ -607,7 +660,7 @@ describe('runContactTurn', () => {
607
660
  expect(result.text).toBe(example)
608
661
  expect(createChatCompletion).toHaveBeenCalledTimes(3)
609
662
  const messages = createChatCompletion.mock.calls[1][0].body.messages
610
- const emptyResult = messages.find((message) => message.content.includes('tool result name=bash'))
663
+ const emptyResult = messages.find((message) => message.role === 'tool' && message.name === 'bash')
611
664
  expect(emptyResult).toBeTruthy()
612
665
  expect(emptyResult.content).toContain('"isError":false')
613
666
  } finally {
@@ -639,11 +692,11 @@ describe('runContactTurn', () => {
639
692
  expect(result.text).toBe('已写入并验证。')
640
693
  expect(createChatCompletion).toHaveBeenCalledTimes(4)
641
694
  const lastRequest = createChatCompletion.mock.calls.at(-1)[0].body.messages
642
- const calls = lastRequest.filter((m) => m.role === 'assistant').map((m) => m.content).join('\n')
695
+ const calls = JSON.stringify(lastRequest.filter((m) => m.role === 'assistant'))
643
696
  expect(calls).toContain('"name":"read"')
644
697
  expect(calls).toContain('"name":"write"')
645
- expect(calls).toContain('"path":"result.txt"')
646
- const results = lastRequest.filter((m) => m.role === 'user' && m.content.includes('tool result name='))
698
+ expect(lastRequest.flatMap(message => message.tool_calls ?? []).map(call => JSON.parse(call.function.arguments))).toContainEqual(expect.objectContaining({ path: 'result.txt' }))
699
+ const results = lastRequest.filter((m) => m.role === 'tool')
647
700
  expect(results).toHaveLength(3)
648
701
  expect(results.at(-1).content).toContain('verified note')
649
702
  expect(onBubbleDelta.mock.calls.map((call) => call[1]).join('')).not.toContain('我先')
@@ -744,7 +797,7 @@ describe('runContactTurn', () => {
744
797
  // Tool call/result association: after read, the next completion sees a named tool result.
745
798
  const secondMessages = createChatCompletion.mock.calls[1][0].body.messages
746
799
  const toolResultTurn = secondMessages.find((message) => (
747
- message.role === 'user' && typeof message.content === 'string' && message.content.includes('tool result name=read')
800
+ message.role === 'tool' && message.name === 'read'
748
801
  ))
749
802
  expect(toolResultTurn).toBeTruthy()
750
803
  expect(toolResultTurn.content).toMatch(/Read project docs|documentation/i)
@@ -814,7 +867,7 @@ describe('runContactTurn', () => {
814
867
  }
815
868
  const last = body.messages.at(-1)
816
869
  const lastText = typeof last?.content === 'string' ? last.content : ''
817
- if (lastText.includes('tool result name=list_projects') || lastText.includes('Registered projects')) {
870
+ if (body.messages.at(-1)?.name === 'list_projects' || lastText.includes('Registered projects')) {
818
871
  return {
819
872
  completion: {
820
873
  choices: [{
@@ -23,9 +23,9 @@ const listen = async (app) => {
23
23
  const final = (text) => ({ text: '```yuri-final\n' + JSON.stringify({ status: 'complete', text }) + '\n```' });
24
24
  const call = (name, args) => ({ text: '```yuri-tool\n' + JSON.stringify({ name, arguments: args }) + '\n```' });
25
25
  const resultFor = (body, name) => {
26
- const row = body.messages.findLast((m) => m.content?.startsWith(`Yuri tool result name=${name} `));
26
+ const row = body.messages.findLast((m) => m.role === 'tool' && m.name === name);
27
27
  if (!row) return null;
28
- return JSON.parse(row.content.slice(row.content.indexOf(': ') + 2));
28
+ return JSON.parse(row.content);
29
29
  };
30
30
  const setup = async (existingDirectory = null) => {
31
31
  const directory = existingDirectory || fs.mkdtempSync(path.join(os.tmpdir(), 'yuri-memory-http-'));
@@ -1,7 +1,6 @@
1
1
  import { AssistantError, createAssistantsService } from './service.js';
2
2
  import { isSafeInlineImageMime } from './contact-attachments.js';
3
3
  import { createChatCompletion } from '../llm/completions.js';
4
- import { ensureLlmTempDirectory } from '../llm/temp-directory.js';
5
4
  import { setAssignedSessionSettleHandler } from '../session-goal/runtime.js';
6
5
  import { makeOpenCodeV2Client } from '../opencode/v2-client.js';
7
6
 
@@ -17,8 +16,7 @@ export const registerAssistantRoutes = (app, dependencies) => {
17
16
  baseUrl: dependencies.buildOpenCodeUrl('/', '').replace(/\/$/, ''),
18
17
  authHeaders: dependencies.getOpenCodeAuthHeaders(),
19
18
  }),
20
- ensureTempDirectory: ensureLlmTempDirectory,
21
- // Attachment-session generate may subscribe for session.text.delta (contact harness).
19
+ // Contact activity continues through the existing event hub; inference executes no OpenCode tools.
22
20
  globalEventHub: input?.globalEventHub ?? dependencies.globalEventHub,
23
21
  persistSessionMetadata: dependencies.persistSessionMetadata,
24
22
  onSystemSessionPersisted: dependencies.onSystemSessionPersisted,
@@ -35,6 +33,7 @@ export const registerAssistantRoutes = (app, dependencies) => {
35
33
  listScheduledTasks: dependencies.listScheduledTasks,
36
34
  sessionIndexService: dependencies.sessionIndexService,
37
35
  upsertScheduledTask: dependencies.upsertScheduledTask,
36
+ patchScheduledTask: dependencies.patchScheduledTask,
38
37
  syncScheduledTaskProject: dependencies.syncScheduledTaskProject,
39
38
  globalEventHub: dependencies.globalEventHub,
40
39
  onRevisionTip: dependencies.onRevisionTip,
@@ -60,6 +60,7 @@ import {
60
60
  normalizeConnectedModels,
61
61
  normalizeRegisteredProjects,
62
62
  sanitizeRegisteredProject,
63
+ summarizeScheduledTask,
63
64
  } from './contact-tools.js';
64
65
  import {
65
66
  AssignError,
@@ -236,7 +237,7 @@ const awaitWithDeadline = async (work, ms = CONTACT_CATALOG_DEADLINE_MS, code =
236
237
  }
237
238
  };
238
239
 
239
- export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, getOpenCodeAuthHeaders, getServerId = async () => null, getAllowedRoots = () => [], listProjects = async () => [], readModelPreferences = async () => null, listScheduledTasks = null, sessionIndexService = null, upsertScheduledTask = 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 } = {}) => {
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 } = {}) => {
240
241
  if (!dbPath || !dataDir) return null;
241
242
  const Database = require('better-sqlite3');
242
243
  fs.mkdirSync(path.dirname(dbPath), { recursive: true });
@@ -2489,6 +2490,66 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
2489
2490
  prompt: upserted?.task?.execution?.prompt || params.prompt,
2490
2491
  };
2491
2492
  };
2493
+ const listScheduledTaskWork = async (params = {}) => {
2494
+ if (typeof listScheduledTasks !== 'function') throw new AssignError(ASSIGN_CODES.UPSTREAM, 'Listing scheduled tasks is unavailable.');
2495
+ const projects = normalizeRegisteredProjects(await listProjects());
2496
+ const scope = typeof params.projectPath === 'string' ? params.projectPath.trim() : '';
2497
+ const scoped = scope ? projects.filter((project) => project.id === scope || path.resolve(project.path) === path.resolve(scope)) : projects;
2498
+ if (scope && scoped.length === 0) throw new AssignError(ASSIGN_CODES.PROJECT_REQUIRED, 'No registered project matches that projectPath.');
2499
+ const query = typeof params.query === 'string' ? params.query.trim().toLowerCase() : '';
2500
+ const tasks = [];
2501
+ const failed = [];
2502
+ for (const project of scoped) {
2503
+ try {
2504
+ const listed = await listScheduledTasks(project.id);
2505
+ if (!Array.isArray(listed)) throw new Error('Invalid scheduled task list');
2506
+ for (const task of listed) {
2507
+ const summary = { ...summarizeScheduledTask(task, project.id), projectPath: project.path };
2508
+ if (query && !JSON.stringify([summary.id, summary.name, summary.providerID, summary.modelID, task?.execution?.prompt]).toLowerCase().includes(query)) continue;
2509
+ tasks.push(summary);
2510
+ }
2511
+ } catch {
2512
+ // One unreadable project must not hide the others.
2513
+ failed.push({ projectID: project.id, projectPath: project.path });
2514
+ }
2515
+ }
2516
+ return { tasks, ...(failed.length > 0 ? { partial: true, failed } : {}) };
2517
+ };
2518
+ const updateScheduledTaskWork = async (row, params, signal) => {
2519
+ signal?.throwIfAborted();
2520
+ if (typeof patchScheduledTask !== 'function') throw new AssignError(ASSIGN_CODES.UPSTREAM, 'Updating a scheduled task is unavailable.');
2521
+ const projects = normalizeRegisteredProjects(await listProjects());
2522
+ if (!projects.some((project) => project.id === params.projectID)) throw new AssignError(ASSIGN_CODES.PROJECT_REQUIRED, 'projectID must be a registered project from list_scheduled_tasks.');
2523
+ const execution = {};
2524
+ if (typeof params.prompt === 'string' && params.prompt.trim()) execution.prompt = params.prompt;
2525
+ if (params.providerID || params.modelID || params.model) {
2526
+ const workerModel = resolveAssignWorkerModel({ providerID: params.providerID, modelID: params.modelID, model: params.model,
2527
+ fallback: { providerID: row.provider_id, modelID: row.model_id }, catalog: await loadAssignCatalog(signal) });
2528
+ execution.providerID = workerModel.providerID;
2529
+ execution.modelID = workerModel.modelID;
2530
+ }
2531
+ const schedule = {};
2532
+ for (const key of ['kind', 'time', 'timezone', 'date', 'cron']) {
2533
+ if (typeof params[key] === 'string' && params[key].trim()) schedule[key] = params[key].trim();
2534
+ }
2535
+ if (typeof params.weekdays === 'string' && params.weekdays.trim()) schedule.weekdays = params.weekdays.split(',').map((item) => Number(item.trim())).filter((item) => Number.isInteger(item));
2536
+ if (schedule.time) schedule.times = [schedule.time];
2537
+ const patch = {
2538
+ ...(typeof params.name === 'string' && params.name.trim() ? { name: params.name.trim() } : {}),
2539
+ ...(params.enabled === 'true' || params.enabled === true ? { enabled: true } : {}),
2540
+ ...(params.enabled === 'false' || params.enabled === false ? { enabled: false } : {}),
2541
+ ...(Object.keys(schedule).length > 0 ? { schedule } : {}),
2542
+ ...(Object.keys(execution).length > 0 ? { execution } : {}),
2543
+ };
2544
+ if (Object.keys(patch).length === 0) throw new AssignError(ASSIGN_CODES.VALIDATION, 'update_scheduled_task needs at least one field to change.');
2545
+ signal?.throwIfAborted();
2546
+ const patched = await patchScheduledTask(params.projectID, params.taskID, patch);
2547
+ if (!patched?.task) throw new AssignError(ASSIGN_CODES.VALIDATION, 'Scheduled task not found. Use an exact taskID from list_scheduled_tasks.');
2548
+ if (typeof syncScheduledTaskProject === 'function') {
2549
+ try { await syncScheduledTaskProject(params.projectID); } catch { /* The saved config stays authoritative; the scheduler reloads it on its next sync. */ }
2550
+ }
2551
+ return { task: patched.task, projectID: params.projectID };
2552
+ };
2492
2553
  const listSessionsFromIndex = (params = {}) => {
2493
2554
  if (!sessionIndexService || typeof sessionIndexService.snapshot !== 'function') {
2494
2555
  throw new AssignError(ASSIGN_CODES.UPSTREAM, 'Session index is unavailable.');
@@ -2867,6 +2928,8 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
2867
2928
  deleteSession: (params) => mutateSessionWork('delete', params),
2868
2929
  createAssistant: (toolInput) => createAssistant(toolInput),
2869
2930
  scheduleTask: (params) => scheduleWork(live, params),
2931
+ listScheduledTasks: (params) => listScheduledTaskWork(params),
2932
+ updateScheduledTask: (params) => updateScheduledTaskWork(live, params, controller.signal),
2870
2933
  deliverPeerMessage: (toolInput) => deliverPeerMessage(assistantID, toolInput),
2871
2934
  clearContactMemory: () => {
2872
2935
  const result = clearContactMemory(assistantID, {});
@@ -3224,6 +3287,8 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
3224
3287
  deleteSession: (params) => mutateSessionWork('delete', params),
3225
3288
  createAssistant: (toolInput) => createAssistant(toolInput),
3226
3289
  scheduleTask: (params) => scheduleWork(row, params),
3290
+ listScheduledTasks: (params) => listScheduledTaskWork(params),
3291
+ updateScheduledTask: (params) => updateScheduledTaskWork(row, params, controller.signal),
3227
3292
  deliverPeerMessage: (toolInput) => deliverPeerMessage(row.assistant_id, toolInput),
3228
3293
  clearContactMemory: () => {
3229
3294
  // Cap the watermark at this turn's user ordinal — never global MAX,
@@ -3190,6 +3190,43 @@ describe('assistants service', () => {
3190
3190
  service.close();
3191
3191
  });
3192
3192
 
3193
+ it('lists scheduled tasks with partial failures and updates only the requested model', async () => {
3194
+ const directory = root();
3195
+ const patches = [];
3196
+ const synced = [];
3197
+ const task = { id: 'task_a', name: 'Weekly', enabled: true, schedule: { kind: 'daily', times: ['09:00'] }, execution: { prompt: 'review notes', providerID: 'old', modelID: 'old-model' } };
3198
+ let listed;
3199
+ let missing;
3200
+ let updated;
3201
+ const service = setup(directory, {
3202
+ provider: { list: async () => ({ data: [{ id: 'new-provider' }] }) },
3203
+ model: { list: async () => ({ data: [{ providerID: 'new-provider', id: 'new-model' }] }) },
3204
+ }, {
3205
+ listProjects: async () => [{ id: 'proj_a', path: directory }, { id: 'proj_bad', path: path.join(directory, 'bad') }],
3206
+ listScheduledTasks: async (projectID) => { if (projectID === 'proj_bad') throw new Error('unreadable'); return [task]; },
3207
+ patchScheduledTask: async (projectID, taskID, patch) => {
3208
+ patches.push({ projectID, taskID, patch });
3209
+ return { task: { ...task, execution: { ...task.execution, ...patch.execution } } };
3210
+ },
3211
+ syncScheduledTaskProject: async (projectID) => { synced.push(projectID); },
3212
+ runContactTurn: async ({ tools }) => {
3213
+ listed = await tools.find(tool => tool.name === 'list_scheduled_tasks').execute('call_list', {});
3214
+ const update = tools.find(tool => tool.name === 'update_scheduled_task');
3215
+ missing = await update.execute('call_missing', { projectID: 'proj_a', taskID: 'task_a', model: 'missing/not-real' });
3216
+ updated = await update.execute('call_update', { projectID: 'proj_a', taskID: 'task_a', model: 'new-provider/new-model' });
3217
+ return { text: 'done', bubbles: ['done'], cards: [updated.details.card], tools };
3218
+ },
3219
+ });
3220
+ const host = service.createAssistant(assistantInput);
3221
+ await settleSend(service, host.id, { messageID: 'client_update_schedule', parts: [{ type: 'text', text: '修改定时任务模型' }] });
3222
+ expect(listed.details).toMatchObject({ tasks: [{ id: 'task_a', projectID: 'proj_a' }], partial: true, failed: [{ projectID: 'proj_bad' }] });
3223
+ expect(missing.details.error).toBe('model_not_found');
3224
+ expect(patches).toEqual([{ projectID: 'proj_a', taskID: 'task_a', patch: { execution: { providerID: 'new-provider', modelID: 'new-model' } } }]);
3225
+ expect(synced).toEqual(['proj_a']);
3226
+ expect(updated.details.card).toMatchObject({ taskID: 'task_a' });
3227
+ service.close();
3228
+ });
3229
+
3193
3230
  it('creates a scheduled task from schedule_task and persists the schedule card', async () => {
3194
3231
  const directory = root();
3195
3232
  const upserts = [];