@yuriai/web 0.2.8-beta.2 → 0.2.8

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 (94) hide show
  1. package/dist/assets/{AgentAvatar-MzDm6uBf.js → AgentAvatar--DsfGfhZ.js} +1 -1
  2. package/dist/assets/{AssistantView-BjpY2u0c.js → AssistantView-CaLm2pDU.js} +3 -3
  3. package/dist/assets/{DiagramView-7j0sZC_P.js → DiagramView-Bh_Y3wjs.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-qGOqnbF5.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-CniMrVC7.js +2 -0
  11. package/dist/assets/{MarkdownRendererImpl-Dh7XVDLd.js → MarkdownRendererImpl-BoMHV8l0.js} +1 -1
  12. package/dist/assets/{MarkstreamRendererImpl-D-qtRrvg.js → MarkstreamRendererImpl-BXEZlJGP.js} +1 -1
  13. package/dist/assets/{MobileDetailNavigation-LkTVYLZX.js → MobileDetailNavigation-B6Ohvu93.js} +1 -1
  14. package/dist/assets/{MobileResizableSheet-C9YzOQis.js → MobileResizableSheet-BN07cmQQ.js} +1 -1
  15. package/dist/assets/{MobileShareBridge-CsTyKMtN.js → MobileShareBridge-DRx1mbUO.js} +1 -1
  16. package/dist/assets/MobileTabPageHeader-CHXNz-XU.js +2 -0
  17. package/dist/assets/{MultiRunWindow-hMpjV7so.js → MultiRunWindow-CWwawp5s.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-q2q_C3kF.js} +1 -1
  21. package/dist/assets/{SettingsWindow-B1VuFkFq.js → SettingsWindow-BO4fG8ON.js} +1 -1
  22. package/dist/assets/{TerminalView-CLcaJh2M.js → TerminalView-OVVhfpeZ.js} +1 -1
  23. package/dist/assets/{ToolOutputDialog-BuZo3XvN.js → ToolOutputDialog-CqirE_Q0.js} +1 -1
  24. package/dist/assets/{YuriLogo-DvRSd5NN.js → YuriLogo-kwLWc5Hi.js} +1 -1
  25. package/dist/assets/{appThemeRegistry-B7sp1Hw8.js → appThemeRegistry-Dg6MpoKd.js} +1 -1
  26. package/dist/assets/{button-BSFWH-Ok.js → button-Dodw6LWV.js} +1 -1
  27. package/dist/assets/{capgoAdapter-vxOdqloD.js → capgoAdapter-B7ToX3Rx.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-CHBe_36a.js} +1 -1
  34. package/dist/assets/{fr-YDYbYIZQ.js → fr-CPRTMaky.js} +1 -1
  35. package/dist/assets/{gitApi-BLYdWaG8.js → gitApi-CesLpypb.js} +1 -1
  36. package/dist/assets/{input-BhHXFla6.js → input-HddqDhRi.js} +1 -1
  37. package/dist/assets/{insertionBoundaries-DqlfZVY9.js → insertionBoundaries-BLxQiOvC.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-DlTR1Jke.js} +2 -2
  41. package/dist/assets/{main-Qw23QJ7L.js → main-Z6Jwv7Aw.js} +4 -4
  42. package/dist/assets/{markdownHeightCache-DV2j4PlS.js → markdownHeightCache-BQiIj0aM.js} +1 -1
  43. package/dist/assets/{mcpQueries-C6Tu2cF3.js → mcpQueries-CZLOskV8.js} +1 -1
  44. package/dist/assets/{miniChat-HafcB3H-.js → miniChat-SzvTUnN9.js} +2 -2
  45. package/dist/assets/{mobile-DwXoGpxm.js → mobile-dh54OsZj.js} +2 -2
  46. package/dist/assets/{mobileBackNavigation-9MR5h5K6.js → mobileBackNavigation-D9_5Uqi3.js} +1 -1
  47. package/dist/assets/{multirun-D-je_w02.js → multirun-J_f9gEPw.js} +1 -1
  48. package/dist/assets/{native-config-Bb3pPQPD.js → native-config-Bohk_yve.js} +1 -1
  49. package/dist/assets/{pl-vh0XFuDb.js → pl-mUyhvp8O.js} +1 -1
  50. package/dist/assets/{projectMeta-DaCyZW_D.js → projectMeta-BH9vbJqs.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-D1Glg4WD.js} +1 -1
  53. package/dist/assets/{renderElectronMiniChatApp-COaMALRh.js → renderElectronMiniChatApp-DM5OW4_M.js} +2 -2
  54. package/dist/assets/{renderMobileApp-BOGntDSu.js → renderMobileApp-CvDZu5Qx.js} +4 -4
  55. package/dist/assets/{runtimeConfig-BiSluBXe.js → runtimeConfig-CwEhy80T.js} +1 -1
  56. package/dist/assets/{runtimeEndpointReset-CJwlI_R-.js → runtimeEndpointReset-CFELYYml.js} +3 -3
  57. package/dist/assets/{scheduledTaskNavigation-BZ3B5bpN.js → scheduledTaskNavigation-CyPkVBKs.js} +1 -1
  58. package/dist/assets/{sessionChangeSummary-BAv8zzro.js → sessionChangeSummary-DnCiwEhi.js} +1 -1
  59. package/dist/assets/{sessionLookup-DOw7g15p.js → sessionLookup-BxXJcGxg.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-7aN_QCn_.js} +1 -1
  62. package/dist/assets/src-BJ51FtVW.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-Dzzdq2e0.js +2 -0
  67. package/dist/assets/{uk-3a9vdLJ-.js → uk-D9iQbGbr.js} +1 -1
  68. package/dist/assets/{useAppFontEffects-De1qI6c-.js → useAppFontEffects-Ql6SjWay.js} +5 -5
  69. package/dist/assets/{useDesktopWindowControlsLayout-BzXi6Wf1.js → useDesktopWindowControlsLayout-DpovjCsM.js} +1 -1
  70. package/dist/assets/{useEffectiveDirectory-BcbBl_6y.js → useEffectiveDirectory-CjXQBqAr.js} +1 -1
  71. package/dist/assets/{useMobileNavigationStore-DqDCVXO1.js → useMobileNavigationStore-BTJNY1Yo.js} +6 -6
  72. package/dist/assets/{useWorkerHighlightedLines-CDVleuma.js → useWorkerHighlightedLines-cS9vGi9t.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/MarkdownRenderer-B8zgOCfr.js +0 -2
  92. package/dist/assets/MobileTabPageHeader-xz9RMXg4.js +0 -2
  93. package/dist/assets/src-NlrSCyPZ.css +0 -2
  94. package/dist/assets/types-BiP0jssb.js +0 -2
@@ -77,7 +77,7 @@
77
77
  .dark #initial-loading img { filter: invert(1); }
78
78
  </style>
79
79
 
80
- <script type="module" crossorigin src="/assets/miniChat-HafcB3H-.js"></script>
80
+ <script type="module" crossorigin src="/assets/miniChat-SzvTUnN9.js"></script>
81
81
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-hePW80VL.js">
82
82
  <link rel="modulepreload" crossorigin href="/assets/runtime-auth-ef9W7A43.js">
83
83
  <link rel="modulepreload" crossorigin href="/assets/runtime-switch-CAZiOV2G.js">
@@ -108,11 +108,11 @@
108
108
  <link rel="modulepreload" crossorigin href="/assets/platform-DXeTzJHG.js">
109
109
  <link rel="modulepreload" crossorigin href="/assets/terminalApi-CIbkfDkE.js">
110
110
  <link rel="modulepreload" crossorigin href="/assets/runtime-file-download-BzblfnMx.js">
111
- <link rel="modulepreload" crossorigin href="/assets/types-BiP0jssb.js">
112
- <link rel="modulepreload" crossorigin href="/assets/capgoAdapter-vxOdqloD.js">
113
- <link rel="modulepreload" crossorigin href="/assets/native-config-Bb3pPQPD.js">
114
- <link rel="modulepreload" crossorigin href="/assets/runtimeConfig-BiSluBXe.js">
115
- <link rel="stylesheet" crossorigin href="/assets/src-NlrSCyPZ.css">
111
+ <link rel="modulepreload" crossorigin href="/assets/types-Dzzdq2e0.js">
112
+ <link rel="modulepreload" crossorigin href="/assets/capgoAdapter-B7ToX3Rx.js">
113
+ <link rel="modulepreload" crossorigin href="/assets/native-config-Bohk_yve.js">
114
+ <link rel="modulepreload" crossorigin href="/assets/runtimeConfig-CwEhy80T.js">
115
+ <link rel="stylesheet" crossorigin href="/assets/src-BJ51FtVW.css">
116
116
  </head>
117
117
  <body class="h-full bg-background text-foreground">
118
118
  <div id="root" class="h-full">
package/dist/mobile.html CHANGED
@@ -64,7 +64,7 @@
64
64
  </script>
65
65
 
66
66
  <style>.dark #mobile-startup-logo img { filter: invert(1); }</style>
67
- <script type="module" crossorigin src="/assets/mobile-DwXoGpxm.js"></script>
67
+ <script type="module" crossorigin src="/assets/mobile-dh54OsZj.js"></script>
68
68
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-hePW80VL.js">
69
69
  <link rel="modulepreload" crossorigin href="/assets/runtime-auth-ef9W7A43.js">
70
70
  <link rel="modulepreload" crossorigin href="/assets/runtime-switch-CAZiOV2G.js">
@@ -95,11 +95,11 @@
95
95
  <link rel="modulepreload" crossorigin href="/assets/platform-DXeTzJHG.js">
96
96
  <link rel="modulepreload" crossorigin href="/assets/terminalApi-CIbkfDkE.js">
97
97
  <link rel="modulepreload" crossorigin href="/assets/runtime-file-download-BzblfnMx.js">
98
- <link rel="modulepreload" crossorigin href="/assets/types-BiP0jssb.js">
99
- <link rel="modulepreload" crossorigin href="/assets/capgoAdapter-vxOdqloD.js">
100
- <link rel="modulepreload" crossorigin href="/assets/native-config-Bb3pPQPD.js">
101
- <link rel="modulepreload" crossorigin href="/assets/runtimeConfig-BiSluBXe.js">
102
- <link rel="stylesheet" crossorigin href="/assets/src-NlrSCyPZ.css">
98
+ <link rel="modulepreload" crossorigin href="/assets/types-Dzzdq2e0.js">
99
+ <link rel="modulepreload" crossorigin href="/assets/capgoAdapter-B7ToX3Rx.js">
100
+ <link rel="modulepreload" crossorigin href="/assets/native-config-Bohk_yve.js">
101
+ <link rel="modulepreload" crossorigin href="/assets/runtimeConfig-CwEhy80T.js">
102
+ <link rel="stylesheet" crossorigin href="/assets/src-BJ51FtVW.css">
103
103
  </head>
104
104
  <body class="h-full bg-background text-foreground">
105
105
  <div id="root" class="h-full">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yuriai/web",
3
- "version": "0.2.8-beta.2",
3
+ "version": "0.2.8",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "main": "./server/index.js",
@@ -93,10 +93,9 @@ reasoning display.
93
93
  user message is inserted. The review cannot execute the task again.
94
94
  - The model decides whether to deliver requested findings or remain quiet for
95
95
  successful background work. Scheduled reviews and read-only worker-watch
96
- follow-ups accept an exact `yuri-final` declaration
97
- `{ "status": "silent", "text": "" }`. Empty/malformed responses remain errors.
98
- Background reviews never publish `yuri-message` progress; they speak once
99
- through the final decision. Silent reviews produce no transcript bubble,
96
+ follow-ups register a terminal `stay_silent` tool; a turn ending in its result
97
+ is silent. Empty/malformed responses remain errors. Background reviews get no
98
+ `notify_user` tool; they speak once through the final reply. Silent reviews produce no transcript bubble,
100
99
  unread message, or contact notification. Worker-watch follow-ups still report
101
100
  the awaited result unless history already reports the same result.
102
101
  - The additive `assistant_scheduled_result` table records terminal review
@@ -185,17 +184,18 @@ and keep their existing error result handling.
185
184
  context, not hidden OpenCode Agent context. Summaries receive only their explicit
186
185
  system/prompt. Native inference is currently one-shot, not token-streaming.
187
186
 
188
- - Public progress uses leading `yuri-message` fences containing single-line JSON `{ "text": "..." }`. A complete, valid public record emits a `done:true` bubble immediately during generation, before the following tool/final output completes. Incomplete records and ordinary raw tokens stay private. Each public record is capped at 2,000 text characters and the incomplete-record buffer at 8 KiB. The parser reads only consecutive prefix records, so quoted tool examples cannot become public events.
187
+ - Tools use native function calling only (`message.tool_calls`); text is never parsed for tool calls and no schema catalog is repeated in the prompt. A response without tool calls is the final reply.
188
+ - Public progress uses the harness-owned `notify_user` tool `{ text }` (max 2,000 characters), usually batched with the next call. Its text emits `done:true` bubbles when the response arrives, before the batch executes. Batched notes are dropped from execution and stored as the assistant message's public text (`contactPublicText`); a notes-only response executes and the loop continues. Text beside tool calls is model narration and stays private. Later rounds replay delivered notes to the model as `notify_user` calls.
189
189
  - The model is prompted to send a progress message only when it adds information the user does not already have (a direction worth correcting, a meaningful finding, a blocker, or expected long work), then give a short final outcome. A message is not required before each tool call, and successful lookups need no separate confirmation. Public messages share the existing SSE, durable contact rows, and turn-global indices across web, desktop, VS Code, hosted mobile, and Capacitor. No timer narration, tool logs, progress widgets, or synthetic chat messages are added. Timing of model-authored milestones remains model policy; the transport guarantees immediate delivery once an explicit public record arrives.
190
190
  - Completion notifications use the latest spoken message, keeping earlier progress out of the final notification body. Transcript persistence reconciles by stable bubble IDs and adds only remaining messages.
191
191
  - Tool results remain model context for every tool. The outcome projector uses assistant-authored text only. Terminal operations retain the mutation stop gate, followed by a tools-disabled completion on the same provider/model to communicate the actual result. A failed/empty summary surfaces a turn error; a completed side effect stays committed and is never replayed by that summary pass.
192
192
  - Reset summaries receive only the successful reset tool result, excluding prior messages and attachments. The service retains one model-generated confirmation and discards pre-reset output for that turn. Failures emit temporary live error feedback outside assistant speech bubbles, without a persisted failure row.
193
193
 
194
- - Protocol correction never replays rejected assistant prose into model history: simulated User/Assistant turns and tool-result records are rejected as fabricated evidence. Known rejected coding calls cannot be skipped with a subsequent `complete` declaration; the model must issue actual calls or report a blocker. Corrections remain bounded and exhaustion is an error, not a completion.
194
+ - Protocol correction never replays rejected assistant prose into model history: simulated User/Assistant turns and tool-result records are rejected as fabricated evidence. Corrections remain bounded and exhaustion is an error, not a completion.
195
195
 
196
- - A workspace-backed contact keeps running until it emits coding calls or an explicit `yuri-final` JSON fence with `{ "status": "complete" | "blocked", "text": "..." }`. Final declarations contain the user-facing answer only; missing input/questions use `blocked`. Ordinary conversation can finish without tools using the same declaration. Reading a skill loads instructions and does not itself complete the user's task. Contacts without coding tools retain their plain-text reply contract.
197
- - Plain progress text is not completion. The stream adapter requests at most two protocol corrections for a rejected response, retaining actual prior calls/results. Rejected ordinary prose and tool calls stay private/unexecuted; independently validated public prefix messages already delivered remain visible. Exhaustion becomes an upstream error containing the last validation reason, without including rejected model output or tool arguments. This guard enforces the response protocol; a model's explicit completion claim is not independent verification of arbitrary task semantics.
198
- - `parseContactToolCalls` returns an ordered `toolCalls` array. It accepts application fences, complete generic JSON fences, and bare/embedded call objects. Nested argument objects and quoted markdown fences remain data. An invalid/unavailable/unclosed explicit application call rejects the entire response before any prefix can execute.
196
+ - A workspace-backed contact keeps calling tools until the work is handed off or done; the prompt tells it that a response without tool calls ends the turn and is only for the final answer, a question, or a real blocker. Reading a skill loads instructions and does not itself complete the user's task.
197
+ - The stream adapter requests at most two protocol corrections for a rejected response (unknown tool, invalid arguments, forged transcript, mixed operation batch), retaining actual prior calls/results. Rejected prose, notes, and tool calls stay private/unexecuted; notes delivered by earlier accepted responses remain visible. Exhaustion becomes an upstream error containing the last validation reason, without including rejected model output or tool arguments. This guard enforces the response protocol; a model's explicit completion claim is not independent verification of arbitrary task semantics.
198
+ - `parseContactNativeToolCalls` returns an ordered `toolCalls` array from native calls, running shell-style aliases through `bash`. An invalid/unavailable call rejects the entire response before any call executes, with a correction naming the available tools.
199
199
  - Multiple coding calls run sequentially through pi (`toolExecution: 'sequential'`), preserving dependencies such as write then read. Yuri operation tools must be sent one at a time: mixed/multiple-operation batches are rejected before execution so terminal assign/reset/watch semantics and side-effect gates remain intact.
200
200
  - Completion history retains every assistant tool call (name, arguments, generated call ID) and its real tool result, including empty content and `isError`. Results still use gateway-supported user messages labeled `Yuri tool result name=... call=...` with a JSON body. Model-written result lookalikes are never executed or admitted as actual tool results. Final JSON text is opaque: quoted tool examples in a final answer cannot execute.
201
201
  - Malformed calls or mixed final declarations use the same bounded correction path. Only a validated tool response or final reply reaches the pi stream; protocol corrections do not replay tools already executed. Runtime file/shell cleanup remains in `finally`.
@@ -219,7 +219,7 @@ and keep their existing error result handling.
219
219
  - **Create-then-prompt failure:** if `session.create` succeeds and `session.prompt` fails, assign best-effort `session.delete`s the new worker so empty sessions are not left behind. Reused `sessionID` paths never delete on prompt failure.
220
220
  - Successful `assign_session` and `watch_session` return `terminate: true` to stop the mutation loop. The harness then requests a tools-disabled model summary. Prerequisite tools (`list_projects` / `list_sessions`) may still run before assign/watch/stop in the same turn; multi-operation user intents remain ordered **across turns** after a successful assign/watch.
221
221
  - Same contact-turn assign gate (tools instance lifetime only, not cross-turn): identical args after success replay the cached success result (no second worker); different args after success, or parallel mismatched args, fail closed with a validation error. The idempotent key includes worker model selection and current-turn attachment scope. Failure clears the gate so a corrected retry may run. Parallel identical args share one in-flight promise.
222
- - After a successful assign or watch, the service persists the existing session card into the contact transcript (user bubbles first, then the card) and watches that worker session in `assistant_contact_watch` (watch baselines the live status). The user-facing outcome is the session card plus any short **spoken** preamble; English tool-result confirms (`Opened a coding session.`, `Watching that coding session.`, `Created assistant…`, `Sent to…`) for card/side-effect tools are **not** written into the transcript.
222
+ - After a successful assign or watch, the service persists the existing session card into the contact transcript (user bubbles first, then the card) and watches that worker session in `assistant_contact_watch` (watch baselines the live status). The user-facing outcome is the session card plus any `notify_user` progress note; English tool-result confirms (`Opened a coding session.`, `Watching that coding session.`, `Created assistant…`, `Sent to…`) for card/side-effect tools are **not** written into the transcript.
223
223
  - Existing OpenCode SSE on the same `globalEventHub` as notifications (`session.idle`, `session.error`, `session.status`, `session.execution.*`, `question.asked`, `permission.asked`) updates **the same card** (`busy` → `complete` / `error` / `question` / `cancelled`). **No canned settle transcript bubbles** (`oc.settle.complete` / `error` / `question` are not written). On **complete, error, or cancelled (user interrupt)** when the watch status actually changed, the service schedules an async contact-lane **continuation** (`inContactTurnLane` + `runContactTurn`) per related assistant: no admitted user row (internal `userText` only), active contact turn (green dot / 3-dot), stable resume id `resume_${assistantID}_${sessionID}_${status}_${updatedAt}`, bounded last worker assistant text (~2000 chars; fetch failure still resumes with status only). Cancelled continuations include `reason: user_interrupted` so the contact can acknowledge the user's abort. The contact Agent can perform read-only lookups and summarize in the user's language, but cannot reassign or mutate a session during this notification — the user sees that Agent summary, not 「会话已完成/会话失败」. `question` updates the card only (worker waiting on the user). `stop_session` cancellation does not schedule this continuation. Session-goal settle (`emitGoalNotification`) uses the same reporter — not a second scheduler. Idle after `session.error` must not rewrite 失败 as 完成 (`changed=false` → no second resume). Same complete status re-reported is idempotent. The watch rows are read inside the `BEGIN IMMEDIATE` transition, so multiple Host processes sharing `assistants.sqlite` schedule at most one continuation per transition. The lock is SQLite's OS file lock, held only for that synchronous transaction (no awaits); a Host that exits mid-transaction releases it and its uncommitted write is discarded. Turn lanes and active-turn markers are process-local memory, so a dead Host never leaves a durable lock: whichever Host receives the next user send admits and runs it.
224
224
  - **Shutdown interrupt (ticket 07):** official `session.execution.interrupted` reason is `user | shutdown | superseded | inactivity`. **`reason: shutdown` does not settle** the watch and does **not** schedule contact resume — upstream keeps the execution claim for restart recovery. The card stays `busy` until an authoritative terminal (`session.execution.succeeded` / `failed` / user interrupt / reconcile). `reason: user` settles `cancelled` + resume. Other non-shutdown interrupts settle `error` unless `MessageAbortedError`. No parallel recovery store — the existing watch row remains the owner.
225
225
  - Restart or a missed `session.idle` cannot leave the watch stuck: boot and the existing 60s reconcile timer `listInFlightWatches` and poll OpenCode `session.get` / `message.list`. Idle, `time.completed`, or a missing session settles the same card (`busy` → 完成) and triggers the same contact continuation (no `oc.settle.complete` bubble). `session.error` or last-assistant `info.error` settles 失败 + resume once; last-assistant `MessageAbortedError` settles `cancelled` + the interrupt notify once. Transport / non-404 get errors leave the watch in flight (failure is not empty success). One failed watch does not block unrelated watches. Reconcile reuses `reportAssignedSession`, so an error watch is never rewritten as complete. Tombstoned assistants skip resume.
@@ -256,15 +256,15 @@ Reply language follows the user's latest substantive message and conversation co
256
256
  - `schedule_task` calls in-process `projectConfigRuntime.upsertScheduledTask` with the same payload as `PUT /api/projects/:id/scheduled-tasks` (`name`, `schedule.kind/time/timezone`, `execution.prompt` + provider/model) on a registered project, then best-effort `scheduledTasksRuntime.syncProject`. It emits a `schedule` card.
257
257
  - `list_scheduled_tasks` lists registered projects' tasks with exact task/project IDs, schedule, model and a bounded prompt preview. Failed project reads remain explicit partial failures. Read-only background turns may list but cannot modify tasks.
258
258
  - `update_scheduled_task` uses the existing project-config patch operation and scheduler sync, changing only supplied fields and validating explicit models against the connected catalog. It emits the existing schedule card; it can edit tasks created outside the Assistant.
259
- - Native and legacy text calls share the same tool-name validation and shell-alias normalization. `shell`, `powershell`, `grep`, `glob`, `find` and `ls` may resolve to the existing `bash` tool only when it is available. Native call IDs survive normalization. Unknown tool corrections identify the rejected name and available tools, without executing a rejected prefix. The contact harness owns bounded correction; generic completion callers retain strict tool-name validation.
259
+ - Native calls use tool-name validation and shell-alias normalization. `shell`, `powershell`, `grep`, `glob`, `find` and `ls` may resolve to the existing `bash` tool only when it is available. Native call IDs survive normalization. Unknown tool corrections identify the rejected name and available tools, without executing a rejected prefix. The contact harness owns bounded correction; generic completion callers retain strict tool-name validation.
260
260
  - Successful `schedule_task` also writes an assistants-owned mapping row in `assistants.sqlite` (`assistant_scheduled_task`: assistantID + projectID + taskID). Project-config execution strips unknown fields, so ownership stays out of the task payload. `GET /api/yuri/assistants/:id/scheduled-tasks` returns those mappings joined with live `listScheduledTasks` records when possible; failed project lookups keep the mapping with `task: null`.
261
- - `CONTACT_SYSTEM_PROMPT` + `formatContactToolsPrompt` + `formatPiCodingPrompt` tell the model to call these from natural language (开新对话 / 找项目 / 现有对话 / 查看助手设定·默认提示词 / 改默认提示词·设置人设 / 建助理 / 建会话·继续会话 / 监听会话 / 停止会话 / 排定时任务 / 给 X 说一声). Catalog lines include each tool's JSON argument schema (pi `write`/`edit` require `path`+`content` / `path`+`edits[{oldText,newText}]`). A reply without the tool call does nothing; never say 已创建 / 已发送 / 已停止 unless the tool returned. Completions are messages-only (no native tools), so `parseContactToolCalls` accepts a fence, a whole-message JSON object, or a bare `{name, arguments}` object anywhere in the reply. Tool results are re-injected as user turns labeled `Yuri tool result name=<tool> call=<id>` with JSON `{ isError, content }`; assistant calls and their arguments/IDs are also retained so multi-step turns keep call/result association. The harness replaces every `{{LANGUAGE}}` token — in the built-in prompt and in `defaultPrompt` — with the UI locale sent on the composer payload (`language` field, whitelisted locale code → display name). Background/settle turns recall the last locale seen for that assistant; unknown or missing locales resolve to `the user's interface language`, so the token never leaks into the prompt.
262
- - If the user asked for `new_conversation` / `clear_chat_history` / `list_projects` / `list_sessions` / `get_assistant_settings` / `update_default_prompt` / `create_assistant` / `schedule_task` / `message_assistant` / `watch_session` / `stop_session` / `assign_session` and the first completion has no tool call, the harness runs **one** follow-up completion whose user content is only `emit the fence now, do not claim success.` If still no tool, the turn replies that it could not complete and does not fake a card. No slash commands. No second store.
261
+ - `CONTACT_SYSTEM_PROMPT` + `formatContactToolsPrompt` + `formatPiCodingPrompt` tell the model to call these from natural language (开新对话 / 找项目 / 现有对话 / 查看助手设定·默认提示词 / 改默认提示词·设置人设 / 建助理 / 建会话·继续会话 / 监听会话 / 停止会话 / 排定时任务 / 给 X 说一声). Argument schemas travel only in the native tool definitions. A reply without the tool call does nothing; never say 已创建 / 已发送 / 已停止 unless the tool returned. Tool results are sent as native tool-role messages with JSON `{ isError, content }`; assistant calls keep their arguments/IDs so multi-step turns keep call/result association. The harness replaces every `{{LANGUAGE}}` token — in the built-in prompt and in `defaultPrompt` — with the UI locale sent on the composer payload (`language` field, whitelisted locale code → display name). Background/settle turns recall the last locale seen for that assistant; unknown or missing locales resolve to `the user's interface language`, so the token never leaks into the prompt.
262
+ - If the user asked for `new_conversation` / `clear_chat_history` / `list_projects` / `list_sessions` / `get_assistant_settings` / `update_default_prompt` / `create_assistant` / `schedule_task` / `message_assistant` / `watch_session` / `stop_session` / `assign_session` and the first completion has no tool call, the harness runs **one** follow-up completion whose user content is only `Call the requested tool now; do not claim success without its result.` If still no tool, the turn replies that it could not complete and does not fake a card. No slash commands. No second store.
263
263
 
264
264
  **Clear memory vs clear chat history (this PR)**
265
265
 
266
266
  - `new_conversation` clears **LLM memory only**. It advances the durable per-assistant context boundary in `assistant_contact_context_boundary` (`after_ordinal` watermark). `GET /:id/contact/messages` keeps the full transcript. Later `contactHistoryForLlm` returns only messages with `ordinal > after_ordinal`. The model authors the confirmation from the actual reset result. Natural language default (safe): 开新对话 / new conversation / 清除记忆 / clear memory / clear chat / start over.
267
- - `clear_chat_history` **deletes** this assistant's contact transcript via `deleteContactMessages` (messages, parts, watches) and clears the boundary. The model authors the confirmation from the actual reset result. Natural-language tool-selection hint (missed-fence retry): 清空/清除/删除聊天记录 / clear chat history / delete chat history. Negation (不要清除聊天记录) is not a wipe request hint. When the model calls the tool, the wipe **executes** — there is no separate user-text authorization gate and no silent/denied bubble protocol. Real storage failures still surface as tool errors.
267
+ - `clear_chat_history` **deletes** this assistant's contact transcript via `deleteContactMessages` (messages, parts, watches) and clears the boundary. The model authors the confirmation from the actual reset result. Natural-language tool-selection hint (missed-tool retry): 清空/清除/删除聊天记录 / clear chat history / delete chat history. Negation (不要清除聊天记录) is not a wipe request hint. When the model calls the tool, the wipe **executes** — there is no separate user-text authorization gate and no silent/denied bubble protocol. Real storage failures still surface as tool errors.
268
268
  - Tool wipe (`upToOrdinal` = current turn's user ordinal) **keeps only** `role=user` rows with `ordinal >= ceiling` (the wipe request itself + later-admitted queued users) and their parts/`messageID`s. It **deletes all other roles at any ordinal** (prior users, assistant/peer/error/cards) — including late writes from an earlier still-running lane whose ordinal landed after the wipe user — so leftover A replies/cards cannot pollute the transcript or later LLM history. Watches and the context boundary always clear. Keeping the wipe user avoids delete+re-admit reordering queued users before it. Direct `POST /api/yuri/assistants/:id/contact/reset` → `resetContact` without a ceiling deletes **every** transcript row (existing contract; concurrent in-flight admissions are not preserved on that path).
269
269
  - Service also exposes `clearContactMemory` for the watermark path (`new_conversation`). Neither path calls OpenCode `session/new` / `createNew`.
270
270
  - Both tools terminate mutations (`terminate: true`). Persist only the isolated model confirmation. Discard leftover assistant text and cards from the same pre-reset generation. Tool result confirmation constants remain internal model input.
@@ -376,7 +376,7 @@ Both HTTP snapshot aliases call `ensureDefaultAssistant` before reading. A never
376
376
 
377
377
  - `POST /api/yuri/assistants/:id/messages` returns **202** `{ messageID, admitted: true, binding }` as soon as the **user row** is persisted (`status: complete`). It does **not** wait for the LLM turn. Validation errors still fail synchronously with 4xx before admit.
378
378
  - After admit: bump revision + `yuri:assistants-changed`, register active contact turn (`queued`), broadcast `yuri:contact-turn-start` `{ assistantID, turnID, messageID, occurredAt }` (`turnID` = client `messageID`), then kick `runContactTurn` asynchronously (serialized per assistant). Lane start marks the turn `running`. Lane start marks the turn `running` and bumps revision. Same `messageID`+payload replays admission once (`replayed: true`) without a second lane run; payload mismatch → `idempotency_conflict`. Failures persist a durable assistant `status: error` bubble for query recovery. Catalog/project list loads use a bounded deadline so the lane cannot hang forever.
379
- - Contact SSE reuses `/api/yuri/events`: `yuri:contact-bubble-delta` `{ assistantID, turnID, bubbleIndex, delta, done, occurredAt }`. Explicit public prefix records publish during generation; ordinary raw tokens remain private and legacy short spoken preambles publish after parsing. Each `done:true` bubble persists immediately as `${userMessageID}:bubble:${index+1}` and bumps `assistants-changed`, allowing another client to fetch it before the turn ends. Token deltas (`done:false`) remain ephemeral. Turn-global indices continue from `projectStreamedContactTurnBubbles` plus the current completion's published records, including corrections. On normal turns these messages form the final array's stable prefix and turn-end persistence adds only the remainder. Every tool result stays model-only; missed-tool exhaustion with no model text becomes an error. Tool cards persist on `onCard` with the existing `${userMessageID}:card:${index+1}` identity.
379
+ - Contact SSE reuses `/api/yuri/events`: `yuri:contact-bubble-delta` `{ assistantID, turnID, bubbleIndex, delta, done, occurredAt }`. `notify_user` notes publish when their response arrives; text beside tool calls remains private. Each `done:true` bubble persists immediately as `${userMessageID}:bubble:${index+1}` and bumps `assistants-changed`, allowing another client to fetch it before the turn ends. Token deltas (`done:false`) remain ephemeral. Turn-global indices continue from `projectStreamedContactTurnBubbles` plus the current completion's published records, including corrections. On normal turns these messages form the final array's stable prefix and turn-end persistence adds only the remainder. Every tool result stays model-only; missed-tool exhaustion with no model text becomes an error. Tool cards persist on `onCard` with the existing `${userMessageID}:card:${index+1}` identity.
380
380
  - Turn end: strip/parse/tools (existing), persist any **remaining** assistant bubbles + cards (skip ids already published mid-turn; never re-insert the user row), clear active contact turn, bump + assistants-changed (error paths bump even without assistant rows), broadcast `yuri:contact-turn-end` `{ assistantID, turnID, status: 'complete'|'error', error?, occurredAt }`. On failure the admitted user row stays; clients must not spin forever. Completing a contact turn also sends the same completion notification path as a normal contact: SMS-style title (assistant name) + body (spoken bubbles), via desktop / UI SSE / push, gated by `notifyOnCompletion`.
381
381
  - **Successful `new_conversation` / `clear_chat_history`:** mid-turn spoken/card publishes for that turn are discarded. `persistContactAssistantReply({ reset:true })` deletes this turn's `role=assistant` rows by `assistantID+turnID` (parts first; same delete pattern as contact-store, **not** `deleteContactMessages`) inside the existing write transaction, then inserts the single confirm bubble and bumps revision. Clearing user, queued users, peers, older turns, watches, generation, context boundary, and read watermark stay. Late bubble/card publish after reset success is ignored; `spokenByIndex` and `assignedCards` clear. Failure keeps prior error semantics.
382
382
  - **`stop_session` abort race:** before `session.interrupt`, the service registers a private per-`sessionID` inflight map (shared promise + observed terminal). Concurrent stop calls on the same worker share that promise. While inflight, `reportAssignedSession` only stashes terminals (`cancelled` > `error` > `complete`) and delays watch writes / continuations. Abort success (including silent no-SSE): release map, `cancelAssignedResumes({ sessionID })`, then `reportAssignedSession(cancelled, resume=false)`. Abort throw / 404 / error / `data:false` / signal failure: release map, replay one observed terminal through the normal reporter when present (else watch unchanged), return the real tool failure. `close()` clears the map; late events stay cancelled-idempotent.
@@ -410,7 +410,7 @@ Assign/watch tools forward the contact AbortSignal into their service calls and
410
410
 
411
411
  ### Referenced conversation content
412
412
 
413
- `read_session` is a read-only contact tool available on user turns and background notifications. An `@session:<id>` chip supplies identity only. The model reads contents through this tool before answering about the reference, and treats returned messages as quoted data, never as new user instructions or authorization to resume/watch/mutate. The quoted payload stays on the tool transcript for the model; contact bubbles keep only the spoken preamble and the post-read reply.
413
+ `read_session` is a read-only contact tool available on user turns and background notifications. An `@session:<id>` chip supplies identity only. The model reads contents through this tool before answering about the reference, and treats returned messages as quoted data, never as new user instructions or authorization to resume/watch/mutate. The quoted payload stays on the tool transcript for the model; contact bubbles keep only `notify_user` notes and the post-read reply.
414
414
 
415
415
  The service resolves the exact session and registered project through the existing authoritative session resolver, then calls SDK `message.list` with `limit` (default 20, maximum 50) and the turn AbortSignal. The first page sends `order=desc`; a continuation sends only the opaque `before` as `cursor` (upstream rejects `order` together with `cursor`). Native v2 rows are projected to role + parts and quoted oldest→newest. The upstream body `cursor.next` (falling back to the `x-next-cursor` header) is returned unchanged as `nextCursor`. Missing sessions, transport errors, malformed message lists and cross-session message identity mismatches fail closed. Empty successful lists remain distinguishable from failures.
416
416
 
@@ -1,18 +1,4 @@
1
1
  const SENTENCE = /(?<=[.!?])\s+(?=[A-Z“"‘])/u;
2
- const CONTACT_PLANNING = /\b(let me think|i should|i need to|i'll call|i will call|the user (said|wants|asked)|actually,?|hmm\.?|assign_session|watch_session|stop_session|list_projects|list_sessions|create_assistant|schedule_task|tool call|projectPath)\b/i;
3
-
4
- /**
5
- * A short spoken contact line (not chain-of-thought). Shown before a tool and kept.
6
- */
7
- export function isContactSpokenPreamble(text, { maxChars = 80 } = {}) {
8
- if (typeof text !== 'string') return false;
9
- const next = text.replace(/\r\n/g, '\n').trim();
10
- if (!next || next.length > maxChars) return false;
11
- if (/\n{2,}/u.test(next)) return false;
12
- if (/```/.test(next)) return false;
13
- if (CONTACT_PLANNING.test(next)) return false;
14
- return true;
15
- }
16
2
 
17
3
  /**
18
4
  * Split model output into short contact bubbles.
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it } from 'vitest'
2
- import { isContactSpokenPreamble, splitContactBubbles } from './bubbles.js'
2
+ import { splitContactBubbles } from './bubbles.js'
3
3
 
4
4
  describe('splitContactBubbles', () => {
5
5
  it('splits on blank lines into short bubbles', () => {
@@ -17,20 +17,3 @@ describe('splitContactBubbles', () => {
17
17
  expect(splitContactBubbles(' \n\n ')).toEqual([])
18
18
  })
19
19
  })
20
-
21
- describe('isContactSpokenPreamble', () => {
22
- it('accepts a short spoken line', () => {
23
- expect(isContactSpokenPreamble('我去找一下')).toBe(true)
24
- expect(isContactSpokenPreamble('On it.')).toBe(true)
25
- })
26
-
27
- it('rejects chain-of-thought and tool narration', () => {
28
- expect(isContactSpokenPreamble('Let me think — I should match the project and call assign_session.')).toBe(false)
29
- expect(isContactSpokenPreamble('I need to list_projects first.')).toBe(false)
30
- })
31
-
32
- it('rejects long or multi-bubble text', () => {
33
- expect(isContactSpokenPreamble('a'.repeat(81))).toBe(false)
34
- expect(isContactSpokenPreamble('先找项目。\n\n再开会话。')).toBe(false)
35
- })
36
- })
@@ -52,7 +52,42 @@ const AVATAR_GUIDE = [
52
52
  'Only seed is editable here; style, colors, facial features, custom URLs and uploaded images are not supported.',
53
53
  'Keep the current avatarSeed to restore it later. Avatar changes preserve identity and conversations.',
54
54
  ].join('\n');
55
- const CONTACT_TOOL_FENCE = 'yuri-tool';
55
+ export const NOTIFY_USER_TOOL_NAME = 'notify_user';
56
+ export const STAY_SILENT_TOOL_NAME = 'stay_silent';
57
+ export const NOTIFY_USER_MAX_CHARS = 2000;
58
+
59
+ /**
60
+ * Harness-owned conversation tools. notify_user is the only mid-turn channel to
61
+ * the user; plain text beside other tool calls stays private. The stream function
62
+ * publishes notify_user text when the response arrives, so execution only
63
+ * acknowledges it. stay_silent lets a background review finish without a reply.
64
+ */
65
+ export function createNotifyUserTool() {
66
+ return {
67
+ name: NOTIFY_USER_TOOL_NAME,
68
+ label: 'Notify user',
69
+ description: 'Send the user a short progress message while you keep working; batch it with your next tool call. Use only when it tells them 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. Never use it to announce the next step or repeat the plan. The final answer is your plain reply, not this tool.',
70
+ parameters: typeboxObject({ text: typeboxString('Short message in the user language.') }),
71
+ execute: async (_toolCallId, params) => {
72
+ const text = typeof params?.text === 'string' ? params.text.trim() : '';
73
+ if (!text || text.length > NOTIFY_USER_MAX_CHARS) {
74
+ return { content: [{ type: 'text', text: `notify_user needs 1-${NOTIFY_USER_MAX_CHARS} characters of text.` }], details: { error: 'validation_error' }, terminate: false };
75
+ }
76
+ return { content: [{ type: 'text', text: 'Delivered.' }], details: { delivered: true }, terminate: false };
77
+ },
78
+ };
79
+ }
80
+
81
+ export function createStaySilentTool() {
82
+ return {
83
+ name: STAY_SILENT_TOOL_NAME,
84
+ label: 'Stay silent',
85
+ description: 'End this background review without replying to the user. Call it alone, only when no reply is needed.',
86
+ parameters: typeboxObject({}),
87
+ execute: async () => ({ content: [{ type: 'text', text: 'Silent.' }], details: { silent: true }, terminate: true }),
88
+ };
89
+ }
90
+
56
91
  export const ASSIGNED_SESSION_FALLBACK_BUBBLE = 'Opened a coding session.';
57
92
  export const WATCHED_SESSION_FALLBACK_BUBBLE = 'Watching that coding session.';
58
93
  export const STOPPED_SESSION_FALLBACK_BUBBLE = '已停止该会话。';
@@ -119,7 +154,7 @@ const bashAliasCommand = (name, args = {}) => {
119
154
  return `if command -v rg >/dev/null 2>&1; then rg --files -g ${shellQuote(pattern)} ${target}; else find ${target} -name ${shellQuote(pattern)}; fi`;
120
155
  };
121
156
 
122
- export const MISSED_FENCE_RETRY_USER_TEXT = 'emit the fence now, do not claim success.';
157
+ export const MISSED_FENCE_RETRY_USER_TEXT = 'Call the requested tool now; do not claim success without its result.';
123
158
 
124
159
  const CREATE_ASSISTANT_INTENT = /建助理|新建[^。\n!]{0,24}助理|创建[^。\n!]{0,24}助理|加一个助理|create (?:an |a new )?assistant|new assistant/iu;
125
160
  // Changing or reviewing existing tasks starts with list_scheduled_tasks, not schedule_task.
@@ -404,178 +439,42 @@ const allowedToolName = (name, allowedNames) => {
404
439
  return BASH_ALIAS_TOOLS.has(next) && allowedNames.has('bash');
405
440
  };
406
441
 
407
- const parseToolPayload = (raw, allowedNames) => {
408
- let parsed;
409
- try {
410
- parsed = JSON.parse(raw);
411
- } catch {
412
- return null;
413
- }
414
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
415
- const name = typeof parsed.name === 'string' ? parsed.name.trim() : '';
442
+ const normalizeToolCall = (name, args, allowedNames) => {
416
443
  if (!allowedToolName(name, allowedNames)) return null;
417
- const args = parsed.arguments;
418
- if (args != null && (typeof args !== 'object' || Array.isArray(args))) return null;
419
- const normalizedArgs = args && typeof args === 'object' ? args : {};
444
+ if (args == null || typeof args !== 'object' || Array.isArray(args)) return null;
420
445
  if (!allowedNames.has(name) && BASH_ALIAS_TOOLS.has(name)) {
421
- const command = bashAliasCommand(name, normalizedArgs);
446
+ const command = bashAliasCommand(name, args);
422
447
  if (!command) return null;
423
- const timeout = typeof normalizedArgs.timeout === 'number' ? { timeout: normalizedArgs.timeout } : {};
448
+ const timeout = typeof args.timeout === 'number' ? { timeout: args.timeout } : {};
424
449
  return { name: 'bash', arguments: { command, ...timeout } };
425
450
  }
426
- return { name, arguments: normalizedArgs };
427
- };
428
-
429
- const describeRejectedToolPayload = (raw, allowedNames) => {
430
- const fallback = 'Invalid or unavailable tool in yuri-tool fence';
431
- let parsed;
432
- try { parsed = JSON.parse(raw); }
433
- catch { return `${fallback}: the payload is not valid JSON.`; }
434
- const name = typeof parsed?.name === 'string' ? parsed.name.trim() : '';
435
- if (name && !allowedToolName(name, allowedNames)) {
436
- return `${fallback}: "${name.slice(0, 80)}" is not an available tool. Use only: ${[...allowedNames].join(', ')}. If no available tool can do the task, say so in a final answer.`;
437
- }
438
- return `${fallback}: expected {"name":"<tool>","arguments":{...}}.`;
451
+ return { name, arguments: args };
439
452
  };
440
453
 
454
+ /**
455
+ * Normalize native function calls: shell-style aliases run through bash, and an
456
+ * unavailable or malformed call becomes an actionable correction for the model.
457
+ */
441
458
  export function parseContactNativeToolCalls(calls, allowedNames) {
442
459
  const allowed = new Set(allowedNames);
443
460
  const toolCalls = [];
444
461
  for (const call of calls) {
462
+ const name = typeof call?.function?.name === 'string' ? call.function.name.trim() : '';
445
463
  let args;
446
- try { args = JSON.parse(call.function.arguments); }
447
- catch { return { toolCalls: [], protocolError: 'Tool arguments must be valid JSON.' }; }
448
- const raw = JSON.stringify({ name: call.function.name, arguments: args });
449
- const parsed = parseToolPayload(raw, allowed);
450
- if (!parsed) return { toolCalls: [], protocolError: describeRejectedToolPayload(raw, allowed) };
451
- toolCalls.push({ ...parsed, id: call.id });
452
- }
453
- return { toolCalls, protocolError: '' };
454
- }
455
-
456
- const extractJsonObjectAt = (text, start) => {
457
- if (text[start] !== '{') return null;
458
- let depth = 0;
459
- let inString = false;
460
- let escape = false;
461
- for (let index = start; index < text.length; index += 1) {
462
- const character = text[index];
463
- if (inString) {
464
- if (escape) {
465
- escape = false;
466
- continue;
467
- }
468
- if (character === '\\') {
469
- escape = true;
470
- continue;
471
- }
472
- if (character === '"') inString = false;
473
- continue;
474
- }
475
- if (character === '"') {
476
- inString = true;
477
- continue;
478
- }
479
- if (character === '{') depth += 1;
480
- else if (character === '}') {
481
- depth -= 1;
482
- if (depth === 0) return text.slice(start, index + 1);
483
- }
484
- }
485
- return null;
486
- };
487
-
488
- const findToolFenceEnd = (text, start) => {
489
- let inString = false;
490
- let escaped = false;
491
- for (let index = start; index < text.length; index += 1) {
492
- const character = text[index];
493
- if (inString) {
494
- if (escaped) escaped = false;
495
- else if (character === '\\') escaped = true;
496
- else if (character === '"') inString = false;
497
- } else if (character === '"') {
498
- inString = true;
499
- } else if (text.startsWith('```', index)) {
500
- return index;
464
+ try { args = JSON.parse(call?.function?.arguments || '{}'); }
465
+ catch { return { toolCalls: [], protocolError: `Arguments for "${name.slice(0, 80)}" must be valid JSON.` }; }
466
+ const normalized = normalizeToolCall(name, args, allowed);
467
+ if (!normalized) {
468
+ return {
469
+ toolCalls: [],
470
+ protocolError: name && !allowedToolName(name, allowed)
471
+ ? `"${name.slice(0, 80)}" is not an available tool. Use only: ${[...allowed].join(', ')}. If no available tool can do the task, say so in your reply.`
472
+ : `Invalid arguments for "${name.slice(0, 80)}".`,
473
+ };
501
474
  }
475
+ toolCalls.push({ ...normalized, id: call.id });
502
476
  }
503
- return -1;
504
- };
505
-
506
- export function stripContactToolFences(text) {
507
- if (typeof text !== 'string') return '';
508
- return text.replace(new RegExp(`\`\`\`${CONTACT_TOOL_FENCE}[\\s\\S]*?\`\`\``, 'gu'), '').trim();
509
- }
510
-
511
- export function parseContactToolCalls(text, allowedNames = []) {
512
- const allowed = new Set(
513
- (Array.isArray(allowedNames) ? allowedNames : [])
514
- .filter((name) => typeof name === 'string' && name.trim())
515
- .map((name) => name.trim()),
516
- );
517
- const raw = typeof text === 'string' ? text : '';
518
- const toolCalls = [];
519
- const visible = [];
520
- let visibleStart = 0;
521
- for (let index = 0; index < raw.length;) {
522
- if (raw.startsWith('```', index)) {
523
- const header = raw.slice(index + 3).match(/^([^\r\n`]*)/u)?.[0] || '';
524
- const explicit = raw.startsWith(CONTACT_TOOL_FENCE, index + 3)
525
- && /[\s{]|^$/u.test(raw[index + 3 + CONTACT_TOOL_FENCE.length] || '');
526
- const genericJson = header.trim() === 'json' || header.trim() === '' || header.trimStart().startsWith('{');
527
- const payloadStart = index + 3 + (explicit
528
- ? CONTACT_TOOL_FENCE.length
529
- : header.trimStart().startsWith('{') ? 0 : header.length);
530
- const end = explicit || genericJson
531
- ? findToolFenceEnd(raw, payloadStart)
532
- : raw.indexOf('```', payloadStart);
533
- if (explicit) {
534
- if (end < 0) {
535
- return { chatText: '', toolCalls: [], protocolError: 'Unclosed yuri-tool fence' };
536
- }
537
- const toolCall = parseToolPayload(raw.slice(payloadStart, end).trim(), allowed);
538
- if (!toolCall) {
539
- return { chatText: '', toolCalls: [], protocolError: describeRejectedToolPayload(raw.slice(payloadStart, end).trim(), allowed) };
540
- }
541
- toolCalls.push(toolCall);
542
- visible.push(raw.slice(visibleStart, index));
543
- visibleStart = end + 3;
544
- }
545
- if (!explicit && genericJson && end >= 0) {
546
- const toolCall = parseToolPayload(raw.slice(payloadStart, end).trim(), allowed);
547
- if (toolCall) {
548
- toolCalls.push(toolCall);
549
- visible.push(raw.slice(visibleStart, index));
550
- visibleStart = end + 3;
551
- }
552
- }
553
- // Other fenced prose/examples and final declarations are not tool invocations.
554
- index = end < 0 ? raw.length : end + 3;
555
- continue;
556
- }
557
- if (raw[index] !== '{') {
558
- index += 1;
559
- continue;
560
- }
561
- const snippet = extractJsonObjectAt(raw, index);
562
- if (!snippet) {
563
- // Do not reinterpret a nested object from malformed outer JSON as an
564
- // operation, or repeatedly scan the same unfinished suffix.
565
- return { chatText: '', toolCalls: [], protocolError: 'Unclosed JSON object in tool response' };
566
- }
567
- const toolCall = parseToolPayload(snippet, allowed);
568
- if (toolCall) {
569
- toolCalls.push(toolCall);
570
- visible.push(raw.slice(visibleStart, index));
571
- visibleStart = index + snippet.length;
572
- }
573
- // Consume the whole outer object even if it is ordinary JSON. Its nested
574
- // arguments or example objects must never become additional operations.
575
- index += snippet.length;
576
- }
577
- visible.push(raw.slice(visibleStart));
578
- return { chatText: visible.join('').trim(), toolCalls };
477
+ return { toolCalls, protocolError: '' };
579
478
  }
580
479
 
581
480
  const isNegatedAt = (text, index) => INTENT_NEGATION.test(text.slice(Math.max(0, index - 12), index));
@@ -669,7 +568,9 @@ export function detectRequestedContactTools(userText, allowedNames = []) {
669
568
  }
670
569
 
671
570
  export function contactTurnHasToolResult(messages) {
672
- return (Array.isArray(messages) ? messages : []).some((message) => message?.role === 'toolResult');
571
+ return (Array.isArray(messages) ? messages : []).some((message) => (
572
+ message?.role === 'toolResult' && message.toolName !== NOTIFY_USER_TOOL_NAME
573
+ ));
673
574
  }
674
575
 
675
576
  const trim = (value, max = 10_000) => {
@@ -777,35 +678,6 @@ export function resolveAssistantTarget(params = {}, assistants = []) {
777
678
  return matches[0];
778
679
  }
779
680
 
780
- /**
781
- * Serialize a tool parameter schema for the contact system prompt.
782
- * Accepts plain JSON-schema-like objects and TypeBox schemas (JSON.stringify).
783
- * Strips non-enumerable TypeBox markers (~kind / ~optional).
784
- */
785
- export function serializeToolParametersForPrompt(parameters) {
786
- if (parameters == null) return '{"type":"object","properties":{}}';
787
- try {
788
- const text = JSON.stringify(parameters, (_key, value) => {
789
- if (typeof value === 'function' || typeof value === 'symbol') return undefined;
790
- return value;
791
- });
792
- if (typeof text === 'string' && text.trim() && text !== 'undefined') return text;
793
- } catch {
794
- // Fall through to empty object schema.
795
- }
796
- return '{"type":"object","properties":{}}';
797
- }
798
-
799
- /** One catalog line: name, description, and full arguments schema. */
800
- export function formatApplicationToolCatalogEntry(tool) {
801
- if (!tool || typeof tool.name !== 'string' || !tool.name.trim()) return '';
802
- const name = tool.name.trim();
803
- const description = typeof tool.description === 'string' && tool.description.trim()
804
- ? tool.description.trim()
805
- : (typeof tool.label === 'string' && tool.label.trim() ? tool.label.trim() : name);
806
- return `- ${name}: ${description}\n arguments schema: ${serializeToolParametersForPrompt(tool.parameters)}`;
807
- }
808
-
809
681
  export function formatContactToolsPrompt(tools) {
810
682
  const list = Array.isArray(tools)
811
683
  ? tools.filter((tool) => tool?.name && !isPiCodingToolName(tool.name))
@@ -827,43 +699,7 @@ export function formatContactToolsPrompt(tools) {
827
699
  'When they want to stop/abort a running coding session (停止会话 / stop session), call stop_session with sessionID — that calls real OpenCode session.abort.',
828
700
  'When they want a scheduled task (排定时任务 / schedule daily ping), call schedule_task.',
829
701
  'When they want to tell another assistant (给 PeerQA 说一声 / message PeerQA), call message_assistant.',
830
- `Call exactly one Yuri operation tool per reply; coding tools may be batched as described by the workspace protocol.`,
831
- `\`\`\`${CONTACT_TOOL_FENCE}`,
832
- `{"name":"${NEW_CONVERSATION_TOOL_NAME}","arguments":{}}`,
833
- '```',
834
- `\`\`\`${CONTACT_TOOL_FENCE}`,
835
- `{"name":"${CLEAR_CHAT_HISTORY_TOOL_NAME}","arguments":{}}`,
836
- '```',
837
- `\`\`\`${CONTACT_TOOL_FENCE}`,
838
- `{"name":"${LIST_PROJECTS_TOOL_NAME}","arguments":{"query":"yuri yee"}}`,
839
- '```',
840
- `\`\`\`${CONTACT_TOOL_FENCE}`,
841
- `{"name":"${LIST_SESSIONS_TOOL_NAME}","arguments":{"projectPath":"/path/to/repo","query":"login"}}`,
842
- '```',
843
- `\`\`\`${CONTACT_TOOL_FENCE}`,
844
- `{"name":"${GET_ASSISTANT_SETTINGS_TOOL_NAME}","arguments":{}}`,
845
- '```',
846
- `\`\`\`${CONTACT_TOOL_FENCE}`,
847
- `{"name":"${UPDATE_DEFAULT_PROMPT_TOOL_NAME}","arguments":{"to":"OpenCode 配置助手","prompt":"Be terse and reply in Chinese."}}`,
848
- '```',
849
- `\`\`\`${CONTACT_TOOL_FENCE}`,
850
- `{"name":"${CREATE_ASSISTANT_TOOL_NAME}","arguments":{"name":"FlowQA","model":"opencode-go/deepseek-v4-flash"}}`,
851
- '```',
852
- `\`\`\`${CONTACT_TOOL_FENCE}`,
853
- `{"name":"${SCHEDULE_TASK_TOOL_NAME}","arguments":{"name":"Daily ping","prompt":"ping","time":"18:00","timezone":"Asia/Shanghai"}}`,
854
- '```',
855
- `\`\`\`${CONTACT_TOOL_FENCE}`,
856
- `{"name":"${MESSAGE_ASSISTANT_TOOL_NAME}","arguments":{"to":"PeerQA","text":"hello-from-assistant 写好了"}}`,
857
- '```',
858
- `\`\`\`${CONTACT_TOOL_FENCE}`,
859
- `{"name":"${ASSIGN_SESSION_TOOL_NAME}","arguments":{"prompt":"...","projectPath":"...","model":"provider/model-id"}}`,
860
- '```',
861
- `\`\`\`${CONTACT_TOOL_FENCE}`,
862
- `{"name":"${WATCH_SESSION_TOOL_NAME}","arguments":{"sessionID":"ses_example"}}`,
863
- '```',
864
- `\`\`\`${CONTACT_TOOL_FENCE}`,
865
- `{"name":"${STOP_SESSION_TOOL_NAME}","arguments":{"sessionID":"ses_example"}}`,
866
- '```',
702
+ 'Call exactly one Yuri operation tool per response; coding tools may be batched.',
867
703
  'If the user asked for more than one of these, do them in that order across turns: new_conversation or clear_chat_history, then list_projects, then list_sessions, then get_assistant_settings or update_default_prompt, then create_assistant, then schedule_task, then message_assistant, then watch_session or stop_session, then assign_session.',
868
704
  'Prerequisite lookups (list_projects / list_sessions) may run before assign_session / watch_session / stop_session in the same turn. After a successful assign_session or watch_session the turn ends — never call them again in that turn, and do not keep looping tools.',
869
705
  'new_conversation advances this contact\'s LLM context boundary only. Stored messages and watches remain. It never calls session/new or createNew.',
@@ -881,13 +717,10 @@ export function formatContactToolsPrompt(tools) {
881
717
  'To review or change existing scheduled tasks, call list_scheduled_tasks, then update_scheduled_task with the exact taskID and projectID it returned. Update one task per call and pass only the fields to change.',
882
718
  'message_assistant is read-only: it inserts into the other contact transcript. It never runs promptAsync or mutates sessions or files. Never assign through a peer message.',
883
719
  'A reply without the tool call does nothing — agreeing in Chinese (好的 / 我来创建 / 我去说一声) is not sending.',
884
- 'A yuri-message prefix is not required before a tool fence; publish one only when it tells the user something new. Keep private reasoning, tool names, and raw traces out of public messages.',
885
720
  'Never say 已创建, 已发送, 已停止, created, scheduled, opened, watched, stopped, or sent unless the tool already returned success.',
886
721
  'With an empty registered catalog, first discover the relevant existing workspace through list_sessions and directory lookups, then ask the user to register that workspace in Settings before assignment.',
887
722
  'After a tool that changes state succeeds, confirm in one short bubble; lookups need no separate confirmation. The user sees a contact card, not tool traces. After successful assign_session or watch_session the session card plus that short confirm is enough — stop.',
888
- 'These are application-owned Yuri contact tools (not OpenCode native tools, not MCP, not skill directory entries). Use only the names and argument schemas below:',
889
- 'Available Yuri tools:',
890
- ...list.map((tool) => formatApplicationToolCatalogEntry(tool)).filter(Boolean),
723
+ 'These are application-owned Yuri contact tools (not OpenCode native tools, not MCP, not skill directory entries). Use only the provided tool names and their schemas.',
891
724
  ].join('\n');
892
725
  }
893
726