@yuriai/web 0.2.8-beta.2 → 0.2.8-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.
Files changed (92) hide show
  1. package/dist/assets/{AgentAvatar-MzDm6uBf.js → AgentAvatar--DsfGfhZ.js} +1 -1
  2. package/dist/assets/{AssistantView-BjpY2u0c.js → AssistantView-Bf19-qvJ.js} +3 -3
  3. package/dist/assets/{DiagramView-7j0sZC_P.js → DiagramView-UvYyjtWA.js} +1 -1
  4. package/dist/assets/{FadeInOnReveal-DkmfVoTO.js → FadeInOnReveal-NAFOww9Y.js} +1 -1
  5. package/dist/assets/{GuiPluginSurface-D_TK-2vZ.js → GuiPluginSurface-DNzJNcMh.js} +1 -1
  6. package/dist/assets/{GuiPluginWindow-dDG5Uyqb.js → GuiPluginWindow-C73klYx3.js} +1 -1
  7. package/dist/assets/{Icon-BjiyvtB2.js → Icon-Cy25fgQb.js} +1 -1
  8. package/dist/assets/{ImageLoadingPlaceholder-CUKFQTAG.js → ImageLoadingPlaceholder-DGRjdn_K.js} +1 -1
  9. package/dist/assets/{LoadingImage-B7cT_4Oe.js → LoadingImage-2pPdTFHh.js} +1 -1
  10. package/dist/assets/{MarkdownRenderer-B8zgOCfr.js → MarkdownRenderer-GuwP9qiJ.js} +2 -2
  11. package/dist/assets/{MarkdownRendererImpl-Dh7XVDLd.js → MarkdownRendererImpl-tHItN1IG.js} +1 -1
  12. package/dist/assets/{MarkstreamRendererImpl-D-qtRrvg.js → MarkstreamRendererImpl-Dh13e1UE.js} +1 -1
  13. package/dist/assets/{MobileDetailNavigation-LkTVYLZX.js → MobileDetailNavigation-CSxBgVuQ.js} +1 -1
  14. package/dist/assets/{MobileResizableSheet-C9YzOQis.js → MobileResizableSheet-BN07cmQQ.js} +1 -1
  15. package/dist/assets/{MobileShareBridge-CsTyKMtN.js → MobileShareBridge-7SAELdqu.js} +1 -1
  16. package/dist/assets/MobileTabPageHeader-Bbb36BtD.js +2 -0
  17. package/dist/assets/{MultiRunWindow-hMpjV7so.js → MultiRunWindow-DbI9KTph.js} +1 -1
  18. package/dist/assets/{OnboardingScreen-D6iQ5qjF.js → OnboardingScreen-rp0qwvgz.js} +1 -1
  19. package/dist/assets/{OverlayScrollbar-Dbx1atD-.js → OverlayScrollbar-B--v-oQW.js} +1 -1
  20. package/dist/assets/{SettingsView-D8qpss-X.js → SettingsView-C1AQoEIQ.js} +1 -1
  21. package/dist/assets/{SettingsWindow-B1VuFkFq.js → SettingsWindow-6M0ssWHM.js} +1 -1
  22. package/dist/assets/{TerminalView-CLcaJh2M.js → TerminalView-bhL6Ccen.js} +1 -1
  23. package/dist/assets/{ToolOutputDialog-BuZo3XvN.js → ToolOutputDialog-BaLKI3Yc.js} +1 -1
  24. package/dist/assets/{YuriLogo-DvRSd5NN.js → YuriLogo-kwLWc5Hi.js} +1 -1
  25. package/dist/assets/{appThemeRegistry-B7sp1Hw8.js → appThemeRegistry-Bk_N8btz.js} +1 -1
  26. package/dist/assets/{button-BSFWH-Ok.js → button-Dodw6LWV.js} +1 -1
  27. package/dist/assets/{capgoAdapter-vxOdqloD.js → capgoAdapter-DqHX7fkj.js} +1 -1
  28. package/dist/assets/{collapsible-DaevjAvt.js → collapsible-C9kOfVDe.js} +1 -1
  29. package/dist/assets/{diagram-7OgmyecX.js → diagram-CfBQ9Icg.js} +1 -1
  30. package/dist/assets/{dialog-D1pXn_b9.js → dialog-D0bq7nr2.js} +1 -1
  31. package/dist/assets/{dropdown-menu.styles-CGHPvEgD.js → dropdown-menu.styles-CLxDPSrk.js} +1 -1
  32. package/dist/assets/{es-DJzbuYpv.js → es-Diy_UpPF.js} +1 -1
  33. package/dist/assets/{fileMentionTouchSelection-DspnKU8D.js → fileMentionTouchSelection-C16Q21Ht.js} +1 -1
  34. package/dist/assets/{fr-YDYbYIZQ.js → fr-CPRTMaky.js} +1 -1
  35. package/dist/assets/{gitApi-BLYdWaG8.js → gitApi-_yKaBF0a.js} +1 -1
  36. package/dist/assets/{input-BhHXFla6.js → input-HddqDhRi.js} +1 -1
  37. package/dist/assets/{insertionBoundaries-DqlfZVY9.js → insertionBoundaries-CHqJLwJg.js} +1 -1
  38. package/dist/assets/{ja-SjX3NBJz.js → ja-Cc1jn0Ag.js} +1 -1
  39. package/dist/assets/{ko-BxcUEWjB.js → ko-CfHUuNNe.js} +1 -1
  40. package/dist/assets/{main-DA7z198b.js → main-Bja5DG1P.js} +2 -2
  41. package/dist/assets/{main-Qw23QJ7L.js → main-njE9rVzm.js} +4 -4
  42. package/dist/assets/{markdownHeightCache-DV2j4PlS.js → markdownHeightCache-BQiIj0aM.js} +1 -1
  43. package/dist/assets/{mcpQueries-C6Tu2cF3.js → mcpQueries-uM1Chfdc.js} +1 -1
  44. package/dist/assets/{miniChat-HafcB3H-.js → miniChat-DAwBa-3U.js} +2 -2
  45. package/dist/assets/{mobile-DwXoGpxm.js → mobile-BQmrdXmD.js} +2 -2
  46. package/dist/assets/{mobileBackNavigation-9MR5h5K6.js → mobileBackNavigation-DsU3qQ8W.js} +1 -1
  47. package/dist/assets/{multirun-D-je_w02.js → multirun-DRL1Wf-K.js} +1 -1
  48. package/dist/assets/{native-config-Bb3pPQPD.js → native-config-BMflOjo8.js} +1 -1
  49. package/dist/assets/{pl-vh0XFuDb.js → pl-mUyhvp8O.js} +1 -1
  50. package/dist/assets/{projectMeta-DaCyZW_D.js → projectMeta-DK-kl6vM.js} +1 -1
  51. package/dist/assets/{pt-BR-Cv5tssQz.js → pt-BR-D3E4Wxao.js} +1 -1
  52. package/dist/assets/{readiness-BHqz_NPS.js → readiness-CMHDs1YN.js} +1 -1
  53. package/dist/assets/{renderElectronMiniChatApp-COaMALRh.js → renderElectronMiniChatApp-CkSP0eQz.js} +2 -2
  54. package/dist/assets/{renderMobileApp-BOGntDSu.js → renderMobileApp-wELnHLDT.js} +4 -4
  55. package/dist/assets/{runtimeConfig-BiSluBXe.js → runtimeConfig-KpW0l510.js} +1 -1
  56. package/dist/assets/{runtimeEndpointReset-CJwlI_R-.js → runtimeEndpointReset-BBxpXfkE.js} +3 -3
  57. package/dist/assets/{scheduledTaskNavigation-BZ3B5bpN.js → scheduledTaskNavigation-CyPkVBKs.js} +1 -1
  58. package/dist/assets/{sessionChangeSummary-BAv8zzro.js → sessionChangeSummary-Bb7dqAie.js} +1 -1
  59. package/dist/assets/{sessionLookup-DOw7g15p.js → sessionLookup-D_P3C7rX.js} +1 -1
  60. package/dist/assets/{sortable-tabs-strip-BnTV_KYG.js → sortable-tabs-strip-C-qSUWlr.js} +1 -1
  61. package/dist/assets/{speechSettingsQueries-B8zEN5QM.js → speechSettingsQueries-BSBjx3wG.js} +1 -1
  62. package/dist/assets/src-CbY9YJrh.css +2 -0
  63. package/dist/assets/{store-CgQdmzpX.js → store-FxBFwq--.js} +2 -2
  64. package/dist/assets/{textarea-Deh9E1KP.js → textarea-BvfW0tsL.js} +1 -1
  65. package/dist/assets/{tooltip-DygQ-2xe.js → tooltip-BmKpb74n.js} +1 -1
  66. package/dist/assets/{types-BiP0jssb.js → types-rJezumB4.js} +1 -1
  67. package/dist/assets/{uk-3a9vdLJ-.js → uk-D9iQbGbr.js} +1 -1
  68. package/dist/assets/{useAppFontEffects-De1qI6c-.js → useAppFontEffects-DZ1W3_cy.js} +5 -5
  69. package/dist/assets/{useDesktopWindowControlsLayout-BzXi6Wf1.js → useDesktopWindowControlsLayout-D_1DLCOD.js} +1 -1
  70. package/dist/assets/{useEffectiveDirectory-BcbBl_6y.js → useEffectiveDirectory-joUiryc3.js} +1 -1
  71. package/dist/assets/{useMobileNavigationStore-DqDCVXO1.js → useMobileNavigationStore-BaQ7TIpx.js} +6 -6
  72. package/dist/assets/{useWorkerHighlightedLines-CDVleuma.js → useWorkerHighlightedLines-CiU1xPjX.js} +1 -1
  73. package/dist/assets/{zh-CN-kwaUr5W5.js → zh-CN-mNVX6pMK.js} +1 -1
  74. package/dist/assets/{zh-TW-BBs44W7l.js → zh-TW-B7T0e-Qv.js} +1 -1
  75. package/dist/index.html +6 -6
  76. package/dist/mini-chat.html +6 -6
  77. package/dist/mobile.html +6 -6
  78. package/package.json +1 -1
  79. package/server/lib/assistants/DOCUMENTATION.md +16 -16
  80. package/server/lib/assistants/bubbles.js +0 -14
  81. package/server/lib/assistants/bubbles.test.js +1 -18
  82. package/server/lib/assistants/contact-tools.js +64 -231
  83. package/server/lib/assistants/contact-tools.test.js +29 -164
  84. package/server/lib/assistants/harness.js +72 -237
  85. package/server/lib/assistants/harness.test.js +199 -280
  86. package/server/lib/assistants/memory.http.test.js +2 -2
  87. package/server/lib/assistants/pi-tools.js +1 -54
  88. package/server/lib/assistants/pi-tools.test.js +5 -9
  89. package/server/lib/assistants/service.test.js +23 -42
  90. package/server/lib/scheduled-tasks/runtime.test.js +3 -3
  91. package/dist/assets/MobileTabPageHeader-xz9RMXg4.js +0 -2
  92. package/dist/assets/src-NlrSCyPZ.css +0 -2
@@ -1,6 +1,6 @@
1
1
  import { Agent } from '@earendil-works/pi-agent-core';
2
2
  import { randomUUID } from 'node:crypto';
3
- import { isContactSpokenPreamble, splitContactBubbles } from './bubbles.js';
3
+ import { splitContactBubbles } from './bubbles.js';
4
4
  import {
5
5
  contactTurnClearedChatHistory,
6
6
  contactTurnHasSuccessfulReset,
@@ -10,10 +10,13 @@ import {
10
10
  formatContactToolsPrompt,
11
11
  formatConnectedModelsPrompt,
12
12
  formatRegisteredProjectsPrompt,
13
+ createNotifyUserTool,
14
+ createStaySilentTool,
13
15
  MISSED_FENCE_RETRY_USER_TEXT,
14
- parseContactToolCalls,
16
+ NOTIFY_USER_MAX_CHARS,
17
+ NOTIFY_USER_TOOL_NAME,
15
18
  parseContactNativeToolCalls,
16
- stripContactToolFences,
19
+ STAY_SILENT_TOOL_NAME,
17
20
  } from './contact-tools.js';
18
21
  import {
19
22
  createPiCodingRuntime,
@@ -107,7 +110,7 @@ export const CONTACT_SYSTEM_PROMPT = [
107
110
  'Reply in the language of the user\'s messages, unless they explicitly request another language. Infer it from their latest substantive message and conversation context, never from the app interface locale. For ambiguous messages or background follow-ups, continue the established conversation language.',
108
111
  'Keep private reasoning and tool traces private.',
109
112
  '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.',
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.',
113
+ 'Progress messages go only through notify_user, batched with your next tool call; it is delivered immediately. Any other text alongside a tool call is never shown to the user. A response without tool calls is your final reply. Tool results are evidence for you to summarize in your own words; never copy their stock confirmation wording into your reply.',
111
114
  'Do not expose tool traces, Activity, or editor actions.',
112
115
  '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.',
113
116
  '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.',
@@ -119,30 +122,16 @@ export const CONTACT_SYSTEM_PROMPT = [
119
122
  'When creating a scheduled task, preserve the user reporting intent in its prompt: deliver requested research/summaries, or keep successful background work quiet when no report is wanted. Its eventual result returns to this contact for a read-only review; waking the contact does not require sending a message.',
120
123
  ].join(' ');
121
124
 
122
- // A workspace response must explicitly finish or ask for missing input. Plain
123
- // progress prose is not a final answer and must not silently end the pi loop.
125
+ // Plain text without tool calls ends the pi loop, so a workspace turn keeps
126
+ // calling tools until the work is done or handed off.
124
127
  const WORKSPACE_RESPONSE_PROTOCOL = [
125
- 'Workspace response protocol: continue using yuri-tool calls until the task is handed to a worker session, or the small direct task and its verification are done. A successful assign_session ends this turn and worker completion is reported through the session follow-up.',
126
- 'You may batch independent coding calls, but they execute sequentially in the order supplied. Wait for results before using their output. Send Yuri operation tools one at a time.',
128
+ 'Workspace response protocol: keep calling tools until the task is handed to a worker session, or the small direct task and its verification are done. A successful assign_session ends this turn and worker completion is reported through the session follow-up.',
129
+ 'You may batch independent coding calls, but they execute sequentially in the order supplied. Wait for results before using their output. Send Yuri operation tools one at a time; notify_user may accompany any call.',
127
130
  'Reading a skill loads instructions. For substantive work, pass relevant instructions and context to the worker session; for a small direct task, execute the applicable steps and verify the result before completing.',
128
- 'To finish, reply with only an yuri-final JSON fence: ```yuri-final\n{"status":"complete","text":"Your final answer in the user language"}\n```.',
129
- 'Use status "blocked" with the missing information or real blocker when you cannot proceed. Questions and ordinary conversation also use this final format; they do not require a tool call.',
130
- 'Do not use a final declaration for a progress update or promise to act later. Never invent tool results, User messages, or future assistant turns. Only supplied tool-result records are execution evidence.',
131
+ 'A response without tool calls ends the turn: use it only for the final answer, a question, or the real blocker, never for a progress update or a promise to act later.',
132
+ 'Never invent tool results, User messages, or future assistant turns. Only supplied tool-result records are execution evidence.',
131
133
  ].join('\n');
132
134
 
133
- const parseFinalResponse = (text, allowSilent = false) => {
134
- const match = text.trim().match(/^```yuri-final\s*([\s\S]*?)```$/u);
135
- if (!match) return null;
136
- try {
137
- const value = JSON.parse(match[1]);
138
- if (allowSilent && value?.status === 'silent' && value.text === '') return { status: 'silent', text: '' };
139
- if (!value || !['complete', 'blocked'].includes(value.status) || typeof value.text !== 'string' || !value.text.trim()) return null;
140
- return { status: value.status, text: value.text.trim() };
141
- } catch {
142
- return null;
143
- }
144
- };
145
-
146
135
  const emptyUsage = () => ({
147
136
  input: 0,
148
137
  output: 0,
@@ -182,9 +171,9 @@ const assistantMessage = (model, text, stopReason, errorMessage) => ({
182
171
  /**
183
172
  * streamFn for pi-agent-core. Calls Yuri completions (public HTTP stays
184
173
  * non-streaming). In-process callers may pass onTextDelta/globalEventHub for
185
- * the throwaway generate path. Complete public prefix records publish during
186
- * generation; ordinary raw tokens stay private. Legacy prose and final replies
187
- * publish after parsing. Failures are encoded on the event stream.
174
+ * the throwaway generate path. notify_user notes publish when the response
175
+ * arrives; other text beside tool calls stays private, and a response without
176
+ * tool calls is the final reply. Failures are encoded on the event stream.
188
177
  */
189
178
  const completionFileParts = (value) => (Array.isArray(value) ? value : [])
190
179
  .filter((part) => part?.type === 'file' && typeof part.mime === 'string' && typeof part.url === 'string')
@@ -195,58 +184,6 @@ const completionFileParts = (value) => (Array.isArray(value) ? value : [])
195
184
  ...(typeof part.filename === 'string' && part.filename.trim() ? { filename: part.filename.trim() } : {}),
196
185
  }));
197
186
 
198
- /** Fence start (yuri-tool or generic ```) — stop live bubble deltas. */
199
- const CONTACT_FENCE_START = /```/;
200
-
201
- // Only explicitly public, complete prefix records may publish before completion.
202
- // Retain at most one bounded incomplete record; ordinary text and tool JSON stay private.
203
- function createPublicMessageReader(publish) {
204
- const marker = '```yuri-message';
205
- let pending = '';
206
- let stopped = false;
207
- return {
208
- push(delta) {
209
- if (stopped || typeof delta !== 'string') return;
210
- pending += delta;
211
- while (true) {
212
- pending = pending.trimStart();
213
- if (!pending || marker.startsWith(pending)) return;
214
- if (!pending.startsWith(marker)) { stopped = true; return; }
215
- const match = pending.match(/^```yuri-message[ \t]*\r?\n([^\n]+)\r?\n```/u);
216
- if (match && match[0].length > 8192) { stopped = true; return; }
217
- if (!match) {
218
- if (pending.length > 8192) stopped = true;
219
- return;
220
- }
221
- let value;
222
- try {
223
- value = JSON.parse(match[1]);
224
- if (typeof value?.text !== 'string' || !value.text.trim() || value.text.length > 2000) {
225
- stopped = true;
226
- return;
227
- }
228
- } catch { stopped = true; return; }
229
- publish(value.text.trim());
230
- pending = pending.slice(match[0].length);
231
- }
232
- },
233
- };
234
- }
235
-
236
- function stripPublicMessages(text) {
237
- let rest = text.trimStart();
238
- while (rest.startsWith('```yuri-message')) {
239
- const match = rest.match(/^```yuri-message[ \t]*\r?\n([^\n]+)\r?\n```/u);
240
- if (!match || match[0].length > 8192) throw new Error('Invalid public message record');
241
- const value = JSON.parse(match[1]);
242
- if (typeof value?.text !== 'string' || !value.text.trim() || value.text.length > 2000) {
243
- throw new Error('Invalid public message text');
244
- }
245
- rest = rest.slice(match[0].length).trimStart();
246
- }
247
- return rest;
248
- }
249
-
250
187
  const assistantTextParts = (message) => (Array.isArray(message?.content) ? message.content : [])
251
188
  .filter((part) => part?.type === 'text' && typeof part.text === 'string')
252
189
  .map((part) => part.text)
@@ -254,7 +191,7 @@ const assistantTextParts = (message) => (Array.isArray(message?.content) ? messa
254
191
 
255
192
  /**
256
193
  * Streamed assistant bubbles already present in this turn's Agent messages.
257
- * Spoken preambles (tool turns) and final assistant text share splitContactBubbles.
194
+ * notify_user notes (tool turns) and final assistant text share splitContactBubbles.
258
195
  * Independent messages keep duplicate text. Tool-result confirms are not streamed here.
259
196
  */
260
197
  export function projectStreamedContactTurnBubbles(messages, turnStart = 0) {
@@ -267,100 +204,12 @@ export function projectStreamedContactTurnBubbles(messages, turnStart = 0) {
267
204
  const hasTool = parts.some((part) => part?.type === 'toolCall');
268
205
  const text = assistantTextParts(message).trim();
269
206
  if (!text) continue;
270
- if (hasTool && message.contactPublicText !== true && !isContactSpokenPreamble(text)) continue;
207
+ if (hasTool && message.contactPublicText !== true) continue;
271
208
  for (const bubble of splitContactBubbles(text)) bubbles.push(bubble);
272
209
  }
273
210
  return bubbles;
274
211
  }
275
212
 
276
- /**
277
- * Incremental bubble stream from live token deltas.
278
- * - done:false = token increment for the active bubble
279
- * - done:true = that bubble is complete (split off or finalized)
280
- * - baseIndex offsets indices so later completions continue the turn sequence
281
- * Stops when a markdown fence starts so tool JSON never leaks.
282
- */
283
- export function createContactBubbleDeltaTracker(onBubbleDelta, { baseIndex = 0 } = {}) {
284
- const emit = typeof onBubbleDelta === 'function' ? onBubbleDelta : null;
285
- const offset = Number.isFinite(Number(baseIndex)) ? Math.max(0, Number(baseIndex)) : 0;
286
- let accumulated = '';
287
- let completedCount = 0;
288
- let activeEmitted = '';
289
- let stopped = false;
290
- let emittedAny = false;
291
-
292
- const push = (index, delta, done) => {
293
- if (!emit || (typeof delta === 'string' && delta.length === 0 && !done)) return;
294
- emittedAny = true;
295
- emit(offset + index, delta, done);
296
- };
297
-
298
- const applyVisible = (visible) => {
299
- const bubbles = splitContactBubbles(visible);
300
- if (bubbles.length === 0) return;
301
- while (completedCount < bubbles.length - 1) {
302
- const bubble = bubbles[completedCount];
303
- const rest = bubble.slice(activeEmitted.length);
304
- push(completedCount, rest, true);
305
- completedCount += 1;
306
- activeEmitted = '';
307
- }
308
- const active = bubbles[bubbles.length - 1] || '';
309
- if (active.length > activeEmitted.length) {
310
- push(completedCount, active.slice(activeEmitted.length), false);
311
- }
312
- activeEmitted = active;
313
- };
314
-
315
- return {
316
- get emittedAny() {
317
- return emittedAny;
318
- },
319
- get stopped() {
320
- return stopped;
321
- },
322
- get baseIndex() {
323
- return offset;
324
- },
325
- pushDelta(delta) {
326
- if (stopped || typeof delta !== 'string' || !delta) return;
327
- const next = accumulated + delta;
328
- const fenceAt = next.search(CONTACT_FENCE_START);
329
- if (fenceAt >= 0) {
330
- const visibleChunk = next.slice(accumulated.length, fenceAt);
331
- accumulated = next.slice(0, fenceAt);
332
- if (visibleChunk) applyVisible(accumulated);
333
- stopped = true;
334
- return;
335
- }
336
- accumulated = next;
337
- applyVisible(accumulated);
338
- },
339
- /** Finalize after full stripped chat text is known. */
340
- finish(finalBubbles) {
341
- const bubbles = Array.isArray(finalBubbles)
342
- ? finalBubbles.filter((item) => typeof item === 'string' && item.trim())
343
- : [];
344
- if (!emittedAny) {
345
- bubbles.forEach((bubble, index) => push(index, bubble, true));
346
- return;
347
- }
348
- // Complete the active partial bubble, then any trailing bubbles not yet opened.
349
- if (completedCount < bubbles.length) {
350
- const current = bubbles[completedCount] || '';
351
- const rest = current.slice(activeEmitted.length);
352
- if (rest || activeEmitted || current) push(completedCount, rest, true);
353
- completedCount += 1;
354
- activeEmitted = '';
355
- }
356
- while (completedCount < bubbles.length) {
357
- push(completedCount, bubbles[completedCount], true);
358
- completedCount += 1;
359
- }
360
- },
361
- };
362
- }
363
-
364
213
  export function createContactStreamFn(createChatCompletion, {
365
214
  pendingFileParts = [],
366
215
  onTextDelta = null,
@@ -409,7 +258,17 @@ export function createContactStreamFn(createChatCompletion, {
409
258
  if (message.role === 'assistant') {
410
259
  const content = (message.content || []).filter(part => part?.type === 'text').map(part => part.text).join('\n\n');
411
260
  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 } : {}) }] : [];
261
+ // Delivered notes beside other calls replay as the notify_user call they
262
+ // came from, so the model never sees narration accompanying a tool call.
263
+ if (message.contactPublicText === true && content && calls.length && !calls.some((call) => call.function.name === NOTIFY_USER_TOOL_NAME)) {
264
+ const id = `${calls[0].id || 'call'}_notify`;
265
+ return [
266
+ { role: 'assistant', content: '', tool_calls: [{ id, type: 'function', function: { name: NOTIFY_USER_TOOL_NAME, arguments: JSON.stringify({ text: content }) } }, ...calls] },
267
+ { role: 'tool', name: NOTIFY_USER_TOOL_NAME, tool_call_id: id, content: JSON.stringify({ isError: false, content: 'Delivered.' }) },
268
+ ];
269
+ }
270
+ if (calls.length) return [{ role: 'assistant', content: '', tool_calls: calls }];
271
+ return content ? [{ role: 'assistant', content }] : [];
413
272
  }
414
273
  if (message.role === 'toolResult') {
415
274
  const content = (message.content || [])
@@ -435,18 +294,13 @@ export function createContactStreamFn(createChatCompletion, {
435
294
  lastUser.parts = fallbackFiles;
436
295
  }
437
296
  const allowedNames = (context.tools || []).map((tool) => tool?.name).filter(Boolean);
438
- const requiresFinal = allowedNames.some(isPiCodingToolName);
439
297
  let text;
440
298
  let parsed;
441
- let finalText;
442
- let silent = false;
443
299
  let rejectedCodingCalls = [];
444
300
  // Repair only the rejected response: no tools have executed from it.
445
301
  // Real results stay in messages, so already completed work is not replayed.
446
302
  for (let attempt = 0; ; attempt += 1) {
447
303
  signal?.throwIfAborted();
448
- const publicStart = publicBubbles.length;
449
- const publicReader = createPublicMessageReader(publishPublicMessage);
450
304
  const result = await createChatCompletion({
451
305
  signal,
452
306
  timeoutMs: 0,
@@ -464,78 +318,62 @@ export function createContactStreamFn(createChatCompletion, {
464
318
  },
465
319
  onTextDelta: (delta) => {
466
320
  if (signal?.aborted) return;
467
- if (typeof delta === 'string') {
468
- publicReader.push(delta);
469
- }
470
321
  if (typeof delta === 'string' && delta && typeof onTextDelta === 'function') onTextDelta(delta);
471
322
  },
472
323
  globalEventHub,
473
324
  validateToolCalls: false,
474
325
  });
475
326
  signal?.throwIfAborted();
476
- text = result?.completion?.choices?.[0]?.message?.content ?? result?.text ?? '';
477
- const finalPublic = [];
478
- createPublicMessageReader((value) => finalPublic.push(...splitContactBubbles(value))).push(text);
479
- const observedPublic = publicBubbles.slice(publicStart);
480
- if (observedPublic.some((value, index) => finalPublic[index] !== value)) {
481
- throw new Error('Model changed an already published public message');
482
- }
483
- for (const value of finalPublic.slice(observedPublic.length)) publishPublicMessage(value);
484
- text = stripPublicMessages(text);
485
- const finalResponse = parseFinalResponse(text, allowSilent);
486
- silent = finalResponse?.status === 'silent';
487
- finalText = finalResponse?.text ?? null;
488
- // A final answer is opaque text; quoted tool examples in it cannot run.
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 };
495
- const mixedBatch = parsed.toolCalls.length > 1 && parsed.toolCalls.some((call) => !isPiCodingToolName(call.name));
496
- const malformedFinal = finalText === null && /```yuri-final/u.test(parsed.chatText);
497
- const skippedRejectedWork = rejectedCodingCalls.length > 0 && finalResponse?.status === 'complete';
498
- const forgedTranscript = finalText === null && /(?:^|\n)\s*(?:(?:User|Assistant|Tool):|Yuri tool result name=)/iu.test(parsed.chatText);
327
+ const message = result?.completion?.choices?.[0]?.message;
328
+ const content = message?.content ?? result?.text ?? '';
329
+ text = typeof content === 'string' ? content : '';
330
+ const nativeCalls = Array.isArray(message?.tool_calls) ? message.tool_calls : [];
331
+ parsed = nativeCalls.length
332
+ ? parseContactNativeToolCalls(nativeCalls, allowedNames)
333
+ : { toolCalls: [], protocolError: '' };
334
+ const operations = parsed.toolCalls.filter((call) => call.name !== NOTIFY_USER_TOOL_NAME);
335
+ const mixedBatch = operations.length > 1 && operations.some((call) => !isPiCodingToolName(call.name));
336
+ const forgedTranscript = nativeCalls.length === 0 && /(?:^|\n)\s*(?:(?:User|Assistant|Tool):|Yuri tool result name=)/iu.test(text);
499
337
  const protocolError = parsed.protocolError
500
- || (forgedTranscript ? 'Do not simulate user messages, assistant turns, or tool results. Output only your next real tool call and wait for execution.' : '')
501
- || (skippedRejectedWork ? 'Previously rejected coding calls have not executed. Issue the remaining tool calls, or report a blocked outcome; do not declare them complete.' : '')
502
- || (mixedBatch ? 'Send Yuri operation tools one at a time, without other calls in the same response.' : '')
503
- || (malformedFinal ? 'The final declaration must be a single valid yuri-final JSON fence with status and text, without other content.' : '')
504
- || (requiresFinal && parsed.toolCalls.length === 0 && finalText === null ? 'A workspace response needs an actual tool call or an explicit final declaration.' : '');
338
+ || (forgedTranscript ? 'Do not simulate user messages, assistant turns, or tool results. Call the next real tool and wait for its result.' : '')
339
+ || (mixedBatch ? 'Send Yuri operation tools one at a time, without other calls in the same response.' : '');
505
340
  if (!protocolError) break;
506
341
  if (attempt >= 2) throw new Error(`Assistant response protocol failed after two corrections; the task was not confirmed complete. Reason: ${protocolError}`);
507
- const rejected = parsed.toolCalls.filter((call) => isPiCodingToolName(call.name));
342
+ const rejected = operations.filter((call) => isPiCodingToolName(call.name));
508
343
  if (rejected.length > 0) rejectedCodingCalls = rejected.map(({ name, arguments: args }) => ({ name, arguments: args }));
509
- if (publicBubbles.length > publicStart) {
510
- messages.push({ role: 'assistant', content: publicBubbles.slice(publicStart).join('\n\n') });
511
- }
512
344
  // Never replay rejected prose: it may contain fabricated user/tool results.
513
345
  messages.push(
514
- { role: 'user', content: `Yuri response protocol correction: ${protocolError} No tool calls from the rejected response executed. ${rejectedCodingCalls.length ? `Unexecuted proposed calls (not results): ${JSON.stringify(rejectedCodingCalls)}.` : ''} Continue the remaining work using the supplied real results; do not repeat completed operations. ${requiresFinal ? WORKSPACE_RESPONSE_PROTOCOL : 'Emit the corrected yuri-tool call.'}` },
346
+ { role: 'user', content: `Yuri response protocol correction: ${protocolError} No tool calls from the rejected response executed. ${rejectedCodingCalls.length ? `Unexecuted proposed calls (not results): ${JSON.stringify(rejectedCodingCalls)}.` : ''} Continue the remaining work using the supplied real results; do not repeat completed operations.` },
515
347
  );
516
348
  }
517
- // Continue turn-global bubble indices from already-streamed turn messages.
518
- const nextIndex = baseIndex + publicBubbles.length;
519
- const bubbleTracker = createContactBubbleDeltaTracker(onBubbleDelta, { baseIndex: nextIndex });
520
349
  if (parsed.toolCalls.length > 0) {
521
- const toolCalls = parsed.toolCalls.map((call) => ({
350
+ // notify_user text is the only public part of a tool-call response; other
351
+ // text that accompanies a tool call is model narration and stays private.
352
+ for (const call of parsed.toolCalls) {
353
+ if (call.name !== NOTIFY_USER_TOOL_NAME) continue;
354
+ const note = typeof call.arguments?.text === 'string' ? call.arguments.text.trim() : '';
355
+ if (note && note.length <= NOTIFY_USER_MAX_CHARS) publishPublicMessage(note);
356
+ }
357
+ const operations = parsed.toolCalls.filter((call) => call.name !== NOTIFY_USER_TOOL_NAME);
358
+ // Delivered notes alongside other calls need no execution. Dropping them keeps
359
+ // terminal batches (assign_session, stay_silent) terminal; a notes-only
360
+ // response still executes so the loop continues.
361
+ const executed = operations.length > 0 ? operations : parsed.toolCalls;
362
+ const toolCalls = executed.map((call) => ({
522
363
  type: 'toolCall',
523
364
  id: call.id || `call_${Date.now().toString(36)}_${++callSequence}`,
524
365
  name: call.name,
525
366
  arguments: call.arguments,
526
367
  }));
527
- const spoken = isContactSpokenPreamble(parsed.chatText) ? parsed.chatText.trim() : '';
528
- const spokenBubbles = spoken ? splitContactBubbles(spoken) : [];
529
- const publicText = [...publicBubbles, ...spokenBubbles].join('\n\n');
368
+ const publicText = publicBubbles.join('\n\n');
530
369
  const content = publicText
531
370
  ? [{ type: 'text', text: publicText }, ...toolCalls]
532
371
  : toolCalls;
533
372
  const partial = {
534
- ...assistantMessage(model, spoken, 'toolUse'),
373
+ ...assistantMessage(model, '', 'toolUse'),
535
374
  content,
536
375
  contactPublicText: true,
537
376
  };
538
- if (spokenBubbles.length > 0) bubbleTracker.finish(spokenBubbles);
539
377
  stream.push({ type: 'start', partial });
540
378
  if (publicText) {
541
379
  stream.push({ type: 'text_start', contentIndex: 0, partial });
@@ -552,20 +390,16 @@ export function createContactStreamFn(createChatCompletion, {
552
390
  stream.end(partial);
553
391
  return;
554
392
  }
555
- const chatText = finalText ?? parsed.chatText;
393
+ // A response without tool calls is the final reply.
394
+ const chatText = text.trim();
556
395
  const replyBubbles = splitContactBubbles(chatText);
557
- if (bubbleGapMs > 0 && replyBubbles.length > 1) {
558
- for (let index = 0; index < replyBubbles.length; index += 1) {
559
- onBubbleDelta?.(nextIndex + index, replyBubbles[index], true);
560
- if (index < replyBubbles.length - 1) {
561
- await new Promise((resolve) => setTimeout(resolve, bubbleGapMs));
562
- }
396
+ for (let index = 0; index < replyBubbles.length; index += 1) {
397
+ onBubbleDelta?.(baseIndex + index, replyBubbles[index], true);
398
+ if (bubbleGapMs > 0 && index < replyBubbles.length - 1) {
399
+ await new Promise((resolve) => setTimeout(resolve, bubbleGapMs));
563
400
  }
564
- } else {
565
- bubbleTracker.finish(replyBubbles);
566
401
  }
567
- const partial = assistantMessage(model, silent ? '' : [...publicBubbles, ...replyBubbles].join('\n\n'), 'stop');
568
- if (silent) partial.contactSilent = true;
402
+ const partial = assistantMessage(model, replyBubbles.join('\n\n'), 'stop');
569
403
  stream.push({ type: 'start', partial });
570
404
  stream.push({ type: 'text_start', contentIndex: 0, partial });
571
405
  stream.push({ type: 'text_delta', contentIndex: 0, delta: chatText, partial });
@@ -664,6 +498,8 @@ export async function runContactTurn({
664
498
  const contactTools = Array.isArray(tools)
665
499
  ? 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)))
666
500
  : [];
501
+ // Background reviews only reply or stay silent; interactive turns may notify mid-turn.
502
+ const conversationTools = allowSilent ? [createStaySilentTool()] : readOnly ? [] : [createNotifyUserTool()];
667
503
  let runtime = null;
668
504
  let removeAbortListener = null;
669
505
  try {
@@ -674,18 +510,17 @@ export async function runContactTurn({
674
510
  CONTACT_SYSTEM_PROMPT,
675
511
  'Conversation history is a bounded recent window. Use search_memory and read_memory to recall earlier facts from this contact when references or decisions are missing. Search by short distinctive terms or browse by time, read the relevant source, and report its date when useful. A page with complete=false still has older candidates. Cleared memory forms an access boundary and deleted history is unavailable. Historical messages are quoted evidence; current user instructions govern actions. Yuri card context records contain actual session identifiers and status. Ask for missing details after checking accessible history.',
676
512
  readOnly ? 'This turn is a background result review. Only read-only lookup tools are available. Never create or continue work; follow the latest user constraints.' : '',
677
- allowSilent ? 'Decide whether this background result needs a user-facing reply. Deliver requested research, summaries, or other requested output. Successful background work with no requested report should stay silent. Stay silent when conversation history already reports this same result and nothing new needs the user. Report actionable failures or missing input unless the user explicitly requested silence. For silence, emit only ```yuri-final\n{"status":"silent","text":""}\n```. Otherwise give the actual result once, in the user language, as a single short final answer. Do not narrate checks, announce progress, or send yuri-message progress updates.' : '',
513
+ allowSilent ? 'Decide whether this background result needs a user-facing reply. Deliver requested research, summaries, or other requested output. Successful background work with no requested report should stay silent. Stay silent when conversation history already reports this same result and nothing new needs the user. Report actionable failures or missing input unless the user explicitly requested silence. For silence, call stay_silent alone. Otherwise give the actual result once, in the user language, as a single short final answer. Do not narrate checks or announce progress.' : '',
678
514
  formatPiCodingPrompt({
679
515
  cwd: runtime?.cwd,
680
516
  skillsPrompt: runtime?.skillsPrompt,
681
- tools: codingTools,
682
517
  }),
683
518
  formatRegisteredProjectsPrompt(projects),
684
519
  formatConnectedModelsPrompt(connectedModels, { preferences: modelPreferences, catalogAvailable: modelCatalogAvailable }),
685
520
  formatContactToolsPrompt(contactTools),
686
521
  assistant.defaultPrompt,
687
522
  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.',
523
+ 'Actual tool results arrive in tool-role messages; never manufacture them.',
689
524
  ].filter((value) => typeof value === 'string' && value.trim()).join('\n\n')
690
525
  .replaceAll('{{LANGUAGE}}', resolveContactLanguage(language));
691
526
  const model = createContactModel(providerID, modelID);
@@ -718,7 +553,7 @@ export async function runContactTurn({
718
553
  systemPrompt,
719
554
  model,
720
555
  thinkingLevel: 'off',
721
- tools: [...codingTools, ...contactTools],
556
+ tools: [...codingTools, ...contactTools, ...conversationTools],
722
557
  messages: prior,
723
558
  },
724
559
  streamFn: createContactStreamFn(createChatCompletion, {
@@ -765,7 +600,7 @@ export async function runContactTurn({
765
600
  // a turn error; the harness never manufactures an assistant reply.
766
601
  const missed = extractContactTurnOutcome(agent.state.messages.slice(turnMessageStart));
767
602
  const missedBubbles = (Array.isArray(missed.bubbles) ? missed.bubbles : [])
768
- .map((item) => (typeof item === 'string' ? stripContactToolFences(item).trim() : ''))
603
+ .map((item) => (typeof item === 'string' ? item.trim() : ''))
769
604
  .filter(Boolean);
770
605
  if (missedBubbles.length > 0) {
771
606
  return {
@@ -781,7 +616,7 @@ export async function runContactTurn({
781
616
  const turnMessages = agent.state.messages.slice(turnMessageStart);
782
617
  const reset = contactTurnHasSuccessfulReset(turnMessages);
783
618
  const lastMessage = turnMessages.at(-1);
784
- if (allowSilent && lastMessage?.role === 'assistant' && lastMessage.contactSilent === true) {
619
+ if (allowSilent && lastMessage?.role === 'toolResult' && lastMessage.toolName === STAY_SILENT_TOOL_NAME && !lastMessage.isError) {
785
620
  return { silent: true, text: '', bubbles: [], cards: [], thinkingLevel: agent.state.thinkingLevel, tools: [...agent.state.tools] };
786
621
  }
787
622
  // Terminal tools stop further mutations. A tools-disabled model pass owns