@zhin.js/adapter-sandbox 1.1.17 → 1.1.19

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.
@@ -1,4 +1,5 @@
1
1
  // Generated by build-plugin-runtime-entries.mjs. Do not edit.
2
+ import { sandboxText } from './messages.js';
2
3
  import { getSandboxApiBase, getSandboxAuthHeaders } from './sandboxTransport.js';
3
4
  const problemTypes = new Set(['tool_denied', 'tool_failed', 'tool_cancelled', 'turn_cancelled', 'budget_exceeded', 'error']);
4
5
  const toolTypes = new Set(['tool_call', 'mcp_tool_call']);
@@ -123,7 +124,7 @@ export function deriveTaskRuns(snapshot) {
123
124
  };
124
125
  }).sort((left, right) => right.startedAt - left.startedAt);
125
126
  }
126
- export function deriveWorkbenchArtifacts(snapshot) {
127
+ export function deriveWorkbenchArtifacts(snapshot, locale = 'zh-CN') {
127
128
  if (!snapshot)
128
129
  return [];
129
130
  const outcomes = new Map();
@@ -157,7 +158,7 @@ export function deriveWorkbenchArtifacts(snapshot) {
157
158
  return [{
158
159
  ...common,
159
160
  kind: 'file-change',
160
- title: toolName === 'write_file' ? '写入文件' : '编辑文件',
161
+ title: toolName === 'write_file' ? sandboxText(locale, "写入文件") : sandboxText(locale, "编辑文件"),
161
162
  path: filePath,
162
163
  detail: artifactOutputDetail(outcome),
163
164
  diff: fileDiff(toolName, args, filePath),
@@ -177,7 +178,7 @@ export function deriveWorkbenchArtifacts(snapshot) {
177
178
  return [];
178
179
  }).sort((left, right) => right.recordedAt - left.recordedAt);
179
180
  }
180
- export function deriveAgentRunSteps(snapshot, run) {
181
+ export function deriveAgentRunSteps(snapshot, run, locale = 'zh-CN') {
181
182
  if (!snapshot || !run)
182
183
  return [];
183
184
  const { turnId } = run;
@@ -193,12 +194,12 @@ export function deriveAgentRunSteps(snapshot, run) {
193
194
  const steps = events.flatMap((event) => {
194
195
  const common = { id: `${event.runtimeId ?? 'legacy'}:${turnId}:${event.sequence}`, recordedAt: event.recordedAt };
195
196
  if (event.type === 'turn_start') {
196
- return [{ ...common, title: '接收任务', detail: shortTurn(turnId), status: 'completed' }];
197
+ return [{ ...common, title: sandboxText(locale, "接收任务"), detail: shortTurn(turnId), status: 'completed' }];
197
198
  }
198
199
  if (event.type === 'capability_resolution') {
199
200
  return [{
200
201
  ...common,
201
- title: '准备运行能力',
202
+ title: sandboxText(locale, "准备运行能力"),
202
203
  detail: `${arrayLength(event.data.tools)} tools · ${arrayLength(event.data.skills)} skills`,
203
204
  status: 'completed',
204
205
  }];
@@ -206,8 +207,8 @@ export function deriveAgentRunSteps(snapshot, run) {
206
207
  if (event.type === 'iteration_start') {
207
208
  return [{
208
209
  ...common,
209
- title: `推理迭代 ${String(event.data.iteration ?? '')}`.trim(),
210
- detail: event.data.maxIterations == null ? undefined : `上限 ${String(event.data.maxIterations)}`,
210
+ title: sandboxText(locale, "推理迭代 {0}", [String(event.data.iteration ?? '')]).trim(),
211
+ detail: event.data.maxIterations == null ? undefined : sandboxText(locale, "上限 {0}", [String(event.data.maxIterations)]),
211
212
  status: 'completed',
212
213
  }];
213
214
  }
@@ -221,7 +222,7 @@ export function deriveAgentRunSteps(snapshot, run) {
221
222
  return [{
222
223
  ...common,
223
224
  id: toolCorrelationKey(event, toolUseId),
224
- title: `运行 ${toolName}`,
225
+ title: sandboxText(locale, "运行 {0}", [toolName]),
225
226
  ...(detail ? { detail } : {}),
226
227
  status: artifactStatus(outcome),
227
228
  ...(durationMs !== undefined ? { durationMs } : {}),
@@ -230,7 +231,7 @@ export function deriveAgentRunSteps(snapshot, run) {
230
231
  if (event.type === 'subagent_start') {
231
232
  return [{
232
233
  ...common,
233
- title: `委派 ${stringValue(event.data.agentName) || '子 Agent'}`,
234
+ title: sandboxText(locale, "委派 {0}", [stringValue(event.data.agentName) || sandboxText(locale, "子 Agent")]),
234
235
  detail: preview(event.data.description) || undefined,
235
236
  status: 'running',
236
237
  }];
@@ -239,19 +240,19 @@ export function deriveAgentRunSteps(snapshot, run) {
239
240
  const failed = event.data.status === 'error';
240
241
  return [{
241
242
  ...common,
242
- title: failed ? '子 Agent 失败' : '子 Agent 返回',
243
+ title: failed ? sandboxText(locale, "子 Agent 失败") : sandboxText(locale, "子 Agent 返回"),
243
244
  detail: preview(event.data.summary ?? event.data.error) || undefined,
244
245
  status: failed ? 'failed' : 'completed',
245
246
  }];
246
247
  }
247
248
  if (event.type === 'turn_end')
248
- return [{ ...common, title: '任务完成', detail: 'Agent 已返回结果', status: 'completed' }];
249
+ return [{ ...common, title: sandboxText(locale, "任务完成"), detail: sandboxText(locale, "Agent 已返回结果"), status: 'completed' }];
249
250
  if (event.type === 'turn_cancelled')
250
- return [{ ...common, title: '任务已停止', detail: preview(event.data.reason) || undefined, status: 'cancelled' }];
251
+ return [{ ...common, title: sandboxText(locale, "任务已停止"), detail: preview(event.data.reason) || undefined, status: 'cancelled' }];
251
252
  if (event.type === 'budget_exceeded')
252
- return [{ ...common, title: '达到预算上限', detail: preview(event.data.budget) || undefined, status: 'failed' }];
253
+ return [{ ...common, title: sandboxText(locale, "达到预算上限"), detail: preview(event.data.budget) || undefined, status: 'failed' }];
253
254
  if (event.type === 'error')
254
- return [{ ...common, title: '任务失败', detail: preview(event.data.error) || undefined, status: 'failed' }];
255
+ return [{ ...common, title: sandboxText(locale, "任务失败"), detail: preview(event.data.error) || undefined, status: 'failed' }];
255
256
  return [];
256
257
  });
257
258
  const task = deriveTaskRuns(snapshot).find((candidate) => candidate.id === runIdentityKey(run));
@@ -269,90 +270,90 @@ export function deriveAgentRunSteps(snapshot, run) {
269
270
  if (task?.status === 'running' && steps.length > 0 && steps.at(-1)?.status !== 'running') {
270
271
  steps.push({
271
272
  id: `${task.id}:waiting`,
272
- title: '等待 Agent 返回',
273
- detail: '任务仍在运行',
273
+ title: sandboxText(locale, "等待 Agent 返回"),
274
+ detail: sandboxText(locale, "任务仍在运行"),
274
275
  status: 'running',
275
276
  recordedAt: events.at(-1)?.recordedAt ?? task.startedAt,
276
277
  });
277
278
  }
278
279
  return steps;
279
280
  }
280
- export function buildAgentRunReport(snapshot, context = {}) {
281
+ export function buildAgentRunReport(snapshot, context = {}, locale = 'zh-CN') {
281
282
  const runs = deriveTaskRuns(snapshot);
282
283
  const run = context.run ? runs.find((candidate) => candidate.id === runIdentityKey(context.run)) : runs[0];
283
284
  const identity = run ?? context.run;
284
285
  const turnId = identity?.turnId;
285
- const steps = deriveAgentRunSteps(snapshot, identity);
286
- const artifacts = deriveWorkbenchArtifacts(snapshot).filter((artifact) => identity && matchesRun(artifact, identity));
287
- const status = run ? taskStatusText(run.status) : '无运行记录';
286
+ const steps = deriveAgentRunSteps(snapshot, identity, locale);
287
+ const artifacts = deriveWorkbenchArtifacts(snapshot, locale).filter((artifact) => identity && matchesRun(artifact, identity));
288
+ const status = run ? taskStatusText(run.status, locale) : sandboxText(locale, "无运行记录");
288
289
  const lines = [
289
- '# Agent 运行报告',
290
+ sandboxText(locale, "# Agent 运行报告"),
290
291
  '',
291
- `- **会话:** ${markdownInline(context.sessionName || snapshot?.sessionKey || '未命名会话')}`,
292
- `- **任务 ID:** ${markdownInline(turnId || '—')}`,
293
- `- **状态:** ${status}`,
294
- `- **开始时间:** ${run ? new Date(run.startedAt).toISOString() : '—'}`,
295
- `- **耗时:** ${run?.durationMs === undefined ? (run?.status === 'running' ? '进行中' : '—') : `${run.durationMs.toLocaleString()} ms`}`,
296
- `- **工作目录:** ${markdownInline(context.workingDirectory || 'Host project root')}`,
297
- `- **安全策略:** ${markdownInline(context.safetyMode || '—')} / ${markdownInline(context.approvalMode || '—')} / network ${context.networkAccess ? 'enabled' : 'disabled'}`,
298
- `- **用量:** ${run?.toolCount ?? 0} tools / ${(run?.tokenCount ?? 0).toLocaleString()} tokens / ${run?.problemCount ?? 0} problems`,
292
+ sandboxText(locale, "- **会话:** {0}", [markdownInline(context.sessionName || snapshot?.sessionKey || sandboxText(locale, "未命名会话"))]),
293
+ sandboxText(locale, "- **任务 ID:** {0}", [markdownInline(turnId || '—')]),
294
+ sandboxText(locale, "- **状态:** {0}", [status]),
295
+ sandboxText(locale, "- **开始时间:** {0}", [run ? new Date(run.startedAt).toISOString() : '—']),
296
+ sandboxText(locale, "- **耗时:** {0}", [run?.durationMs === undefined ? (run?.status === 'running' ? sandboxText(locale, "进行中") : '—') : `${run.durationMs.toLocaleString(locale)} ms`]),
297
+ sandboxText(locale, "- **工作目录:** {0}", [markdownInline(context.workingDirectory || 'Host project root')]),
298
+ sandboxText(locale, "- **安全策略:** {0} / {1} / network {2}", [markdownInline(context.safetyMode || '—'), markdownInline(context.approvalMode || '—'), context.networkAccess ? 'enabled' : 'disabled']),
299
+ sandboxText(locale, "- **用量:** {0} tools / {1} tokens / {2} problems", [run?.toolCount ?? 0, (run?.tokenCount ?? 0).toLocaleString(locale), run?.problemCount ?? 0]),
299
300
  ];
300
301
  if (context.taskPrompt?.trim()) {
301
- lines.push('', '## 任务', '', ...markdownBlock('text', context.taskPrompt.trim()));
302
+ lines.push('', sandboxText(locale, "## 任务"), '', ...markdownBlock('text', context.taskPrompt.trim()));
302
303
  }
303
- lines.push('', '## 执行轨迹', '');
304
+ lines.push('', sandboxText(locale, "## 执行轨迹"), '');
304
305
  if (steps.length === 0)
305
- lines.push('- 暂无可用轨迹');
306
+ lines.push(sandboxText(locale, "- 暂无可用轨迹"));
306
307
  else
307
308
  for (const step of steps) {
308
- lines.push(`- ${stepStatusMark(step.status)} **${reportStepTitle(step.title)}**${step.detail ? ` — ${markdownInline(step.detail)}` : ''}${step.durationMs === undefined ? '' : ` (${step.durationMs.toLocaleString()} ms)`}`);
309
+ lines.push(`- ${stepStatusMark(step.status)} **${reportStepTitle(step.title, locale)}**${step.detail ? ` — ${markdownInline(step.detail)}` : ''}${step.durationMs === undefined ? '' : ` (${step.durationMs.toLocaleString(locale)} ms)`}`);
309
310
  }
310
- lines.push('', '## 变更与产物', '');
311
+ lines.push('', sandboxText(locale, "## 变更与产物"), '');
311
312
  if (artifacts.length === 0)
312
- lines.push('- 本次运行没有文件、命令或测试产物。');
313
+ lines.push(sandboxText(locale, "- 本次运行没有文件、命令或测试产物。"));
313
314
  else
314
315
  artifacts.forEach((artifact, index) => {
315
316
  lines.push(`### ${index + 1}. ${markdownInline(artifact.title)}`, '');
316
- lines.push(`- 类型:${artifact.kind}`, `- 状态:${artifact.status}`);
317
+ lines.push(sandboxText(locale, "- 类型:{0}", [artifact.kind]), sandboxText(locale, "- 状态:{0}", [artifact.status]));
317
318
  if (artifact.path)
318
- lines.push(`- 路径:${markdownInlineCode(artifact.path)}`);
319
+ lines.push(sandboxText(locale, "- 路径:{0}", [markdownInlineCode(artifact.path)]));
319
320
  if (artifact.durationMs !== undefined)
320
- lines.push(`- 耗时:${artifact.durationMs.toLocaleString()} ms`);
321
+ lines.push(sandboxText(locale, "- 耗时:{0} ms", [artifact.durationMs.toLocaleString(locale)]));
321
322
  if (artifact.diff)
322
323
  lines.push('', ...markdownBlock('diff', artifact.diff));
323
324
  else if (artifact.detail)
324
325
  lines.push('', ...markdownBlock('text', artifact.detail));
325
326
  lines.push('');
326
327
  });
327
- lines.push('---', `由 Zhin Agent 试验台于 ${new Date().toISOString()} 导出。`);
328
+ lines.push('---', sandboxText(locale, "由 Zhin「试聊一下」于 {0} 导出。", [new Date().toISOString()]));
328
329
  return `${lines.join('\n').trim()}\n`;
329
330
  }
330
- export function presentTraceEvent(event) {
331
+ export function presentTraceEvent(event, locale = 'zh-CN') {
331
332
  const data = event.data;
332
333
  const tool = String(data.toolName ?? 'tool');
333
334
  switch (event.type) {
334
- case 'turn_start': return { title: '开始处理', detail: shortTurn(event.turnId), tone: 'running' };
335
- case 'capability_resolution': return { title: '能力已解析', detail: `${arrayLength(data.tools)} tools · ${arrayLength(data.skills)} skills`, tone: 'capability' };
336
- case 'iteration_start': return { title: `推理迭代 ${String(data.iteration ?? '')}`, detail: `上限 ${String(data.maxIterations ?? '—')}`, tone: 'thinking' };
337
- case 'thinking': return { title: '模型思考', detail: preview(data.text), tone: 'thinking' };
338
- case 'tool_call': return { title: `调用 ${tool}`, detail: preview(data.toolUseId), tone: 'tool' };
339
- case 'tool_result': return { title: `${tool} 完成`, detail: duration(data.durationMs), tone: 'success' };
340
- case 'tool_denied': return { title: `${tool} 被拒绝`, detail: preview(data.reason ?? data.policy), tone: 'problem' };
341
- case 'tool_failed': return { title: `${tool} 失败`, detail: preview(data.error), tone: 'problem' };
342
- case 'mcp_connect': return { title: `${String(data.serverName ?? 'MCP')} 连接`, detail: String(data.status ?? ''), tone: 'capability' };
335
+ case 'turn_start': return { title: sandboxText(locale, "开始处理"), detail: shortTurn(event.turnId), tone: 'running' };
336
+ case 'capability_resolution': return { title: sandboxText(locale, "能力已解析"), detail: `${arrayLength(data.tools)} tools · ${arrayLength(data.skills)} skills`, tone: 'capability' };
337
+ case 'iteration_start': return { title: sandboxText(locale, "推理迭代 {0}", [String(data.iteration ?? '')]), detail: sandboxText(locale, "上限 {0}", [String(data.maxIterations ?? '—')]), tone: 'thinking' };
338
+ case 'thinking': return { title: sandboxText(locale, "模型思考"), detail: preview(data.text), tone: 'thinking' };
339
+ case 'tool_call': return { title: sandboxText(locale, "调用 {0}", [tool]), detail: preview(data.toolUseId), tone: 'tool' };
340
+ case 'tool_result': return { title: sandboxText(locale, "{0} 完成", [tool]), detail: duration(data.durationMs, locale), tone: 'success' };
341
+ case 'tool_denied': return { title: sandboxText(locale, "{0} 被拒绝", [tool]), detail: preview(data.reason ?? data.policy), tone: 'problem' };
342
+ case 'tool_failed': return { title: sandboxText(locale, "{0} 失败", [tool]), detail: preview(data.error), tone: 'problem' };
343
+ case 'mcp_connect': return { title: sandboxText(locale, "{0} 连接", [String(data.serverName ?? 'MCP')]), detail: String(data.status ?? ''), tone: 'capability' };
343
344
  case 'mcp_tool_call': return { title: String(data.toolName ?? 'MCP tool'), detail: `via ${String(data.serverName ?? 'MCP')}`, tone: 'tool' };
344
- case 'subagent_start': return { title: `委派 ${String(data.agentName ?? 'subagent')}`, detail: preview(data.description), tone: 'capability' };
345
- case 'subagent_progress': return { title: '子 Agent 更新', detail: preview(data.summary), tone: 'running' };
346
- case 'subagent_end': return { title: '子 Agent 返回', detail: String(data.status ?? 'done'), tone: data.status === 'error' ? 'problem' : 'success' };
347
- case 'usage': return { title: `${usageTotal(data).toLocaleString()} tokens`, detail: usageDetail(data), tone: 'usage' };
348
- case 'turn_end': return { title: '本轮完成', detail: 'Agent 已返回结果', tone: 'success' };
349
- case 'turn_cancelled': return { title: '本轮取消', detail: preview(data.reason), tone: 'muted' };
350
- case 'budget_exceeded': return { title: '达到预算上限', detail: preview(data.budget), tone: 'problem' };
351
- case 'error': return { title: '执行失败', detail: preview(data.error), tone: 'problem' };
345
+ case 'subagent_start': return { title: sandboxText(locale, "委派 {0}", [String(data.agentName ?? 'subagent')]), detail: preview(data.description), tone: 'capability' };
346
+ case 'subagent_progress': return { title: sandboxText(locale, "子 Agent 更新"), detail: preview(data.summary), tone: 'running' };
347
+ case 'subagent_end': return { title: sandboxText(locale, "子 Agent 返回"), detail: String(data.status ?? 'done'), tone: data.status === 'error' ? 'problem' : 'success' };
348
+ case 'usage': return { title: `${usageTotal(data).toLocaleString(locale)} tokens`, detail: usageDetail(data, locale), tone: 'usage' };
349
+ case 'turn_end': return { title: sandboxText(locale, "本轮完成"), detail: sandboxText(locale, "Agent 已返回结果"), tone: 'success' };
350
+ case 'turn_cancelled': return { title: sandboxText(locale, "本轮取消"), detail: preview(data.reason), tone: 'muted' };
351
+ case 'budget_exceeded': return { title: sandboxText(locale, "达到预算上限"), detail: preview(data.budget), tone: 'problem' };
352
+ case 'error': return { title: sandboxText(locale, "执行失败"), detail: preview(data.error), tone: 'problem' };
352
353
  default: return { title: event.type.replaceAll('_', ' '), detail: '', tone: 'muted' };
353
354
  }
354
355
  }
355
- export async function fetchAgentTrace(sessionKey, afterSequence = 0) {
356
+ export async function fetchAgentTrace(sessionKey, afterSequence = 0, locale = 'zh-CN') {
356
357
  const base = getSandboxApiBase() || window.location.origin;
357
358
  const url = new URL('/api/agent/traces', `${base}/`);
358
359
  url.searchParams.set('sessionKey', sessionKey);
@@ -363,12 +364,12 @@ export async function fetchAgentTrace(sessionKey, afterSequence = 0) {
363
364
  const body = await response.json().catch(() => ({}));
364
365
  if (!response.ok || body.success === false || !body.data) {
365
366
  throw new Error(response.status === 503
366
- ? 'Agent Trace 尚未启用'
367
- : body.error || '无法读取 Agent Trace');
367
+ ? sandboxText(locale, "Agent Trace 尚未启用")
368
+ : body.error || sandboxText(locale, "无法读取 Agent Trace"));
368
369
  }
369
370
  return body.data;
370
371
  }
371
- export async function cancelAgentTask(sessionKey) {
372
+ export async function cancelAgentTask(sessionKey, locale = 'zh-CN') {
372
373
  const base = getSandboxApiBase() || window.location.origin;
373
374
  const response = await fetch(new URL('/api/agent/tasks/cancel', `${base}/`), {
374
375
  method: 'POST',
@@ -377,7 +378,7 @@ export async function cancelAgentTask(sessionKey) {
377
378
  });
378
379
  const body = await response.json().catch(() => ({}));
379
380
  if (!response.ok || body.success === false) {
380
- throw new Error(body.error || '无法停止 Agent 任务');
381
+ throw new Error(body.error || sandboxText(locale, "无法停止 Agent 任务"));
381
382
  }
382
383
  return body.data?.cancelled === true;
383
384
  }
@@ -387,9 +388,9 @@ function usageRecord(data) {
387
388
  function usageTotal(data) {
388
389
  return Number(usageRecord(data).totalTokens ?? 0);
389
390
  }
390
- function usageDetail(data) {
391
+ function usageDetail(data, locale = 'zh-CN') {
391
392
  const usage = usageRecord(data);
392
- return `输入 ${Number(usage.promptTokens ?? 0).toLocaleString()} · 输出 ${Number(usage.completionTokens ?? 0).toLocaleString()}`;
393
+ return sandboxText(locale, "输入 {0} · 输出 {1}", [Number(usage.promptTokens ?? 0).toLocaleString(locale), Number(usage.completionTokens ?? 0).toLocaleString(locale)]);
393
394
  }
394
395
  function arrayLength(value) {
395
396
  return Array.isArray(value) ? value.length : 0;
@@ -406,9 +407,9 @@ function preview(value) {
406
407
  return String(value).slice(0, 96);
407
408
  }
408
409
  }
409
- function duration(value) {
410
+ function duration(value, locale = 'zh-CN') {
410
411
  const ms = Number(value);
411
- return Number.isFinite(ms) ? `${ms.toLocaleString()} ms` : '执行完成';
412
+ return Number.isFinite(ms) ? `${ms.toLocaleString(locale)} ms` : sandboxText(locale, "执行完成");
412
413
  }
413
414
  function shortTurn(value) {
414
415
  return value.length > 12 ? value.slice(0, 10) : value;
@@ -447,14 +448,14 @@ function toolStepDetail(toolName, args, fallback) {
447
448
  }
448
449
  return fallback;
449
450
  }
450
- function taskStatusText(status) {
451
+ function taskStatusText(status, locale = 'zh-CN') {
451
452
  if (status === 'running')
452
- return '运行中';
453
+ return sandboxText(locale, "运行中");
453
454
  if (status === 'completed')
454
- return '已完成';
455
+ return sandboxText(locale, "已完成");
455
456
  if (status === 'cancelled')
456
- return '已取消';
457
- return '失败';
457
+ return sandboxText(locale, "已取消");
458
+ return sandboxText(locale, "失败");
458
459
  }
459
460
  function stepStatusMark(status) {
460
461
  if (status === 'completed')
@@ -468,9 +469,9 @@ function stepStatusMark(status) {
468
469
  function markdownInline(value) {
469
470
  return value.replace(/[\\`*_[\]<>]/gu, '\\$&').replace(/\r?\n/gu, ' ');
470
471
  }
471
- function reportStepTitle(value) {
472
+ function reportStepTitle(value, locale = 'zh-CN') {
472
473
  const tool = /^运行 (.+)$/u.exec(value)?.[1];
473
- return tool ? `运行 ${markdownInlineCode(tool)}` : markdownInline(value);
474
+ return tool ? sandboxText(locale, "运行 {0}", [markdownInlineCode(tool)]) : markdownInline(value);
474
475
  }
475
476
  function markdownInlineCode(value) {
476
477
  const normalized = value.replace(/\r?\n/gu, ' ');