@yuriai/web 0.2.8-beta.1 → 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.
- package/dist/assets/{AgentAvatar-MzDm6uBf.js → AgentAvatar--DsfGfhZ.js} +1 -1
- package/dist/assets/{AssistantView-Df-G2DX8.js → AssistantView-Bf19-qvJ.js} +3 -3
- package/dist/assets/{DiagramView-BoVqJRQb.js → DiagramView-UvYyjtWA.js} +1 -1
- package/dist/assets/{FadeInOnReveal-DkmfVoTO.js → FadeInOnReveal-NAFOww9Y.js} +1 -1
- package/dist/assets/{GuiPluginSurface-DxLoeTDb.js → GuiPluginSurface-DNzJNcMh.js} +1 -1
- package/dist/assets/{GuiPluginWindow-dDG5Uyqb.js → GuiPluginWindow-C73klYx3.js} +1 -1
- package/dist/assets/{Icon-BjiyvtB2.js → Icon-Cy25fgQb.js} +1 -1
- package/dist/assets/{ImageLoadingPlaceholder-CUKFQTAG.js → ImageLoadingPlaceholder-DGRjdn_K.js} +1 -1
- package/dist/assets/{LoadingImage-B7cT_4Oe.js → LoadingImage-2pPdTFHh.js} +1 -1
- package/dist/assets/{MarkdownRenderer-DYi_qpYy.js → MarkdownRenderer-GuwP9qiJ.js} +2 -2
- package/dist/assets/{MarkdownRendererImpl-CMxRMFqp.js → MarkdownRendererImpl-tHItN1IG.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-DQ4urBZW.js → MarkstreamRendererImpl-Dh13e1UE.js} +1 -1
- package/dist/assets/{MobileDetailNavigation-C4fJlKdu.js → MobileDetailNavigation-CSxBgVuQ.js} +1 -1
- package/dist/assets/{MobileResizableSheet-C9YzOQis.js → MobileResizableSheet-BN07cmQQ.js} +1 -1
- package/dist/assets/{MobileShareBridge-DLC-TdRy.js → MobileShareBridge-7SAELdqu.js} +1 -1
- package/dist/assets/MobileTabPageHeader-Bbb36BtD.js +2 -0
- package/dist/assets/{MultiRunWindow-Cwp8-_Wh.js → MultiRunWindow-DbI9KTph.js} +1 -1
- package/dist/assets/{OnboardingScreen-D6iQ5qjF.js → OnboardingScreen-rp0qwvgz.js} +1 -1
- package/dist/assets/{OverlayScrollbar-Dbx1atD-.js → OverlayScrollbar-B--v-oQW.js} +1 -1
- package/dist/assets/{SettingsView-CYDk0wpN.js → SettingsView-C1AQoEIQ.js} +1 -1
- package/dist/assets/{SettingsWindow-Vuzphf9b.js → SettingsWindow-6M0ssWHM.js} +1 -1
- package/dist/assets/{TerminalView-Dhalx6_Z.js → TerminalView-bhL6Ccen.js} +1 -1
- package/dist/assets/{ToolOutputDialog-DBxSxWNh.js → ToolOutputDialog-BaLKI3Yc.js} +1 -1
- package/dist/assets/{YuriLogo-DvRSd5NN.js → YuriLogo-kwLWc5Hi.js} +1 -1
- package/dist/assets/{appThemeRegistry-JEhMXHGF.js → appThemeRegistry-Bk_N8btz.js} +1 -1
- package/dist/assets/{button-BSFWH-Ok.js → button-Dodw6LWV.js} +1 -1
- package/dist/assets/{capgoAdapter-BgD0wyhC.js → capgoAdapter-DqHX7fkj.js} +1 -1
- package/dist/assets/{collapsible-DaevjAvt.js → collapsible-C9kOfVDe.js} +1 -1
- package/dist/assets/{diagram-7OgmyecX.js → diagram-CfBQ9Icg.js} +1 -1
- package/dist/assets/{dialog-D1pXn_b9.js → dialog-D0bq7nr2.js} +1 -1
- package/dist/assets/{dropdown-menu.styles-CGHPvEgD.js → dropdown-menu.styles-CLxDPSrk.js} +1 -1
- package/dist/assets/{es-DJzbuYpv.js → es-Diy_UpPF.js} +1 -1
- package/dist/assets/{fileMentionTouchSelection-BQdfRBkk.js → fileMentionTouchSelection-C16Q21Ht.js} +1 -1
- package/dist/assets/{fr-YDYbYIZQ.js → fr-CPRTMaky.js} +1 -1
- package/dist/assets/{gitApi-DhDVqj9b.js → gitApi-_yKaBF0a.js} +1 -1
- package/dist/assets/{input-BhHXFla6.js → input-HddqDhRi.js} +1 -1
- package/dist/assets/{insertionBoundaries-BMe1F3uB.js → insertionBoundaries-CHqJLwJg.js} +1 -1
- package/dist/assets/{ja-SjX3NBJz.js → ja-Cc1jn0Ag.js} +1 -1
- package/dist/assets/{ko-BxcUEWjB.js → ko-CfHUuNNe.js} +1 -1
- package/dist/assets/{main-DXlMu2LF.js → main-Bja5DG1P.js} +2 -2
- package/dist/assets/{main-CfOYzhn0.js → main-njE9rVzm.js} +4 -4
- package/dist/assets/{markdownHeightCache-DV2j4PlS.js → markdownHeightCache-BQiIj0aM.js} +1 -1
- package/dist/assets/{mcpQueries-vxcQAIGB.js → mcpQueries-uM1Chfdc.js} +1 -1
- package/dist/assets/{miniChat-D48iGEEW.js → miniChat-DAwBa-3U.js} +2 -2
- package/dist/assets/{mobile-Cy5qSiDY.js → mobile-BQmrdXmD.js} +2 -2
- package/dist/assets/{mobileBackNavigation-QtBK9OSb.js → mobileBackNavigation-DsU3qQ8W.js} +1 -1
- package/dist/assets/{multirun-BR9a6EBo.js → multirun-DRL1Wf-K.js} +1 -1
- package/dist/assets/{native-config-CHySeHif.js → native-config-BMflOjo8.js} +1 -1
- package/dist/assets/{pl-vh0XFuDb.js → pl-mUyhvp8O.js} +1 -1
- package/dist/assets/{projectMeta-Bn2vBNDe.js → projectMeta-DK-kl6vM.js} +1 -1
- package/dist/assets/{pt-BR-Cv5tssQz.js → pt-BR-D3E4Wxao.js} +1 -1
- package/dist/assets/{readiness-BAssoNVf.js → readiness-CMHDs1YN.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-B9Kci_8q.js → renderElectronMiniChatApp-CkSP0eQz.js} +2 -2
- package/dist/assets/{renderMobileApp-CBivL8Ps.js → renderMobileApp-wELnHLDT.js} +4 -4
- package/dist/assets/{runtimeConfig-COdEwlK-.js → runtimeConfig-KpW0l510.js} +1 -1
- package/dist/assets/{runtimeEndpointReset-D3x76Qpf.js → runtimeEndpointReset-BBxpXfkE.js} +3 -3
- package/dist/assets/{scheduledTaskNavigation-BZ3B5bpN.js → scheduledTaskNavigation-CyPkVBKs.js} +1 -1
- package/dist/assets/{sessionChangeSummary-Dtgq0CWg.js → sessionChangeSummary-Bb7dqAie.js} +1 -1
- package/dist/assets/{sessionLookup--Wlr3e8X.js → sessionLookup-D_P3C7rX.js} +1 -1
- package/dist/assets/{sortable-tabs-strip-BnTV_KYG.js → sortable-tabs-strip-C-qSUWlr.js} +1 -1
- package/dist/assets/{speechSettingsQueries-D3fc_4Iy.js → speechSettingsQueries-BSBjx3wG.js} +1 -1
- package/dist/assets/src-CbY9YJrh.css +2 -0
- package/dist/assets/{store-CgQdmzpX.js → store-FxBFwq--.js} +2 -2
- package/dist/assets/{textarea-Deh9E1KP.js → textarea-BvfW0tsL.js} +1 -1
- package/dist/assets/{tooltip-DygQ-2xe.js → tooltip-BmKpb74n.js} +1 -1
- package/dist/assets/{types-D8_26ZKT.js → types-rJezumB4.js} +1 -1
- package/dist/assets/{uk-3a9vdLJ-.js → uk-D9iQbGbr.js} +1 -1
- package/dist/assets/{useAppFontEffects-DLT9jVl1.js → useAppFontEffects-DZ1W3_cy.js} +5 -5
- package/dist/assets/{useDesktopWindowControlsLayout-BNAZWH9L.js → useDesktopWindowControlsLayout-D_1DLCOD.js} +1 -1
- package/dist/assets/{useEffectiveDirectory-D2_-KCB7.js → useEffectiveDirectory-joUiryc3.js} +1 -1
- package/dist/assets/{useMobileNavigationStore-DJwk64Po.js → useMobileNavigationStore-BaQ7TIpx.js} +6 -6
- package/dist/assets/{useWorkerHighlightedLines-k48txabk.js → useWorkerHighlightedLines-CiU1xPjX.js} +1 -1
- package/dist/assets/{zh-CN-kwaUr5W5.js → zh-CN-mNVX6pMK.js} +1 -1
- package/dist/assets/{zh-TW-BBs44W7l.js → zh-TW-B7T0e-Qv.js} +1 -1
- package/dist/index.html +6 -6
- package/dist/mini-chat.html +6 -6
- package/dist/mobile.html +6 -6
- package/package.json +1 -1
- package/server/lib/assistants/DOCUMENTATION.md +18 -15
- package/server/lib/assistants/bubbles.js +0 -14
- package/server/lib/assistants/bubbles.test.js +1 -18
- package/server/lib/assistants/contact-tools.js +179 -211
- package/server/lib/assistants/contact-tools.test.js +35 -161
- package/server/lib/assistants/harness.js +76 -238
- package/server/lib/assistants/harness.test.js +255 -279
- package/server/lib/assistants/memory.http.test.js +2 -2
- package/server/lib/assistants/pi-tools.js +1 -54
- package/server/lib/assistants/pi-tools.test.js +5 -9
- package/server/lib/assistants/routes.js +1 -0
- package/server/lib/assistants/service.js +66 -1
- package/server/lib/assistants/service.test.js +60 -42
- package/server/lib/llm/DOCUMENTATION.md +3 -0
- package/server/lib/llm/completions.js +2 -1
- package/server/lib/llm/completions.test.js +9 -0
- package/server/lib/opencode/feature-routes-runtime.js +1 -0
- package/server/lib/scheduled-tasks/runtime.test.js +3 -3
- package/dist/assets/MobileTabPageHeader-CMbbtHh7.js +0 -2
- 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 {
|
|
3
|
+
import { splitContactBubbles } from './bubbles.js';
|
|
4
4
|
import {
|
|
5
5
|
contactTurnClearedChatHistory,
|
|
6
6
|
contactTurnHasSuccessfulReset,
|
|
@@ -10,9 +10,13 @@ import {
|
|
|
10
10
|
formatContactToolsPrompt,
|
|
11
11
|
formatConnectedModelsPrompt,
|
|
12
12
|
formatRegisteredProjectsPrompt,
|
|
13
|
+
createNotifyUserTool,
|
|
14
|
+
createStaySilentTool,
|
|
13
15
|
MISSED_FENCE_RETRY_USER_TEXT,
|
|
14
|
-
|
|
15
|
-
|
|
16
|
+
NOTIFY_USER_MAX_CHARS,
|
|
17
|
+
NOTIFY_USER_TOOL_NAME,
|
|
18
|
+
parseContactNativeToolCalls,
|
|
19
|
+
STAY_SILENT_TOOL_NAME,
|
|
16
20
|
} from './contact-tools.js';
|
|
17
21
|
import {
|
|
18
22
|
createPiCodingRuntime,
|
|
@@ -106,8 +110,9 @@ export const CONTACT_SYSTEM_PROMPT = [
|
|
|
106
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.',
|
|
107
111
|
'Keep private reasoning and tool traces private.',
|
|
108
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.',
|
|
109
|
-
'
|
|
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.',
|
|
110
114
|
'Do not expose tool traces, Activity, or editor actions.',
|
|
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.',
|
|
111
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.',
|
|
112
117
|
'Understand natural language in any language, including Chinese: 开新对话 / 清除记忆 means new_conversation (LLM memory only, chat history stays), 清空聊天记录 means clear_chat_history (delete transcript), 找项目 means list_projects, 现有对话 means list_sessions, 查看助手设定 / 默认提示词 means get_assistant_settings (pass to="Name" for another assistant), 改默认提示词 / 设置人设 / 改某助手的默认提示词 means update_default_prompt (persists that assistant\'s settings, later turns only; pass to="OpenCode 配置助手" to edit another contact without changing this one), 建助理 means create_assistant, 建会话 / 开个新会话 / 继续会话 means assign_session, 监听会话 means watch_session, 停止/取消/打断会话 means stop_session, 插话 means steer_session, 归档会话 means archive_session, 删除会话 means delete_session, 排定时任务 means schedule_task, 给 X 说一声 means message_assistant, 发卡片 means emit a card via those tools — never ask the user to type /card or /dm.',
|
|
113
118
|
'You receive the registered project catalog every turn. Match the user goal against project labels and paths and existing OpenCode conversations via list_sessions. Start in the user-configured working directory; managed contacts start in the current server user home directory and can inspect user-global directories with read/bash. When the starting directory has no relevant session, walk its parent directories to find the nearest relevant existing OpenCode workspace using session directory metadata, then search that workspace for the requested project or conversation. Use an unscoped list_sessions lookup when broader context is needed. Prefer the user-configured directory and explicit session context; ask a short question when several relevant targets remain. Keep discovery bounded and use actual tool results as evidence.',
|
|
@@ -117,30 +122,16 @@ export const CONTACT_SYSTEM_PROMPT = [
|
|
|
117
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.',
|
|
118
123
|
].join(' ');
|
|
119
124
|
|
|
120
|
-
//
|
|
121
|
-
//
|
|
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.
|
|
122
127
|
const WORKSPACE_RESPONSE_PROTOCOL = [
|
|
123
|
-
'Workspace response protocol:
|
|
124
|
-
'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.',
|
|
125
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.',
|
|
126
|
-
'
|
|
127
|
-
'
|
|
128
|
-
'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.',
|
|
129
133
|
].join('\n');
|
|
130
134
|
|
|
131
|
-
const parseFinalResponse = (text, allowSilent = false) => {
|
|
132
|
-
const match = text.trim().match(/^```yuri-final\s*([\s\S]*?)```$/u);
|
|
133
|
-
if (!match) return null;
|
|
134
|
-
try {
|
|
135
|
-
const value = JSON.parse(match[1]);
|
|
136
|
-
if (allowSilent && value?.status === 'silent' && value.text === '') return { status: 'silent', text: '' };
|
|
137
|
-
if (!value || !['complete', 'blocked'].includes(value.status) || typeof value.text !== 'string' || !value.text.trim()) return null;
|
|
138
|
-
return { status: value.status, text: value.text.trim() };
|
|
139
|
-
} catch {
|
|
140
|
-
return null;
|
|
141
|
-
}
|
|
142
|
-
};
|
|
143
|
-
|
|
144
135
|
const emptyUsage = () => ({
|
|
145
136
|
input: 0,
|
|
146
137
|
output: 0,
|
|
@@ -180,9 +171,9 @@ const assistantMessage = (model, text, stopReason, errorMessage) => ({
|
|
|
180
171
|
/**
|
|
181
172
|
* streamFn for pi-agent-core. Calls Yuri completions (public HTTP stays
|
|
182
173
|
* non-streaming). In-process callers may pass onTextDelta/globalEventHub for
|
|
183
|
-
* the throwaway generate path.
|
|
184
|
-
*
|
|
185
|
-
*
|
|
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.
|
|
186
177
|
*/
|
|
187
178
|
const completionFileParts = (value) => (Array.isArray(value) ? value : [])
|
|
188
179
|
.filter((part) => part?.type === 'file' && typeof part.mime === 'string' && typeof part.url === 'string')
|
|
@@ -193,58 +184,6 @@ const completionFileParts = (value) => (Array.isArray(value) ? value : [])
|
|
|
193
184
|
...(typeof part.filename === 'string' && part.filename.trim() ? { filename: part.filename.trim() } : {}),
|
|
194
185
|
}));
|
|
195
186
|
|
|
196
|
-
/** Fence start (yuri-tool or generic ```) — stop live bubble deltas. */
|
|
197
|
-
const CONTACT_FENCE_START = /```/;
|
|
198
|
-
|
|
199
|
-
// Only explicitly public, complete prefix records may publish before completion.
|
|
200
|
-
// Retain at most one bounded incomplete record; ordinary text and tool JSON stay private.
|
|
201
|
-
function createPublicMessageReader(publish) {
|
|
202
|
-
const marker = '```yuri-message';
|
|
203
|
-
let pending = '';
|
|
204
|
-
let stopped = false;
|
|
205
|
-
return {
|
|
206
|
-
push(delta) {
|
|
207
|
-
if (stopped || typeof delta !== 'string') return;
|
|
208
|
-
pending += delta;
|
|
209
|
-
while (true) {
|
|
210
|
-
pending = pending.trimStart();
|
|
211
|
-
if (!pending || marker.startsWith(pending)) return;
|
|
212
|
-
if (!pending.startsWith(marker)) { stopped = true; return; }
|
|
213
|
-
const match = pending.match(/^```yuri-message[ \t]*\r?\n([^\n]+)\r?\n```/u);
|
|
214
|
-
if (match && match[0].length > 8192) { stopped = true; return; }
|
|
215
|
-
if (!match) {
|
|
216
|
-
if (pending.length > 8192) stopped = true;
|
|
217
|
-
return;
|
|
218
|
-
}
|
|
219
|
-
let value;
|
|
220
|
-
try {
|
|
221
|
-
value = JSON.parse(match[1]);
|
|
222
|
-
if (typeof value?.text !== 'string' || !value.text.trim() || value.text.length > 2000) {
|
|
223
|
-
stopped = true;
|
|
224
|
-
return;
|
|
225
|
-
}
|
|
226
|
-
} catch { stopped = true; return; }
|
|
227
|
-
publish(value.text.trim());
|
|
228
|
-
pending = pending.slice(match[0].length);
|
|
229
|
-
}
|
|
230
|
-
},
|
|
231
|
-
};
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
function stripPublicMessages(text) {
|
|
235
|
-
let rest = text.trimStart();
|
|
236
|
-
while (rest.startsWith('```yuri-message')) {
|
|
237
|
-
const match = rest.match(/^```yuri-message[ \t]*\r?\n([^\n]+)\r?\n```/u);
|
|
238
|
-
if (!match || match[0].length > 8192) throw new Error('Invalid public message record');
|
|
239
|
-
const value = JSON.parse(match[1]);
|
|
240
|
-
if (typeof value?.text !== 'string' || !value.text.trim() || value.text.length > 2000) {
|
|
241
|
-
throw new Error('Invalid public message text');
|
|
242
|
-
}
|
|
243
|
-
rest = rest.slice(match[0].length).trimStart();
|
|
244
|
-
}
|
|
245
|
-
return rest;
|
|
246
|
-
}
|
|
247
|
-
|
|
248
187
|
const assistantTextParts = (message) => (Array.isArray(message?.content) ? message.content : [])
|
|
249
188
|
.filter((part) => part?.type === 'text' && typeof part.text === 'string')
|
|
250
189
|
.map((part) => part.text)
|
|
@@ -252,7 +191,7 @@ const assistantTextParts = (message) => (Array.isArray(message?.content) ? messa
|
|
|
252
191
|
|
|
253
192
|
/**
|
|
254
193
|
* Streamed assistant bubbles already present in this turn's Agent messages.
|
|
255
|
-
*
|
|
194
|
+
* notify_user notes (tool turns) and final assistant text share splitContactBubbles.
|
|
256
195
|
* Independent messages keep duplicate text. Tool-result confirms are not streamed here.
|
|
257
196
|
*/
|
|
258
197
|
export function projectStreamedContactTurnBubbles(messages, turnStart = 0) {
|
|
@@ -265,100 +204,12 @@ export function projectStreamedContactTurnBubbles(messages, turnStart = 0) {
|
|
|
265
204
|
const hasTool = parts.some((part) => part?.type === 'toolCall');
|
|
266
205
|
const text = assistantTextParts(message).trim();
|
|
267
206
|
if (!text) continue;
|
|
268
|
-
if (hasTool && message.contactPublicText !== true
|
|
207
|
+
if (hasTool && message.contactPublicText !== true) continue;
|
|
269
208
|
for (const bubble of splitContactBubbles(text)) bubbles.push(bubble);
|
|
270
209
|
}
|
|
271
210
|
return bubbles;
|
|
272
211
|
}
|
|
273
212
|
|
|
274
|
-
/**
|
|
275
|
-
* Incremental bubble stream from live token deltas.
|
|
276
|
-
* - done:false = token increment for the active bubble
|
|
277
|
-
* - done:true = that bubble is complete (split off or finalized)
|
|
278
|
-
* - baseIndex offsets indices so later completions continue the turn sequence
|
|
279
|
-
* Stops when a markdown fence starts so tool JSON never leaks.
|
|
280
|
-
*/
|
|
281
|
-
export function createContactBubbleDeltaTracker(onBubbleDelta, { baseIndex = 0 } = {}) {
|
|
282
|
-
const emit = typeof onBubbleDelta === 'function' ? onBubbleDelta : null;
|
|
283
|
-
const offset = Number.isFinite(Number(baseIndex)) ? Math.max(0, Number(baseIndex)) : 0;
|
|
284
|
-
let accumulated = '';
|
|
285
|
-
let completedCount = 0;
|
|
286
|
-
let activeEmitted = '';
|
|
287
|
-
let stopped = false;
|
|
288
|
-
let emittedAny = false;
|
|
289
|
-
|
|
290
|
-
const push = (index, delta, done) => {
|
|
291
|
-
if (!emit || (typeof delta === 'string' && delta.length === 0 && !done)) return;
|
|
292
|
-
emittedAny = true;
|
|
293
|
-
emit(offset + index, delta, done);
|
|
294
|
-
};
|
|
295
|
-
|
|
296
|
-
const applyVisible = (visible) => {
|
|
297
|
-
const bubbles = splitContactBubbles(visible);
|
|
298
|
-
if (bubbles.length === 0) return;
|
|
299
|
-
while (completedCount < bubbles.length - 1) {
|
|
300
|
-
const bubble = bubbles[completedCount];
|
|
301
|
-
const rest = bubble.slice(activeEmitted.length);
|
|
302
|
-
push(completedCount, rest, true);
|
|
303
|
-
completedCount += 1;
|
|
304
|
-
activeEmitted = '';
|
|
305
|
-
}
|
|
306
|
-
const active = bubbles[bubbles.length - 1] || '';
|
|
307
|
-
if (active.length > activeEmitted.length) {
|
|
308
|
-
push(completedCount, active.slice(activeEmitted.length), false);
|
|
309
|
-
}
|
|
310
|
-
activeEmitted = active;
|
|
311
|
-
};
|
|
312
|
-
|
|
313
|
-
return {
|
|
314
|
-
get emittedAny() {
|
|
315
|
-
return emittedAny;
|
|
316
|
-
},
|
|
317
|
-
get stopped() {
|
|
318
|
-
return stopped;
|
|
319
|
-
},
|
|
320
|
-
get baseIndex() {
|
|
321
|
-
return offset;
|
|
322
|
-
},
|
|
323
|
-
pushDelta(delta) {
|
|
324
|
-
if (stopped || typeof delta !== 'string' || !delta) return;
|
|
325
|
-
const next = accumulated + delta;
|
|
326
|
-
const fenceAt = next.search(CONTACT_FENCE_START);
|
|
327
|
-
if (fenceAt >= 0) {
|
|
328
|
-
const visibleChunk = next.slice(accumulated.length, fenceAt);
|
|
329
|
-
accumulated = next.slice(0, fenceAt);
|
|
330
|
-
if (visibleChunk) applyVisible(accumulated);
|
|
331
|
-
stopped = true;
|
|
332
|
-
return;
|
|
333
|
-
}
|
|
334
|
-
accumulated = next;
|
|
335
|
-
applyVisible(accumulated);
|
|
336
|
-
},
|
|
337
|
-
/** Finalize after full stripped chat text is known. */
|
|
338
|
-
finish(finalBubbles) {
|
|
339
|
-
const bubbles = Array.isArray(finalBubbles)
|
|
340
|
-
? finalBubbles.filter((item) => typeof item === 'string' && item.trim())
|
|
341
|
-
: [];
|
|
342
|
-
if (!emittedAny) {
|
|
343
|
-
bubbles.forEach((bubble, index) => push(index, bubble, true));
|
|
344
|
-
return;
|
|
345
|
-
}
|
|
346
|
-
// Complete the active partial bubble, then any trailing bubbles not yet opened.
|
|
347
|
-
if (completedCount < bubbles.length) {
|
|
348
|
-
const current = bubbles[completedCount] || '';
|
|
349
|
-
const rest = current.slice(activeEmitted.length);
|
|
350
|
-
if (rest || activeEmitted || current) push(completedCount, rest, true);
|
|
351
|
-
completedCount += 1;
|
|
352
|
-
activeEmitted = '';
|
|
353
|
-
}
|
|
354
|
-
while (completedCount < bubbles.length) {
|
|
355
|
-
push(completedCount, bubbles[completedCount], true);
|
|
356
|
-
completedCount += 1;
|
|
357
|
-
}
|
|
358
|
-
},
|
|
359
|
-
};
|
|
360
|
-
}
|
|
361
|
-
|
|
362
213
|
export function createContactStreamFn(createChatCompletion, {
|
|
363
214
|
pendingFileParts = [],
|
|
364
215
|
onTextDelta = null,
|
|
@@ -407,7 +258,17 @@ export function createContactStreamFn(createChatCompletion, {
|
|
|
407
258
|
if (message.role === 'assistant') {
|
|
408
259
|
const content = (message.content || []).filter(part => part?.type === 'text').map(part => part.text).join('\n\n');
|
|
409
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) } }));
|
|
410
|
-
|
|
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 }] : [];
|
|
411
272
|
}
|
|
412
273
|
if (message.role === 'toolResult') {
|
|
413
274
|
const content = (message.content || [])
|
|
@@ -433,18 +294,13 @@ export function createContactStreamFn(createChatCompletion, {
|
|
|
433
294
|
lastUser.parts = fallbackFiles;
|
|
434
295
|
}
|
|
435
296
|
const allowedNames = (context.tools || []).map((tool) => tool?.name).filter(Boolean);
|
|
436
|
-
const requiresFinal = allowedNames.some(isPiCodingToolName);
|
|
437
297
|
let text;
|
|
438
298
|
let parsed;
|
|
439
|
-
let finalText;
|
|
440
|
-
let silent = false;
|
|
441
299
|
let rejectedCodingCalls = [];
|
|
442
300
|
// Repair only the rejected response: no tools have executed from it.
|
|
443
301
|
// Real results stay in messages, so already completed work is not replayed.
|
|
444
302
|
for (let attempt = 0; ; attempt += 1) {
|
|
445
303
|
signal?.throwIfAborted();
|
|
446
|
-
const publicStart = publicBubbles.length;
|
|
447
|
-
const publicReader = createPublicMessageReader(publishPublicMessage);
|
|
448
304
|
const result = await createChatCompletion({
|
|
449
305
|
signal,
|
|
450
306
|
timeoutMs: 0,
|
|
@@ -462,77 +318,62 @@ export function createContactStreamFn(createChatCompletion, {
|
|
|
462
318
|
},
|
|
463
319
|
onTextDelta: (delta) => {
|
|
464
320
|
if (signal?.aborted) return;
|
|
465
|
-
if (typeof delta === 'string') {
|
|
466
|
-
publicReader.push(delta);
|
|
467
|
-
}
|
|
468
321
|
if (typeof delta === 'string' && delta && typeof onTextDelta === 'function') onTextDelta(delta);
|
|
469
322
|
},
|
|
470
323
|
globalEventHub,
|
|
324
|
+
validateToolCalls: false,
|
|
471
325
|
});
|
|
472
326
|
signal?.throwIfAborted();
|
|
473
|
-
|
|
474
|
-
const
|
|
475
|
-
|
|
476
|
-
const
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
const
|
|
483
|
-
silent = finalResponse?.status === 'silent';
|
|
484
|
-
finalText = finalResponse?.text ?? null;
|
|
485
|
-
// A final answer is opaque text; quoted tool examples in it cannot run.
|
|
486
|
-
const nativeCalls = result?.completion?.choices?.[0]?.message?.tool_calls ?? [];
|
|
487
|
-
parsed = nativeCalls.length ? {
|
|
488
|
-
toolCalls: nativeCalls.map(call => ({ id: call.id, name: call.function.name, arguments: JSON.parse(call.function.arguments) })),
|
|
489
|
-
chatText: text,
|
|
490
|
-
protocolError: finalText !== null ? 'Do not mix native tool calls with a final declaration.' : nativeCalls.some(call => !allowedNames.includes(call.function.name)) ? 'The requested tool is unavailable.' : '',
|
|
491
|
-
} : finalText === null ? parseContactToolCalls(text, allowedNames) : { toolCalls: [], chatText: finalText };
|
|
492
|
-
const mixedBatch = parsed.toolCalls.length > 1 && parsed.toolCalls.some((call) => !isPiCodingToolName(call.name));
|
|
493
|
-
const malformedFinal = finalText === null && /```yuri-final/u.test(parsed.chatText);
|
|
494
|
-
const skippedRejectedWork = rejectedCodingCalls.length > 0 && finalResponse?.status === 'complete';
|
|
495
|
-
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);
|
|
496
337
|
const protocolError = parsed.protocolError
|
|
497
|
-
|| (forgedTranscript ? 'Do not simulate user messages, assistant turns, or tool results.
|
|
498
|
-
|| (
|
|
499
|
-
|| (mixedBatch ? 'Send Yuri operation tools one at a time, without other calls in the same response.' : '')
|
|
500
|
-
|| (malformedFinal ? 'The final declaration must be a single valid yuri-final JSON fence with status and text, without other content.' : '')
|
|
501
|
-
|| (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.' : '');
|
|
502
340
|
if (!protocolError) break;
|
|
503
341
|
if (attempt >= 2) throw new Error(`Assistant response protocol failed after two corrections; the task was not confirmed complete. Reason: ${protocolError}`);
|
|
504
|
-
const rejected =
|
|
342
|
+
const rejected = operations.filter((call) => isPiCodingToolName(call.name));
|
|
505
343
|
if (rejected.length > 0) rejectedCodingCalls = rejected.map(({ name, arguments: args }) => ({ name, arguments: args }));
|
|
506
|
-
if (publicBubbles.length > publicStart) {
|
|
507
|
-
messages.push({ role: 'assistant', content: publicBubbles.slice(publicStart).join('\n\n') });
|
|
508
|
-
}
|
|
509
344
|
// Never replay rejected prose: it may contain fabricated user/tool results.
|
|
510
345
|
messages.push(
|
|
511
|
-
{ 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
|
|
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.` },
|
|
512
347
|
);
|
|
513
348
|
}
|
|
514
|
-
// Continue turn-global bubble indices from already-streamed turn messages.
|
|
515
|
-
const nextIndex = baseIndex + publicBubbles.length;
|
|
516
|
-
const bubbleTracker = createContactBubbleDeltaTracker(onBubbleDelta, { baseIndex: nextIndex });
|
|
517
349
|
if (parsed.toolCalls.length > 0) {
|
|
518
|
-
|
|
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) => ({
|
|
519
363
|
type: 'toolCall',
|
|
520
364
|
id: call.id || `call_${Date.now().toString(36)}_${++callSequence}`,
|
|
521
365
|
name: call.name,
|
|
522
366
|
arguments: call.arguments,
|
|
523
367
|
}));
|
|
524
|
-
const
|
|
525
|
-
const spokenBubbles = spoken ? splitContactBubbles(spoken) : [];
|
|
526
|
-
const publicText = [...publicBubbles, ...spokenBubbles].join('\n\n');
|
|
368
|
+
const publicText = publicBubbles.join('\n\n');
|
|
527
369
|
const content = publicText
|
|
528
370
|
? [{ type: 'text', text: publicText }, ...toolCalls]
|
|
529
371
|
: toolCalls;
|
|
530
372
|
const partial = {
|
|
531
|
-
...assistantMessage(model,
|
|
373
|
+
...assistantMessage(model, '', 'toolUse'),
|
|
532
374
|
content,
|
|
533
375
|
contactPublicText: true,
|
|
534
376
|
};
|
|
535
|
-
if (spokenBubbles.length > 0) bubbleTracker.finish(spokenBubbles);
|
|
536
377
|
stream.push({ type: 'start', partial });
|
|
537
378
|
if (publicText) {
|
|
538
379
|
stream.push({ type: 'text_start', contentIndex: 0, partial });
|
|
@@ -549,20 +390,16 @@ export function createContactStreamFn(createChatCompletion, {
|
|
|
549
390
|
stream.end(partial);
|
|
550
391
|
return;
|
|
551
392
|
}
|
|
552
|
-
|
|
393
|
+
// A response without tool calls is the final reply.
|
|
394
|
+
const chatText = text.trim();
|
|
553
395
|
const replyBubbles = splitContactBubbles(chatText);
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
await new Promise((resolve) => setTimeout(resolve, bubbleGapMs));
|
|
559
|
-
}
|
|
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));
|
|
560
400
|
}
|
|
561
|
-
} else {
|
|
562
|
-
bubbleTracker.finish(replyBubbles);
|
|
563
401
|
}
|
|
564
|
-
const partial = assistantMessage(model,
|
|
565
|
-
if (silent) partial.contactSilent = true;
|
|
402
|
+
const partial = assistantMessage(model, replyBubbles.join('\n\n'), 'stop');
|
|
566
403
|
stream.push({ type: 'start', partial });
|
|
567
404
|
stream.push({ type: 'text_start', contentIndex: 0, partial });
|
|
568
405
|
stream.push({ type: 'text_delta', contentIndex: 0, delta: chatText, partial });
|
|
@@ -659,8 +496,10 @@ export async function runContactTurn({
|
|
|
659
496
|
const modelID = assistant.modelID;
|
|
660
497
|
const cwd = resolveAssistantCwd(assistant);
|
|
661
498
|
const contactTools = Array.isArray(tools)
|
|
662
|
-
? tools.filter((tool) => tool && typeof tool.name === 'string' && !isPiCodingToolName(tool.name) && (!readOnly || ['list_projects', 'list_sessions', 'read_session', 'get_assistant_settings', 'search_memory', 'read_memory'].includes(tool.name)))
|
|
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)))
|
|
663
500
|
: [];
|
|
501
|
+
// Background reviews only reply or stay silent; interactive turns may notify mid-turn.
|
|
502
|
+
const conversationTools = allowSilent ? [createStaySilentTool()] : readOnly ? [] : [createNotifyUserTool()];
|
|
664
503
|
let runtime = null;
|
|
665
504
|
let removeAbortListener = null;
|
|
666
505
|
try {
|
|
@@ -671,18 +510,17 @@ export async function runContactTurn({
|
|
|
671
510
|
CONTACT_SYSTEM_PROMPT,
|
|
672
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.',
|
|
673
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.' : '',
|
|
674
|
-
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,
|
|
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.' : '',
|
|
675
514
|
formatPiCodingPrompt({
|
|
676
515
|
cwd: runtime?.cwd,
|
|
677
516
|
skillsPrompt: runtime?.skillsPrompt,
|
|
678
|
-
tools: codingTools,
|
|
679
517
|
}),
|
|
680
518
|
formatRegisteredProjectsPrompt(projects),
|
|
681
519
|
formatConnectedModelsPrompt(connectedModels, { preferences: modelPreferences, catalogAvailable: modelCatalogAvailable }),
|
|
682
520
|
formatContactToolsPrompt(contactTools),
|
|
683
521
|
assistant.defaultPrompt,
|
|
684
522
|
codingTools.length > 0 ? WORKSPACE_RESPONSE_PROTOCOL : '',
|
|
685
|
-
'
|
|
523
|
+
'Actual tool results arrive in tool-role messages; never manufacture them.',
|
|
686
524
|
].filter((value) => typeof value === 'string' && value.trim()).join('\n\n')
|
|
687
525
|
.replaceAll('{{LANGUAGE}}', resolveContactLanguage(language));
|
|
688
526
|
const model = createContactModel(providerID, modelID);
|
|
@@ -715,7 +553,7 @@ export async function runContactTurn({
|
|
|
715
553
|
systemPrompt,
|
|
716
554
|
model,
|
|
717
555
|
thinkingLevel: 'off',
|
|
718
|
-
tools: [...codingTools, ...contactTools],
|
|
556
|
+
tools: [...codingTools, ...contactTools, ...conversationTools],
|
|
719
557
|
messages: prior,
|
|
720
558
|
},
|
|
721
559
|
streamFn: createContactStreamFn(createChatCompletion, {
|
|
@@ -762,7 +600,7 @@ export async function runContactTurn({
|
|
|
762
600
|
// a turn error; the harness never manufactures an assistant reply.
|
|
763
601
|
const missed = extractContactTurnOutcome(agent.state.messages.slice(turnMessageStart));
|
|
764
602
|
const missedBubbles = (Array.isArray(missed.bubbles) ? missed.bubbles : [])
|
|
765
|
-
.map((item) => (typeof item === 'string' ?
|
|
603
|
+
.map((item) => (typeof item === 'string' ? item.trim() : ''))
|
|
766
604
|
.filter(Boolean);
|
|
767
605
|
if (missedBubbles.length > 0) {
|
|
768
606
|
return {
|
|
@@ -778,7 +616,7 @@ export async function runContactTurn({
|
|
|
778
616
|
const turnMessages = agent.state.messages.slice(turnMessageStart);
|
|
779
617
|
const reset = contactTurnHasSuccessfulReset(turnMessages);
|
|
780
618
|
const lastMessage = turnMessages.at(-1);
|
|
781
|
-
if (allowSilent && lastMessage?.role === '
|
|
619
|
+
if (allowSilent && lastMessage?.role === 'toolResult' && lastMessage.toolName === STAY_SILENT_TOOL_NAME && !lastMessage.isError) {
|
|
782
620
|
return { silent: true, text: '', bubbles: [], cards: [], thinkingLevel: agent.state.thinkingLevel, tools: [...agent.state.tools] };
|
|
783
621
|
}
|
|
784
622
|
// Terminal tools stop further mutations. A tools-disabled model pass owns
|