@steerable/agent-shell 0.14.2 → 0.14.4

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
  export declare const ATTACHMENTS_DIR_NAME = "attachments";
2
+ export declare const VIEWED_IMAGES_SUBDIR = ".viewed";
2
3
  /** 单个附件上限(base64 解码前字节数);多文件总和还受 HTTP body 上限约束。 */
3
4
  export declare const ATTACHMENT_MAX_BYTES: number;
4
5
  export interface AttachmentInput {
@@ -45,3 +46,17 @@ export declare function uniqueFileName(dir: string, name: string): string;
45
46
  export declare function saveAttachmentFiles(chatId: string, files: AttachmentInput[]): Promise<{
46
47
  files: StoredAttachment[];
47
48
  }>;
49
+ /**
50
+ * Persist a normalized `view_image` / `_image` payload under
51
+ * `<userDataDir>/attachments/<chatId>/.viewed/` so chat thumbnails survive
52
+ * even if the agent deletes temporary preview files later in the turn.
53
+ */
54
+ export declare function saveViewedImageSnapshot(chatId: string, sourcePath: string, image: {
55
+ b64: string;
56
+ media_type: string;
57
+ }): Promise<string | null>;
58
+ /**
59
+ * Look up a previously snapshotted `view_image` payload for `sourcePath`
60
+ * when the original file on disk was cleaned up after inspection.
61
+ */
62
+ export declare function findViewedImageSnapshot(chatId: string, sourcePath: string): Promise<string | null>;
@@ -19,11 +19,13 @@
19
19
  * - `data`:浏览器(BS 模式)里 File 没有路径,renderer 读成 base64 传上
20
20
  * 来,服务端解码后落盘。
21
21
  */
22
- import { existsSync, mkdirSync } from 'node:fs';
23
- import { copyFile, stat, writeFile } from 'node:fs/promises';
22
+ import { createHash } from 'node:crypto';
23
+ import { existsSync, mkdirSync, realpathSync } from 'node:fs';
24
+ import { copyFile, mkdir, stat, writeFile } from 'node:fs/promises';
24
25
  import path from 'node:path';
25
26
  import { getUserDataDir } from './runtime.js';
26
27
  export const ATTACHMENTS_DIR_NAME = 'attachments';
28
+ export const VIEWED_IMAGES_SUBDIR = '.viewed';
27
29
  /** 单个附件上限(base64 解码前字节数);多文件总和还受 HTTP body 上限约束。 */
28
30
  export const ATTACHMENT_MAX_BYTES = 25 * 1024 * 1024;
29
31
  /** chatId 由 storage 用 randomUUID 生成;这里只做白名单防御。 */
@@ -153,3 +155,68 @@ export async function saveAttachmentFiles(chatId, files) {
153
155
  }
154
156
  return { files: out };
155
157
  }
158
+ function normalizeSnapshotSourceKey(rawPath) {
159
+ try {
160
+ return realpathSync(rawPath);
161
+ }
162
+ catch {
163
+ try {
164
+ const parent = realpathSync(path.dirname(rawPath));
165
+ return path.join(parent, path.basename(rawPath));
166
+ }
167
+ catch {
168
+ return path.resolve(rawPath);
169
+ }
170
+ }
171
+ }
172
+ function viewedSnapshotDigests(rawPath) {
173
+ const canonical = normalizeSnapshotSourceKey(rawPath);
174
+ const resolved = path.resolve(rawPath);
175
+ const keys = canonical === resolved ? [canonical] : [canonical, resolved];
176
+ return keys.map((key) => createHash('sha256').update(key).digest('hex').slice(0, 24));
177
+ }
178
+ /**
179
+ * Persist a normalized `view_image` / `_image` payload under
180
+ * `<userDataDir>/attachments/<chatId>/.viewed/` so chat thumbnails survive
181
+ * even if the agent deletes temporary preview files later in the turn.
182
+ */
183
+ export async function saveViewedImageSnapshot(chatId, sourcePath, image) {
184
+ if (!isValidChatAttachmentsKey(chatId))
185
+ return null;
186
+ const trimmedSource = sourcePath.trim();
187
+ const b64 = image.b64.trim();
188
+ if (!trimmedSource || !b64)
189
+ return null;
190
+ const bytes = Buffer.from(b64, 'base64');
191
+ if (bytes.length === 0 || bytes.length > ATTACHMENT_MAX_BYTES)
192
+ return null;
193
+ const ext = image.media_type === 'image/jpeg' ? '.jpg' : '.png';
194
+ const viewedDir = path.join(chatAttachmentsDirPath(chatId), VIEWED_IMAGES_SUBDIR);
195
+ await mkdir(viewedDir, { recursive: true });
196
+ const digest = viewedSnapshotDigests(trimmedSource)[0];
197
+ const destPath = path.join(viewedDir, `${digest}${ext}`);
198
+ await writeFile(destPath, bytes);
199
+ return destPath;
200
+ }
201
+ /**
202
+ * Look up a previously snapshotted `view_image` payload for `sourcePath`
203
+ * when the original file on disk was cleaned up after inspection.
204
+ */
205
+ export async function findViewedImageSnapshot(chatId, sourcePath) {
206
+ if (!isValidChatAttachmentsKey(chatId))
207
+ return null;
208
+ const trimmedSource = sourcePath.trim();
209
+ if (!trimmedSource)
210
+ return null;
211
+ const viewedDir = path.join(chatAttachmentsDirPath(chatId), VIEWED_IMAGES_SUBDIR);
212
+ if (!existsSync(viewedDir))
213
+ return null;
214
+ for (const digest of viewedSnapshotDigests(trimmedSource)) {
215
+ for (const ext of ['.png', '.jpg']) {
216
+ const candidate = path.join(viewedDir, `${digest}${ext}`);
217
+ if (existsSync(candidate))
218
+ return candidate;
219
+ }
220
+ }
221
+ return null;
222
+ }
@@ -9,7 +9,7 @@ import { isProductLlmLocked } from '../host-tools-runtime.js';
9
9
  import { ensureProjectHome } from '../project-home.js';
10
10
  import { getUserDataDir } from '../runtime.js';
11
11
  import { chatAttachmentsDirPath, isValidChatAttachmentsKey, saveAttachmentFiles, } from '../attachments.js';
12
- import { sanitizeCompatOverrides, sanitizeLlmProvider, sanitizePresetsChoice, sanitizeVendorId, } from '../storage/llm-settings.js';
12
+ import { DEFAULT_LLM_SETTINGS, sanitizeCompatOverrides, sanitizeLlmProvider, sanitizePresetsChoice, sanitizeVendorId, } from '../storage/llm-settings.js';
13
13
  const ATTACHMENT_FILE_BYTES = 8 * 1024 * 1024;
14
14
  const ATTACHMENT_TOTAL_BYTES = 32 * 1024 * 1024;
15
15
  function fail(status, detail) {
@@ -160,7 +160,7 @@ async function applyLlm(store, section) {
160
160
  const next = {
161
161
  provider: sanitizeLlmProvider(section.provider),
162
162
  vendorId: sanitizeVendorId(section.vendorId),
163
- model: section.model?.trim() || current?.model || 'deepseek-chat',
163
+ model: section.model?.trim() || current?.model || DEFAULT_LLM_SETTINGS.model,
164
164
  baseUrl: section.baseUrl,
165
165
  apiKey: section.apiKeyIncluded ? section.apiKey : current?.apiKey,
166
166
  temperature: section.temperature,
@@ -239,7 +239,6 @@ export declare class LocalBackendRouter {
239
239
  private detectDeferredExecution;
240
240
  private detectToolDenialInHistory;
241
241
  private buildModePreamble;
242
- private isLocalSystemInfoRequest;
243
242
  private buildRuntimeEnvironmentContext;
244
243
  private buildToolRealityCheck;
245
244
  /**
@@ -50,7 +50,7 @@ import { handlePortableRequest } from './portable-service.js';
50
50
  import { getProductConfig, isPortableProduct, productConfigDirectConnection, } from '../product-config.js';
51
51
  import { dropCurrentUserMessage } from './history-helper.js';
52
52
  import { parseImageAttachments, processImageAttachments } from '../image-attachment.js';
53
- import { chatAttachmentsDirPath, isValidChatAttachmentsKey } from '../attachments.js';
53
+ import { chatAttachmentsDirPath, findViewedImageSnapshot, isValidChatAttachmentsKey, } from '../attachments.js';
54
54
  import { canonicalFencePath, canonicalPathInside } from '../fence-path.js';
55
55
  import { listProjectRuleFiles, loadProjectRuleFiles } from '../project-rules.js';
56
56
  import { allocateProjectHome, chatWorkspacePath, ensureChatWorkspace, ensureProjectHome, ensureWritableRoots, expandUserPath, } from '../project-home.js';
@@ -131,6 +131,75 @@ function turnFilePathsFromMetadata(raw) {
131
131
  }
132
132
  return paths;
133
133
  }
134
+ const IMAGE_OR_ARTIFACT_ACTION_TOOLS = new Set([
135
+ 'view_image',
136
+ 'capture_display',
137
+ 'present_files',
138
+ 'local_write_file',
139
+ 'write_file',
140
+ 'local_edit_file',
141
+ 'edit_file',
142
+ ]);
143
+ function extractActionReferencedPaths(actions) {
144
+ if (!Array.isArray(actions))
145
+ return [];
146
+ const paths = [];
147
+ for (const raw of actions) {
148
+ if (!raw || typeof raw !== 'object')
149
+ continue;
150
+ const row = raw;
151
+ if (typeof row.tool !== 'string' || !IMAGE_OR_ARTIFACT_ACTION_TOOLS.has(row.tool))
152
+ continue;
153
+ if (row.success === false)
154
+ continue;
155
+ if (row.arguments && typeof row.arguments === 'object') {
156
+ const args = row.arguments;
157
+ if (typeof args.path === 'string' && args.path.trim())
158
+ paths.push(args.path.trim());
159
+ if (typeof args.file === 'string' && args.file.trim())
160
+ paths.push(args.file.trim());
161
+ }
162
+ let resultObj = null;
163
+ if (typeof row.result === 'string' && row.result.trimStart().startsWith('{')) {
164
+ try {
165
+ const parsed = JSON.parse(row.result);
166
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
167
+ resultObj = parsed;
168
+ }
169
+ }
170
+ catch {
171
+ // Ignore truncated JSON envelopes.
172
+ }
173
+ }
174
+ else if (row.result && typeof row.result === 'object' && !Array.isArray(row.result)) {
175
+ resultObj = row.result;
176
+ }
177
+ if (resultObj?.success === false)
178
+ continue;
179
+ const dataObj = resultObj?.data && typeof resultObj.data === 'object' && !Array.isArray(resultObj.data)
180
+ ? resultObj.data
181
+ : resultObj;
182
+ if (dataObj) {
183
+ for (const key of ['sourcePath', 'path', 'filePath']) {
184
+ const candidate = dataObj[key];
185
+ if (typeof candidate === 'string' && candidate.trim())
186
+ paths.push(candidate.trim());
187
+ }
188
+ }
189
+ }
190
+ return paths;
191
+ }
192
+ function actionPathsFromMetadata(raw) {
193
+ if (typeof raw !== 'string' || !raw)
194
+ return [];
195
+ try {
196
+ const parsed = JSON.parse(raw);
197
+ return extractActionReferencedPaths(parsed?.executedActions);
198
+ }
199
+ catch {
200
+ return [];
201
+ }
202
+ }
134
203
  const DOWNLOAD_MIME_BY_EXT = {
135
204
  '.doc': 'application/msword',
136
205
  '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
@@ -1659,10 +1728,11 @@ export class LocalBackendRouter {
1659
1728
  continue;
1660
1729
  try {
1661
1730
  const meta = JSON.parse(msg.messageMetadata);
1662
- if (meta?.turnUsage) {
1663
- lastPromptTokens = Number(meta.turnUsage.promptTokens ?? 0);
1664
- lastCachedTokens = Number(meta.turnUsage.cachedPromptTokens ?? 0);
1665
- lastCacheCreationTokens = Number(meta.turnUsage.cacheCreationTokens ?? 0);
1731
+ const persistedUsage = meta?.usage ?? meta?.turnUsage;
1732
+ if (persistedUsage) {
1733
+ lastPromptTokens = Number(persistedUsage.promptTokens ?? 0);
1734
+ lastCachedTokens = Number(persistedUsage.cachedPromptTokens ?? 0);
1735
+ lastCacheCreationTokens = Number(persistedUsage.cacheCreationTokens ?? 0);
1666
1736
  break;
1667
1737
  }
1668
1738
  }
@@ -1680,9 +1750,11 @@ export class LocalBackendRouter {
1680
1750
  data: {
1681
1751
  chatId,
1682
1752
  recordId: activeRecordId,
1753
+ // `lastPromptTokens` is cumulative across all tool-loop rounds in a turn,
1754
+ // never the single-window transcript size; fall back to `fallbackTokens` only.
1683
1755
  estimatedTokens: rpcStatus?.recordExists
1684
1756
  ? rpcStatus.estimatedTokens
1685
- : Math.max(lastPromptTokens, fallbackTokens),
1757
+ : fallbackTokens,
1686
1758
  maxContextTokens: rpcStatus?.maxContextTokens ?? 131_072,
1687
1759
  estimatedBytes: rpcStatus?.recordExists ? rpcStatus.estimatedBytes : fallbackBytes,
1688
1760
  maxRequestBytes: rpcStatus?.maxRequestBytes ?? maxRequestBytes,
@@ -3425,7 +3497,7 @@ export class LocalBackendRouter {
3425
3497
  shouldGenerateTitle,
3426
3498
  firstUserMessageForTitle,
3427
3499
  resume: isResume,
3428
- subagent: mergeTurnSubagentParam(Object.fromEntries(mentionRoster.map((row) => [row.profileName, row.profile])), Object.fromEntries(ambientRoster.map((row) => [row.profileName, row.profile]))),
3500
+ subagent: mergeTurnSubagentParam(Object.fromEntries(mentionRoster.map((row) => [row.profileName, row.profile])), Object.fromEntries(ambientRoster.map((row) => [row.profileName, row.profile])), chatMode),
3429
3501
  parentAgentId: turnAgents.parent?.id ?? null,
3430
3502
  });
3431
3503
  });
@@ -3570,17 +3642,54 @@ export class LocalBackendRouter {
3570
3642
  if (!target || target.includes('\0') || !path.isAbsolute(target)) {
3571
3643
  return { status: 400, data: { detail: '需要文件的绝对路径' } };
3572
3644
  }
3573
- let realPath;
3574
- let fileStat;
3645
+ let realPath = null;
3646
+ let fileStat = null;
3575
3647
  try {
3576
- realPath = await realpath(target);
3577
- fileStat = await stat(realPath);
3648
+ const resolvedReal = await realpath(target);
3649
+ const st = await stat(resolvedReal);
3650
+ if (st.isFile()) {
3651
+ realPath = resolvedReal;
3652
+ fileStat = st;
3653
+ }
3578
3654
  }
3579
3655
  catch {
3580
- return { status: 404, data: { detail: '找不到这个文件' } };
3656
+ realPath = null;
3657
+ fileStat = null;
3581
3658
  }
3582
- if (!fileStat.isFile()) {
3583
- return { status: 404, data: { detail: '找不到这个文件' } };
3659
+ if (!realPath || !fileStat) {
3660
+ const snapshot = await findViewedImageSnapshot(chatId, target);
3661
+ if (!snapshot) {
3662
+ return { status: 404, data: { detail: '找不到这个文件' } };
3663
+ }
3664
+ try {
3665
+ const snapshotReal = await realpath(snapshot);
3666
+ const snapshotStat = await stat(snapshotReal);
3667
+ if (!snapshotStat.isFile() ||
3668
+ !isPathInsideRoot(chatAttachmentsDirPath(chatId), snapshotReal)) {
3669
+ return { status: 404, data: { detail: '找不到这个文件' } };
3670
+ }
3671
+ if (snapshotStat.size > MAX_LOCAL_DOWNLOAD_BYTES) {
3672
+ return {
3673
+ status: 413,
3674
+ data: {
3675
+ detail: `文件太大,无法直接下载(上限 ${Math.round(MAX_LOCAL_DOWNLOAD_BYTES / 1024 / 1024)}MB)`,
3676
+ },
3677
+ };
3678
+ }
3679
+ const buffer = await readFile(snapshotReal);
3680
+ return {
3681
+ status: 200,
3682
+ data: {
3683
+ fileName: path.basename(target),
3684
+ mime: downloadMimeForPath(snapshotReal),
3685
+ size: buffer.length,
3686
+ base64: buffer.toString('base64'),
3687
+ },
3688
+ };
3689
+ }
3690
+ catch {
3691
+ return { status: 404, data: { detail: '找不到这个文件' } };
3692
+ }
3584
3693
  }
3585
3694
  if (fileStat.size > MAX_LOCAL_DOWNLOAD_BYTES) {
3586
3695
  return {
@@ -3612,24 +3721,48 @@ export class LocalBackendRouter {
3612
3721
  allowed = roots.some((root) => isPathInsideRoot(root, realPath));
3613
3722
  }
3614
3723
  else {
3615
- const messages = await this.store.listMessages(chatId, 1000);
3616
- for (const message of messages) {
3617
- for (const listed of turnFilePathsFromMetadata(message.messageMetadata)) {
3618
- if (wanted.has(canonicalFencePath(path.resolve(listed)))) {
3619
- allowed = true;
3620
- break;
3724
+ try {
3725
+ const project = await this.resolveChatProject(chatId);
3726
+ const workspaceRoot = project
3727
+ ? project.folderPath
3728
+ : await this.resolveChatWorkspaceRoot(chatId);
3729
+ const chatRoots = [
3730
+ workspaceRoot,
3731
+ ...(project?.sourceFolders ?? []),
3732
+ chatAttachmentsDirPath(chatId),
3733
+ ...collectPackExecWritableRoots(chatId),
3734
+ ];
3735
+ allowed = chatRoots.some((root) => isPathInsideRoot(root, realPath));
3736
+ }
3737
+ catch {
3738
+ allowed = false;
3739
+ }
3740
+ if (!allowed) {
3741
+ const live = getLiveStream(chatId);
3742
+ if (live?.executedActions) {
3743
+ for (const listed of extractActionReferencedPaths(live.executedActions)) {
3744
+ if (path.isAbsolute(listed) && wanted.has(canonicalFencePath(path.resolve(listed)))) {
3745
+ allowed = true;
3746
+ break;
3747
+ }
3621
3748
  }
3622
3749
  }
3623
- if (allowed)
3624
- break;
3625
3750
  }
3626
3751
  if (!allowed) {
3627
- try {
3628
- const workspaceRoot = await this.resolveChatWorkspaceRoot(chatId);
3629
- allowed = isPathInsideRoot(workspaceRoot, realPath);
3630
- }
3631
- catch {
3632
- allowed = false;
3752
+ const messages = await this.store.listMessages(chatId, 1000);
3753
+ for (const message of messages) {
3754
+ const candidates = [
3755
+ ...turnFilePathsFromMetadata(message.messageMetadata),
3756
+ ...actionPathsFromMetadata(message.messageMetadata),
3757
+ ];
3758
+ for (const listed of candidates) {
3759
+ if (path.isAbsolute(listed) && wanted.has(canonicalFencePath(path.resolve(listed)))) {
3760
+ allowed = true;
3761
+ break;
3762
+ }
3763
+ }
3764
+ if (allowed)
3765
+ break;
3633
3766
  }
3634
3767
  }
3635
3768
  }
@@ -4111,55 +4244,17 @@ export class LocalBackendRouter {
4111
4244
  }
4112
4245
  return false;
4113
4246
  }
4114
- buildModePreamble(chatMode, latestUserMessage) {
4247
+ buildModePreamble(chatMode, _latestUserMessage) {
4115
4248
  if (chatMode !== 'plan')
4116
4249
  return '';
4117
- const lines = [
4250
+ return [
4118
4251
  '# 当前模式:PLAN(最高优先级)',
4119
4252
  '',
4120
- '- 你本轮处于 Plan 模式。先规划,后执行;不要以“我来查看/我来执行”开场。',
4121
- '- 即使本轮暴露了只读工具,工具调用也只能用于“制定计划所需的上下文调研”,不能用于完成用户目标任务本身。',
4122
- '- 区分“调研上下文”和“执行任务”:读取项目文件了解代码结构是调研;读取 `/proc/cpuinfo`、查询系统硬件、获取真实运行结果就是在执行“检查电脑配置”任务。',
4123
- '- 输出目标是一个 `plan` 代码块,让用户确认后再执行。不要在计划阶段实际检查电脑配置、读取伪系统路径或运行命令。',
4124
- ];
4125
- if (this.isLocalSystemInfoRequest(latestUserMessage)) {
4126
- lines.push('- 当前用户请求是本机系统/硬件配置类。读取 CPU/内存/磁盘/系统真实信息属于执行任务,不属于计划调研;Plan 模式下应只生成适合当前宿主系统的执行计划。', '- 如果宿主系统是 Windows,计划步骤必须使用 PowerShell/CIM,例如 `Get-CimInstance Win32_Processor`、`Get-CimInstance Win32_PhysicalMemory`、`Get-CimInstance Win32_DiskDrive`、`Get-CimInstance Win32_OperatingSystem`。');
4127
- }
4128
- return lines.join('\n');
4129
- }
4130
- isLocalSystemInfoRequest(text) {
4131
- const normalized = text.toLowerCase();
4132
- const localHints = [
4133
- '电脑配置',
4134
- '本机配置',
4135
- '我的电脑',
4136
- '系统信息',
4137
- '硬件配置',
4138
- '硬件信息',
4139
- 'cpu',
4140
- '内存',
4141
- '磁盘',
4142
- '硬盘',
4143
- '显卡',
4144
- 'gpu',
4145
- 'computer config',
4146
- 'system info',
4147
- 'hardware',
4148
- ];
4149
- const actionHints = [
4150
- '检查',
4151
- '查看',
4152
- '获取',
4153
- '读取',
4154
- '配置',
4155
- '信息',
4156
- 'check',
4157
- 'show',
4158
- 'get',
4159
- 'inspect',
4160
- ];
4161
- return (localHints.some((hint) => normalized.includes(hint)) &&
4162
- actionHints.some((hint) => normalized.includes(hint)));
4253
+ '- 你当前处于**对话式规划模式(Plan Mode)**。无论用户语气多急迫(如“帮我改一下 / 直接跑一下”),都将其视为**先制定执行方案**的请求,严禁执行任何修改环境的动作或伪装“已完成”。',
4254
+ '- **阶段 1 — 环境事实先行探查**:仓库结构、文件内容、配置字段等客观事实,先通过只读工具(`local_read_file`、`grep`、`glob`、`view_image`、`explore` 子代理、`web_search`)核实,不要拿能自己查到的问题去反问用户。注意边界:只读探查仅服务于方案制定;若用户请求本身是一次只读查询/系统巡检(如“查看本机硬件配置”),直接获取最终结果等同于执行任务,此时只输出符合当前宿主系统的巡检方案步骤。',
4255
+ '- **阶段 2 — 关键取舍用 `ask_user` 对齐**:对于无法通过探查推导的产品偏好、范围边界或架构取舍,优先调用 `ask_user` 工具提供 2–4 个有实质差异的选项(首项标 `(推荐)`);在关键分歧未确认前,先完成提问交流,不要仓促输出半成品计划块。',
4256
+ '- **阶段 3 — 唯一、决策完备的 `<proposed_plan>` 定稿块**:当目标与实施路径已明确,将完整定稿方案包裹在独立成行的 `<proposed_plan>` 与 `</proposed_plan>` 标签中(每轮至多输出 1 个定稿块;后续按反馈修订时输出完整替换版,末尾不要追问“是否开始执行”)。',
4257
+ ].join('\n');
4163
4258
  }
4164
4259
  buildRuntimeEnvironmentContext(chatMode, workingDirectory) {
4165
4260
  const platform = process.platform;
@@ -1,58 +1,46 @@
1
1
  ---
2
2
  name: plan-mode
3
- description: Loaded only in Plan mode. The agent must research with read-only tools and produce a structured plan, without executing any write/action.
3
+ description: Loaded only in Plan mode. Guides conversational three-phase planning (read-only exploration, ask_user tradeoff clarification, and a decision-complete <proposed_plan> artifact) without mutating the environment.
4
4
  priority: 950
5
5
  tags: [mode, planning]
6
6
  conditions: [plan-mode]
7
7
  ---
8
8
 
9
- # 计划模式(Plan Mode)
9
+ # 规划模式(Plan Mode · 对话式三阶段工作流)
10
10
 
11
- 你现在处于**计划模式**。本模式的唯一目标是:先把「要做什么、怎么做」想清楚并写成一份结构化计划,
12
- 交给用户确认。**你现在不能执行任何会改变环境的动作。**
11
+ 你当前处于**规划模式**。你的目标是与用户高效协作,产出一份**零悬念、可直接交接落地**的执行方案,在用户确认前**绝不执行任何改变环境的操作**。
13
12
 
14
- ## 硬性约束
13
+ ## 模式铁律
15
14
 
16
- 1. **只读调研只服务于计划**:本轮只暴露了只读工具(读文件、列卡片、查配置、探活等)。这些工具只能用于收集
17
- **制定计划所需的上下文**,不能用于完成用户目标任务本身,绝不要凭空假设。
18
- - 先判断工具调用的目的:如果调用结果会直接构成用户要的最终答案,就是在执行任务;Plan 模式下不要调用。
19
- 如果调用结果只是帮助你理解项目结构、已有卡片、配置约束或待办上下文,才属于计划调研。
20
- - 例:用户说“检查我的电脑配置”时,读取 CPU/内存/磁盘真实信息就是执行任务;Plan 模式应写出稍后要执行的
21
- Windows PowerShell/CIM 步骤,而不是先读取系统信息。
22
- - 只读文件工具不是跨平台系统信息接口;除非路径来自用户明确提供或项目真实文件,**不要猜测读取**
23
- `/proc/cpuinfo`、`/proc/meminfo`、`/sys/...`、`/etc/...` 这类操作系统专属路径。
24
- - 必须先看系统提示里的「本地运行环境」。如果宿主系统是 Windows,计划里应使用 PowerShell / CIM
25
- 命令(如 `Get-CimInstance Win32_Processor`、`Get-CimInstance Win32_PhysicalMemory`),不要写
26
- Linux/macOS 命令(`/proc`、`sysctl`、`lshw` 等)。
27
- 2. **禁止执行**:本轮**没有**暴露 shell、写文件、replay 卡片、MCP 等任何有副作用的工具,也不要尝试调用。
28
- 即使用户直接说"帮我看一下 / 跑一下 / 执行",在计划模式下也**只输出计划**,把要执行的命令写进计划步骤里。
29
- 3. **不要先答应再改口**:开场**不要**写"好的,我来帮你查看/执行…"这类承诺执行的话,也不要为"不能执行"道歉。
30
- 直接进入调研(如需要)和计划本身。
31
- 4. **不要假装已执行**:不要写"已完成 / 已修改 / 运行结果如下"这类话,因为你本轮不会真正执行。
15
+ 1. **严禁变更与越界执行**:
16
+ - 本模式已屏蔽 Shell、写/改文件、代码片段运行及任务进度表(`todo_write`)。即使用户说“帮我直接改掉 / 跑一下”,也必须将其视为**制定该任务的执行计划**。
17
+ - 不要以“好的,我现在帮你修改/执行…”开场,也不要虚构任何“已完成 / 运行结果如下”的输出。
18
+ 2. **区分两类未知信息,按三阶段推进**:
19
+ - **可探查的环境事实(Discoverable Facts)→ 先查后问**:文件路径、现有接口签名、依赖版本、目录结构等,必须先用只读工具(`local_read_file`、`grep`、`glob`、`view_image`、`explore` 子代理、`web_search`)自行查明,严禁把能从工作区读到的问题抛给用户。
20
+ - **探查与执行任务的边界**:只读工具仅用于收集制定方案所需的上下文;若用户的最终诉求本身就是一次只读查询或系统巡检(如“检查我的电脑硬件配置”),直接读取结果就等于替用户跑完了任务——此时不要读取系统信息,而是根据「本地运行环境」提示写出适配当前操作系统的检查步骤方案。
21
+ - **不可探查的偏好与取舍(Preferences & Tradeoffs)→ 优先调 `ask_user`**:涉及产品意图、范围边界或多种合理技术路线时,若本轮存在 `ask_user` 工具,**优先调用 `ask_user` 提供 2–4 个互斥选项(首项放最推荐方案并标注 `(推荐)`)**,把关键问题一次问完。
22
+ - **未收敛前不硬凑定稿块**:如果高影响歧义尚未澄清、还在等待用户回答,本轮只做探查与提问,**不要输出 `<proposed_plan>` 块**。
32
23
 
33
- ## 输出格式:plan 代码块(必须遵守)
24
+ ## 定稿方案输出协议:`<proposed_plan>` 标签块
34
25
 
35
- 计划的**步骤清单必须**放在一个 `plan` 围栏代码块里,前端会把它渲染成可视化的 todolist。格式:
26
+ 当目标与实施路径已经明确、无需执行者再做额外决策时,把完整定稿方案包裹在独立成行的 `<proposed_plan>` 与 `</proposed_plan>` 标签内(标签名保持英文原样,不要翻译或放进外层代码块里):
36
27
 
37
- ```plan
38
- # 一句话计划标题
39
- - [ ] 第一步:足够具体、可直接执行,标注用到的工具/命令/文件
40
- - [ ] 第二步:……
41
- - [ ] (可选)第三步:……
42
- ```
28
+ <proposed_plan>
29
+ # 一句话方案标题
43
30
 
44
- 规则:
31
+ 用 1–2 句话概括方案核心目标与技术选型。
45
32
 
46
- - 每个步骤一行,以 `- [ ] ` 开头;步骤要可执行、有顺序,通常 2-6 步。
47
- - 标题行以 `# ` 开头,概括这份计划。
48
- - 代码块里**只放**标题和步骤,不要放风险、问题等其他内容。
33
+ ## 核心实施步骤
34
+ - [ ] 第一步:具体到目标模块/文件/命令与行为变更
35
+ - [ ] 第二步:……
36
+ - [ ] 第三步:验证方式(测试命令、边界场景或预期产出)
49
37
 
50
- `plan` 代码块之后,再用普通 Markdown 补充(按需裁剪,保持简短):
38
+ ## 默认假设与注意点
39
+ - 列出已采用的推荐默认项或关键风险提示(无则省略本节)
40
+ </proposed_plan>
51
41
 
52
- - **风险与注意点**:可能出错、需要谨慎或不可逆的地方。
53
- - **待确认问题**:任何影响方案的歧义或缺失信息(最多问最关键的 1-3 个)。
42
+ ### 定稿规范
54
43
 
55
- ## 收尾
56
-
57
- 计划末尾用一句话提示用户:确认无误后,点击「开始执行计划」或切换到 Agent 模式,
58
- 我会按计划实际操作。若信息不足,请先回答上面的待确认问题。
44
+ - **每轮最多输出 1 个 `<proposed_plan>` 块**;内部可自由使用标准 Markdown(含二级标题、`- [ ]` 步骤清单、行内代码甚至嵌套 ` ```bash ` / ` ```ts ` 代码块)。
45
+ - **修订全量替换**:若用户留在规划模式提出修改意见,下一轮输出的新 `<proposed_plan>` 必须是整合修改后的**完整方案**,而非局部补丁。
46
+ - **收尾克制**:定稿块渲染后客户端会自动展示「开始执行计划 / 新建会话干净执行 / 继续修改计划」操作面板,正文末尾**不要**再追问“是否现在开始执行?”。
@@ -16,7 +16,7 @@ tags: [tool, guide]
16
16
 
17
17
  ## 多步任务清单(todo_write)
18
18
 
19
- 需要 3 步以上才能完成的任务(生成多页 PPT、批量改文件、多阶段调研等),**先调 `todo_write` 建任务清单再动手**,并在执行过程中**每完成一步立即更新状态**:
19
+ 仅当本轮可用工具包含 `todo_write`(执行模式)且任务需要 3 步以上才能完成(生成多页 PPT、批量改文件、多阶段调研等)时,**先调 `todo_write` 建任务清单再动手**,并在执行过程中**每完成一步立即更新状态**(规划模式下不提供也不要调用 `todo_write`):
20
20
 
21
21
  - 开始执行某项 → 标 `in_progress`(同时最多一个)
22
22
  - **某项刚做完 → 立刻在同一轮(可与下一步业务工具一起批量发出)或紧随下一步调 `todo_write` 将其标为 `completed`,并把下一项标为 `in_progress`**
@@ -176,4 +176,5 @@ export interface TurnSubagentParam {
176
176
  * @param ambientProfiles 常驻可委派画像;与提及画像同名时以提及为准。
177
177
  * @returns 下发给 sidecar 的 `subagent` 参数。
178
178
  */
179
- export declare function mergeTurnSubagentParam(mentionProfiles: Record<string, BuiltinSubagentProfile>, ambientProfiles?: Record<string, BuiltinSubagentProfile>): TurnSubagentParam;
179
+ export declare function builtinSubagentProfilesForMode(chatMode?: 'agent' | 'plan'): Record<string, BuiltinSubagentProfile>;
180
+ export declare function mergeTurnSubagentParam(mentionProfiles: Record<string, BuiltinSubagentProfile>, ambientProfiles?: Record<string, BuiltinSubagentProfile>, chatMode?: 'agent' | 'plan'): TurnSubagentParam;
@@ -362,10 +362,34 @@ export function buildDelegateRosterHint(delegates) {
362
362
  * @param ambientProfiles 常驻可委派画像;与提及画像同名时以提及为准。
363
363
  * @returns 下发给 sidecar 的 `subagent` 参数。
364
364
  */
365
- export function mergeTurnSubagentParam(mentionProfiles, ambientProfiles = {}) {
365
+ export function builtinSubagentProfilesForMode(chatMode = 'agent') {
366
+ if (chatMode !== 'plan')
367
+ return BUILTIN_SUBAGENT_PROFILES;
368
+ return {
369
+ explore: BUILTIN_SUBAGENT_PROFILES.explore,
370
+ research: {
371
+ ...BUILTIN_SUBAGENT_PROFILES.research,
372
+ toolFilter: READ_ONLY_TOOLS,
373
+ description: '深度调研(只读)。多轮 web 搜索/抓取并交叉验证,返回带来源 URL 的结论供主代理整合进计划。',
374
+ systemPrompt: [
375
+ '你是只读调研代理,任务是对一个问题做深度调研并给出可核验的结论。',
376
+ '纪律:',
377
+ '1) 每个事实性主张都必须来自真实抓取结果,并附来源 URL;',
378
+ '2) 至少两个独立来源交叉验证关键结论,来源冲突时并列呈现;',
379
+ '3) 当前处于规划模式,禁止写入或修改任何文件——直接将结论返回给父代理;',
380
+ '4) 查不到就明说,禁止编造来源或数据。',
381
+ ].join('\n'),
382
+ },
383
+ };
384
+ }
385
+ export function mergeTurnSubagentParam(mentionProfiles, ambientProfiles = {}, chatMode = 'agent') {
366
386
  const mentionNames = Object.keys(mentionProfiles);
367
387
  return {
368
- profiles: { ...BUILTIN_SUBAGENT_PROFILES, ...ambientProfiles, ...mentionProfiles },
388
+ profiles: {
389
+ ...builtinSubagentProfilesForMode(chatMode),
390
+ ...ambientProfiles,
391
+ ...mentionProfiles,
392
+ },
369
393
  ...(mentionNames.length > 4 ? { maxParallel: mentionNames.length } : {}),
370
394
  ...(mentionNames.length > 0 ? { requiredProfiles: mentionNames } : {}),
371
395
  };
@@ -301,14 +301,21 @@ export declare class LocalExecutor {
301
301
  /** 解释器探测缓存:undefined=未探测,null=探测过但没有。 */
302
302
  private pythonCommand;
303
303
  private nodeCommand;
304
- /** PEP 668 兜底 venv 的解释器路径;一旦建立,后续 python 运行都用它。 */
304
+ private uvCommand;
305
+ /** PEP 668 / uv scratch venv 的解释器路径;一旦建立,后续 python 运行都用它。 */
305
306
  private pythonVenvPath;
307
+ private scratchVenvProbed;
308
+ private scratchVenvPythonCandidate;
309
+ private resolveScratchVenvPython;
310
+ private resolveUv;
306
311
  private resolveInterpreter;
307
312
  private probeCommand;
308
313
  /**
309
- * pip 安装:`--user` 优先;遇到 PEP 668(externally-managed-environment,
310
- * Homebrew/系统 Python 的默认限制)就在 scratch 目录建 venv 兜底,
311
- * 并把 venv 解释器缓存下来供后续运行使用。
314
+ * Python 依赖安装:
315
+ * 1. 若本机有 `uv`,直接在 scratch `.venv` 中用 `uv pip install`(复用全局 wheel 缓存、
316
+ * 跳过 PEP 668 失败试探与慢速 `python -m venv` ensurepip,并限制单连接超时 20s);
317
+ * 2. 无 `uv` 时优先复用已有 `.venv`,否则 `--user` 优先,遇 PEP 668 在 scratch 目录建 venv,
318
+ * 并显式传入 `--retries 2 --timeout 15` 防止被用户 `pip.conf` 的超大 timeout 拖死。
312
319
  *
313
320
  * 返回的 `python` 字段是后续运行脚本应使用的解释器(可能已被 venv 替换)。
314
321
  */
@@ -872,9 +872,13 @@ export class LocalExecutor {
872
872
  error: `不支持的语言: ${request.language}(目前支持 python / node;其他语言请用 local_exec_shell 自行调用)`,
873
873
  };
874
874
  }
875
+ const scratchDir = this.getCodeScratchDir();
876
+ await mkdir(scratchDir, { recursive: true });
875
877
  let interpreter;
876
878
  if (language === 'python') {
877
- interpreter = this.pythonVenvPath ?? (await this.resolveInterpreter('python'));
879
+ interpreter =
880
+ (await this.resolveScratchVenvPython(scratchDir)) ??
881
+ (await this.resolveInterpreter('python'));
878
882
  if (!interpreter) {
879
883
  return {
880
884
  success: false,
@@ -895,8 +899,6 @@ export class LocalExecutor {
895
899
  };
896
900
  }
897
901
  }
898
- const scratchDir = this.getCodeScratchDir();
899
- await mkdir(scratchDir, { recursive: true });
900
902
  const installed = [];
901
903
  if (language === 'python' && request.pipPackages?.length) {
902
904
  const bad = request.pipPackages.find((p) => !PIP_PACKAGE_RE.test(p));
@@ -917,16 +919,18 @@ export class LocalExecutor {
917
919
  }
918
920
  const pkgs = request.npmPackages.map((p) => `"${p}"`).join(' ');
919
921
  const install = await this.executeShell({
920
- command: `npm install --silent --no-audit --no-fund --prefix "${scratchDir}" ${pkgs}`,
921
- timeout: 180_000,
922
+ command: `npm install --silent --no-audit --no-fund --fetch-retries=2 --fetch-timeout=15000 --prefix "${scratchDir}" ${pkgs}`,
923
+ timeout: 90_000,
922
924
  });
923
925
  if (!install.success) {
926
+ const detail = install.timedOut
927
+ ? `npm 依赖安装超时(90s):${request.npmPackages.join(', ')}。当前网络或镜像源下载过慢,请勿重复安装同一批大型依赖`
928
+ : `npm 依赖安装失败:${(install.stderr || install.error || '').slice(0, 1500)}`;
924
929
  return {
925
930
  success: false,
926
931
  language,
927
932
  interpreter,
928
- error: `npm 依赖安装失败:${(install.stderr || install.error || '').slice(0, 1500)}` +
929
- '。可考虑换用 python 实现,或把失败原因如实告诉用户。',
933
+ error: `${detail}。可考虑换用无需第三方包的方案,或把失败原因如实告诉用户。`,
930
934
  };
931
935
  }
932
936
  installed.push(...request.npmPackages);
@@ -960,8 +964,39 @@ export class LocalExecutor {
960
964
  /** 解释器探测缓存:undefined=未探测,null=探测过但没有。 */
961
965
  pythonCommand = undefined;
962
966
  nodeCommand = undefined;
963
- /** PEP 668 兜底 venv 的解释器路径;一旦建立,后续 python 运行都用它。 */
967
+ uvCommand = undefined;
968
+ /** PEP 668 / uv scratch venv 的解释器路径;一旦建立,后续 python 运行都用它。 */
964
969
  pythonVenvPath = null;
970
+ scratchVenvProbed = false;
971
+ scratchVenvPythonCandidate(scratchDir) {
972
+ const venvDir = path.join(scratchDir, '.venv');
973
+ return process.platform === 'win32'
974
+ ? path.join(venvDir, 'Scripts', 'python.exe')
975
+ : path.join(venvDir, 'bin', 'python');
976
+ }
977
+ async resolveScratchVenvPython(scratchDir) {
978
+ if (this.pythonVenvPath !== null)
979
+ return this.pythonVenvPath;
980
+ if (this.scratchVenvProbed)
981
+ return null;
982
+ this.scratchVenvProbed = true;
983
+ const candidate = this.scratchVenvPythonCandidate(scratchDir);
984
+ if (await this.probeCommand(candidate, ['--version'])) {
985
+ this.pythonVenvPath = candidate;
986
+ return candidate;
987
+ }
988
+ return null;
989
+ }
990
+ async resolveUv() {
991
+ if (this.uvCommand !== undefined)
992
+ return this.uvCommand;
993
+ if (await this.probeCommand('uv', ['--version'])) {
994
+ this.uvCommand = 'uv';
995
+ return 'uv';
996
+ }
997
+ this.uvCommand = null;
998
+ return null;
999
+ }
965
1000
  async resolveInterpreter(kind) {
966
1001
  if (kind === 'python' && this.pythonCommand !== undefined)
967
1002
  return this.pythonCommand;
@@ -1002,29 +1037,68 @@ export class LocalExecutor {
1002
1037
  });
1003
1038
  }
1004
1039
  /**
1005
- * pip 安装:`--user` 优先;遇到 PEP 668(externally-managed-environment,
1006
- * Homebrew/系统 Python 的默认限制)就在 scratch 目录建 venv 兜底,
1007
- * 并把 venv 解释器缓存下来供后续运行使用。
1040
+ * Python 依赖安装:
1041
+ * 1. 若本机有 `uv`,直接在 scratch `.venv` 中用 `uv pip install`(复用全局 wheel 缓存、
1042
+ * 跳过 PEP 668 失败试探与慢速 `python -m venv` ensurepip,并限制单连接超时 20s);
1043
+ * 2. 无 `uv` 时优先复用已有 `.venv`,否则 `--user` 优先,遇 PEP 668 在 scratch 目录建 venv,
1044
+ * 并显式传入 `--retries 2 --timeout 15` 防止被用户 `pip.conf` 的超大 timeout 拖死。
1008
1045
  *
1009
1046
  * 返回的 `python` 字段是后续运行脚本应使用的解释器(可能已被 venv 替换)。
1010
1047
  */
1011
1048
  async installPythonPackages(packages, scratchDir, python) {
1012
1049
  const callOperator = process.platform === 'win32' ? '& ' : '';
1013
1050
  const pkgs = packages.map((p) => `"${p}"`).join(' ');
1051
+ const installTimeoutMs = 90_000;
1052
+ const pipFastFailFlags = '--quiet --disable-pip-version-check --retries 2 --timeout 15';
1053
+ const formatTimeoutError = () => `Python 依赖安装超时(${installTimeoutMs / 1000}s):${packages.join(', ')}。` +
1054
+ '当前网络或包源下载过慢,请勿重复安装同一批大型依赖;可改用无需第三方包的纯标准库方案,或提示用户检查网络/镜像源。';
1055
+ const venvDir = path.join(scratchDir, '.venv');
1056
+ const venvPython = this.scratchVenvPythonCandidate(scratchDir);
1057
+ const uv = await this.resolveUv();
1058
+ if (uv) {
1059
+ if (this.pythonVenvPath === null) {
1060
+ const create = await this.executeShell({
1061
+ command: `${callOperator}"${uv}" venv --seed --clear --python "${python}" "${venvDir}"`,
1062
+ timeout: 30_000,
1063
+ });
1064
+ if (create.success) {
1065
+ this.pythonVenvPath = venvPython;
1066
+ }
1067
+ }
1068
+ if (this.pythonVenvPath !== null) {
1069
+ const uvInstall = await this.executeShell({
1070
+ command: `${callOperator}"${uv}" pip install --python "${this.pythonVenvPath}" --quiet ${pkgs}`,
1071
+ timeout: installTimeoutMs,
1072
+ env: { UV_HTTP_TIMEOUT: '20' },
1073
+ });
1074
+ if (uvInstall.success) {
1075
+ return { success: true, python: this.pythonVenvPath };
1076
+ }
1077
+ if (uvInstall.timedOut) {
1078
+ return { success: false, error: formatTimeoutError() };
1079
+ }
1080
+ const uvErr = (uvInstall.stderr || uvInstall.error || '').slice(0, 1500);
1081
+ return {
1082
+ success: false,
1083
+ error: `Python 依赖安装失败(uv):${uvErr}。可检查包名/网络,或把失败原因如实告诉用户。`,
1084
+ };
1085
+ }
1086
+ }
1014
1087
  const inVenv = this.pythonVenvPath !== null;
1015
1088
  const targetPython = this.pythonVenvPath ?? python;
1016
1089
  const userFlag = inVenv ? '' : '--user ';
1017
1090
  const install = await this.executeShell({
1018
- command: `${callOperator}"${targetPython}" -m pip install ${userFlag}--quiet ${pkgs}`,
1019
- timeout: 180_000,
1091
+ command: `${callOperator}"${targetPython}" -m pip install ${userFlag}${pipFastFailFlags} ${pkgs}`,
1092
+ timeout: installTimeoutMs,
1020
1093
  });
1021
1094
  if (install.success)
1022
1095
  return { success: true, python: targetPython };
1096
+ if (install.timedOut)
1097
+ return { success: false, error: formatTimeoutError() };
1023
1098
  const installError = (install.stderr || install.error || '').slice(0, 1500);
1024
1099
  if (!inVenv && /externally[- ]managed|PEP\s*668/i.test(installError)) {
1025
- const venvDir = path.join(scratchDir, '.venv');
1026
1100
  const create = await this.executeShell({
1027
- command: `${callOperator}"${python}" -m venv "${venvDir}"`,
1101
+ command: `${callOperator}"${python}" -m venv --clear "${venvDir}"`,
1028
1102
  timeout: 120_000,
1029
1103
  });
1030
1104
  if (!create.success) {
@@ -1033,14 +1107,13 @@ export class LocalExecutor {
1033
1107
  error: `pip --user 被 PEP 668 拒绝,且创建 venv 失败:${(create.stderr || create.error || '').slice(0, 1000)}`,
1034
1108
  };
1035
1109
  }
1036
- const venvPython = process.platform === 'win32'
1037
- ? path.join(venvDir, 'Scripts', 'python.exe')
1038
- : path.join(venvDir, 'bin', 'python');
1039
1110
  const retry = await this.executeShell({
1040
- command: `${callOperator}"${venvPython}" -m pip install --quiet ${pkgs}`,
1041
- timeout: 180_000,
1111
+ command: `${callOperator}"${venvPython}" -m pip install ${pipFastFailFlags} ${pkgs}`,
1112
+ timeout: installTimeoutMs,
1042
1113
  });
1043
1114
  if (!retry.success) {
1115
+ if (retry.timedOut)
1116
+ return { success: false, error: formatTimeoutError() };
1044
1117
  return {
1045
1118
  success: false,
1046
1119
  error: `venv 内 pip 安装失败:${(retry.stderr || retry.error || '').slice(0, 1500)}`,
@@ -8,6 +8,7 @@
8
8
  */
9
9
  import { createHash } from 'node:crypto';
10
10
  import { normalizeToolImagePayload, } from '../attachments/image-normalizer.js';
11
+ import { saveViewedImageSnapshot } from '../attachments.js';
11
12
  import { classifyShellCommand } from './safety-patterns.js';
12
13
  import { isRejectedBeforeEffectError } from './rejected-before-effect.js';
13
14
  import { compactToolResultJson } from '../local-backend/context-compactor.js';
@@ -157,6 +158,24 @@ export function createToolInvokeHandler(deps) {
157
158
  workbenchHref,
158
159
  };
159
160
  }
161
+ const invalidMeta = toolArgs._steerable_invalid_arguments;
162
+ if (invalidMeta && typeof invalidMeta === 'object') {
163
+ const meta = invalidMeta;
164
+ const truncated = meta.truncated === true;
165
+ const rawLength = typeof meta.rawLength === 'number' ? meta.rawLength : 0;
166
+ const parseErr = typeof meta.error === 'string' ? meta.error : 'invalid JSON';
167
+ const code = truncated ? 'tool_arguments_truncated' : 'invalid_tool_arguments';
168
+ const detail = truncated
169
+ ? `tool call arguments for "${name}" were truncated before closing JSON (${rawLength} chars; ${parseErr}). Do NOT retry the same large tool call; split the output into smaller chunks/edits or write a compact generator script.`
170
+ : `tool call arguments for "${name}" were not a valid JSON object (${parseErr}). Pass a valid JSON object matching the tool schema.`;
171
+ return {
172
+ success: false,
173
+ error: `${code}: ${detail}`,
174
+ effect: 'none',
175
+ retryable: true,
176
+ needsFollowup: true,
177
+ };
178
+ }
160
179
  if (schema?.inputSchema && typeof schema.inputSchema === 'object') {
161
180
  const schemaObj = schema.inputSchema;
162
181
  if (Array.isArray(schemaObj.required)) {
@@ -226,7 +245,29 @@ export function createToolInvokeHandler(deps) {
226
245
  return await recordUnknownOutcome(msg);
227
246
  }
228
247
  if (out && typeof out === 'object' && 'success' in out) {
229
- return capResultForModelContext(out);
248
+ const capped = capResultForModelContext(out);
249
+ if (chatId && capped && typeof capped === 'object') {
250
+ const cappedData = capped.data;
251
+ if (cappedData && typeof cappedData === 'object') {
252
+ const rec = cappedData;
253
+ const img = rec._image;
254
+ const srcPath = typeof rec.sourcePath === 'string'
255
+ ? rec.sourcePath
256
+ : typeof toolArgs.path === 'string'
257
+ ? toolArgs.path
258
+ : null;
259
+ if (srcPath &&
260
+ img &&
261
+ typeof img.b64 === 'string' &&
262
+ typeof img.media_type === 'string') {
263
+ await saveViewedImageSnapshot(chatId, srcPath, {
264
+ b64: img.b64,
265
+ media_type: img.media_type,
266
+ }).catch(() => { });
267
+ }
268
+ }
269
+ }
270
+ return capped;
230
271
  }
231
272
  return capResultForModelContext({ success: true, data: { value: out } });
232
273
  }
@@ -2,7 +2,7 @@ import { randomUUID } from 'crypto';
2
2
  import path from 'node:path';
3
3
  import { ALL_ROUND_ASSISTANT_AGENT_ID, LOCAL_ASSISTANT_AGENT_ID, getBrand, } from '../brand.js';
4
4
  import { isShellBuiltinAgentEnabled } from '../product-config.js';
5
- import { DEFAULT_LLM_SETTINGS, llmSettingsCarryExpiredBakedKey, llmSettingsMatchOllamaDefaults, mergeLlmSettings, } from './llm-settings.js';
5
+ import { DEFAULT_LLM_SETTINGS, llmSettingsCarryExpiredBakedKey, llmSettingsCarryRetiredDeepSeekModel, llmSettingsMatchOllamaDefaults, mergeLlmSettings, } from './llm-settings.js';
6
6
  import { emitChatActivity } from './chat-activity.js';
7
7
  import { MESSAGE_ORDER_DESC } from './message-order.js';
8
8
  import { currentStorageInstanceId, instanceOwnerIsLive, } from './process-locks.js';
@@ -801,10 +801,21 @@ export class SqliteScopedStore {
801
801
  // 到 DeepSeek 默认,避免 Windows 用户卡在"本机没装 ollama → 上来就不能聊"。
802
802
  await this.setLlmSettings(DEFAULT_LLM_SETTINGS);
803
803
  }
804
- else if (llmSettingsCarryExpiredBakedKey(hasSettings)) {
805
- // 老安装保存过已作废的出厂内置 key(≤0.0.35):静默清掉(保留其它自定义
806
- // 字段),设置页会引导用户填自己的 key。不清则用户永远拿着死 key 撞 401。
807
- await this.setLlmSettings({ ...hasSettings, apiKey: undefined });
804
+ else {
805
+ let next = hasSettings;
806
+ if (llmSettingsCarryExpiredBakedKey(next)) {
807
+ // 老安装保存过已作废的出厂内置 key(≤0.0.35):静默清掉(保留其它自定义
808
+ // 字段),设置页会引导用户填自己的 key。不清则用户永远拿着死 key 撞 401。
809
+ next = { ...next, apiKey: undefined };
810
+ }
811
+ if (llmSettingsCarryRetiredDeepSeekModel(next)) {
812
+ // DeepSeek 官方端点已下线旧默认模型 deepseek-chat:保留用户填过的 key 与
813
+ // 其它自定义字段,把模型迁到当前默认模型。
814
+ next = { ...next, model: DEFAULT_LLM_SETTINGS.model };
815
+ }
816
+ if (next !== hasSettings) {
817
+ await this.setLlmSettings(next);
818
+ }
808
819
  }
809
820
  // 其它情况(用户改过 provider/model/baseUrl/apiKey 任一项):尊重自定义,不动。
810
821
  }
@@ -76,6 +76,9 @@ export interface LlmSettings {
76
76
  }
77
77
  export declare const DEFAULT_SYSTEM_PROMPT: string;
78
78
  export declare const OPENAI_COMPAT_DEFAULTS: LlmSettings;
79
+ export declare const RETIRED_DEEPSEEK_DEFAULT_MODEL = "deepseek-chat";
80
+ /** 已存设置是否仍停留在 DeepSeek 官方端点已下线的旧默认模型。 */
81
+ export declare function llmSettingsCarryRetiredDeepSeekModel(s: LlmSettings): boolean;
79
82
  export declare const EXPIRED_BAKED_API_KEY_SHA256 = "5b761efc05315a24cb86e83a8a9e50fa773d3dc33a8ece4713faeae20ccd75e4";
80
83
  export declare function apiKeyMatchesFingerprint(apiKey: string | undefined, sha256: string): boolean;
81
84
  /** 已存设置是否还挂着作废的出厂内置 key。 */
@@ -20,13 +20,21 @@ export const DEFAULT_SYSTEM_PROMPT = `你是 ${getBrand().agentName},${getBran
20
20
  export const OPENAI_COMPAT_DEFAULTS = {
21
21
  provider: 'openai-compat',
22
22
  vendorId: 'deepseek',
23
- model: 'deepseek-chat',
23
+ model: 'deepseek-flash',
24
24
  baseUrl: 'https://api.deepseek.com',
25
25
  // temperature 缺省 = 自动:命中厂商预制(llm.presets)时用厂商文档最优
26
26
  // 值,未命中则不下发。设置页可切手动。
27
27
  systemPrompt: DEFAULT_SYSTEM_PROMPT,
28
28
  maxTotalTokens: 60000,
29
29
  };
30
+ // DeepSeek 官方 API 已下线的旧出厂默认模型,启动时静默迁到当前官方默认模型。
31
+ export const RETIRED_DEEPSEEK_DEFAULT_MODEL = 'deepseek-chat';
32
+ /** 已存设置是否仍停留在 DeepSeek 官方端点已下线的旧默认模型。 */
33
+ export function llmSettingsCarryRetiredDeepSeekModel(s) {
34
+ return (s.provider === 'openai-compat' &&
35
+ s.model === RETIRED_DEEPSEEK_DEFAULT_MODEL &&
36
+ hostnameOf(s.baseUrl ?? OPENAI_COMPAT_DEFAULTS.baseUrl) === 'api.deepseek.com');
37
+ }
30
38
  // 0.0.35 及之前打包进客户端的内置 DeepSeek key 已作废。只保留不可逆
31
39
  // SHA-256 指纹用于清理老安装;公开源码和新客户端不再携带原始凭据。
32
40
  export const EXPIRED_BAKED_API_KEY_SHA256 = '5b761efc05315a24cb86e83a8a9e50fa773d3dc33a8ece4713faeae20ccd75e4';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@steerable/agent-shell",
3
- "version": "0.14.2",
3
+ "version": "0.14.4",
4
4
  "description": "Steerable framework — product-neutral Node HostRuntime and headless HTTP server shared by Tauri desktop and browser deployments; scenario packs extend it through @steerable/pack-sdk.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://steerableframework.com/",
@@ -53,10 +53,10 @@
53
53
  "jpeg-js": "^0.4.4",
54
54
  "node-pty": "^1.1.0",
55
55
  "pngjs": "^7.0.0",
56
- "@steerable/agent-harness": "0.14.2",
57
- "@steerable/agent-runtime": "0.14.2",
58
- "@steerable/pack-sdk": "0.14.2",
59
- "@steerable/agent-protocol": "0.14.2"
56
+ "@steerable/agent-harness": "0.14.4",
57
+ "@steerable/agent-protocol": "0.14.4",
58
+ "@steerable/agent-runtime": "0.14.4",
59
+ "@steerable/pack-sdk": "0.14.4"
60
60
  },
61
61
  "devDependencies": {
62
62
  "@types/better-sqlite3": "^7.6.13",