@steerable/agent-shell 0.14.1 → 0.14.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.
@@ -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
+ }
@@ -2,12 +2,20 @@ import type { CredentialInjection, PackCredentialClient, PackDataSource, Princip
2
2
  import type { ScopedStore } from '../storage/scoped-store.js';
3
3
  export declare const REDACTED_CREDENTIAL_MARKER = "[REDACTED:credential]";
4
4
  export declare const TENANT_CREDENTIAL_OWNER = "__tenant__";
5
+ /**
6
+ * Registers a host-level secret so every `SecretRedactor` instance created
7
+ * afterward scrubs its raw, URL-encoded, and Base64-encoded forms.
8
+ */
9
+ export declare function registerGlobalSecret(secret: string): () => void;
10
+ /** Clears process-wide registered secrets in unit tests. */
11
+ export declare function clearGlobalSecretsForTests(): void;
5
12
  /**
6
13
  * Tracks active plaintext secrets and scrubs their raw, URL-encoded, and
7
14
  * base64-encoded forms from strings and structured JSON payloads.
8
15
  */
9
16
  export declare class SecretRedactor {
10
17
  private readonly needles;
18
+ constructor();
11
19
  /** Registers one or more secret strings for scrubbing. */
12
20
  registerSecret(secret: string): void;
13
21
  /** Registers every string leaf inside a CredentialInjection payload. */
@@ -27,12 +27,35 @@ export const TENANT_CREDENTIAL_OWNER = '__tenant__';
27
27
  const MIN_REDACT_SECRET_LEN = 4;
28
28
  const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
29
29
  const MAX_CREDENTIAL_REDIRECTS = 5;
30
+ const globalSecretNeedles = new Set();
31
+ /**
32
+ * Registers a host-level secret so every `SecretRedactor` instance created
33
+ * afterward scrubs its raw, URL-encoded, and Base64-encoded forms.
34
+ */
35
+ export function registerGlobalSecret(secret) {
36
+ const trimmed = secret.trim();
37
+ if (trimmed.length < MIN_REDACT_SECRET_LEN)
38
+ return () => { };
39
+ globalSecretNeedles.add(trimmed);
40
+ return () => {
41
+ globalSecretNeedles.delete(trimmed);
42
+ };
43
+ }
44
+ /** Clears process-wide registered secrets in unit tests. */
45
+ export function clearGlobalSecretsForTests() {
46
+ globalSecretNeedles.clear();
47
+ }
30
48
  /**
31
49
  * Tracks active plaintext secrets and scrubs their raw, URL-encoded, and
32
50
  * base64-encoded forms from strings and structured JSON payloads.
33
51
  */
34
52
  export class SecretRedactor {
35
53
  needles = new Set();
54
+ constructor() {
55
+ for (const secret of globalSecretNeedles) {
56
+ this.registerSecret(secret);
57
+ }
58
+ }
36
59
  /** Registers one or more secret strings for scrubbing. */
37
60
  registerSecret(secret) {
38
61
  const trimmed = secret.trim();
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Registers additional exact environment variable names or `PREFIX_` patterns
3
+ * to strip from tool-spawned child processes.
4
+ *
5
+ * Entries ending with `_` match as case-insensitive prefixes; all other entries
6
+ * match exact variable names case-insensitively.
7
+ */
8
+ export declare function registerProtectedEnvKeys(entries: readonly string[]): () => void;
9
+ /** Clears custom protected env rules in unit tests. */
10
+ export declare function resetProtectedEnvKeysForTests(): void;
11
+ /** True when `key` is a host-protected secret variable that tools must not inherit. */
12
+ export declare function isProtectedHostEnvKey(key: string): boolean;
13
+ /**
14
+ * Builds a clean child-process environment from `sourceEnv`, stripping
15
+ * host-protected keys (and registering their values into `SecretRedactor`),
16
+ * then applying caller-supplied `extraEnv`.
17
+ */
18
+ export declare function scrubToolSubprocessEnv(sourceEnv?: NodeJS.ProcessEnv, extraEnv?: Record<string, string>): Record<string, string>;
19
+ /** Scrubs any registered global/host secrets from subprocess text output. */
20
+ export declare function redactSubprocessText(text: string): string;
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Product-neutral environment sanitizer for tool-spawned child processes
3
+ * (`local_exec_shell`, `local_run_snippet`, and interactive PTY sessions).
4
+ *
5
+ * Host master keys, internal RPC tokens, shared database URLs, and host-managed
6
+ * model provider API keys are stripped from ambient `process.env` before a tool
7
+ * subprocess starts, while explicit per-call `extraEnv` (such as `custom_env`
8
+ * injections authorized through `CredentialBroker`) is preserved.
9
+ */
10
+ import { SecretRedactor, registerGlobalSecret } from './auth/credentials.js';
11
+ const DEFAULT_PROTECTED_EXACT_KEYS = new Set([
12
+ 'STEERABLE_CREDENTIAL_MASTER_KEY',
13
+ 'DEEPSEEK_API_KEY',
14
+ 'OPENAI_API_KEY',
15
+ 'OPENAI_COMPAT_API_KEY',
16
+ 'ANTHROPIC_API_KEY',
17
+ 'GEMINI_API_KEY',
18
+ 'GOOGLE_API_KEY',
19
+ 'DASHSCOPE_API_KEY',
20
+ ]);
21
+ const DEFAULT_PROTECTED_PREFIXES = [
22
+ 'STEERABLE_INTERNAL_',
23
+ ];
24
+ const DEFAULT_PROTECTED_SUFFIXES = [
25
+ '_INTERNAL_TOKEN',
26
+ '_INTERNAL_BEARER',
27
+ '_BOOTSTRAP_TOKEN',
28
+ '_MYSQL_URL',
29
+ '_DATABASE_URL',
30
+ '_POSTGRES_URL',
31
+ ];
32
+ const customExactKeys = new Set();
33
+ const customPrefixes = new Set();
34
+ /**
35
+ * Registers additional exact environment variable names or `PREFIX_` patterns
36
+ * to strip from tool-spawned child processes.
37
+ *
38
+ * Entries ending with `_` match as case-insensitive prefixes; all other entries
39
+ * match exact variable names case-insensitively.
40
+ */
41
+ export function registerProtectedEnvKeys(entries) {
42
+ const addedExact = [];
43
+ const addedPrefixes = [];
44
+ for (const raw of entries) {
45
+ const upper = raw.trim().toUpperCase();
46
+ if (!upper)
47
+ continue;
48
+ if (upper.endsWith('_')) {
49
+ if (!customPrefixes.has(upper)) {
50
+ customPrefixes.add(upper);
51
+ addedPrefixes.push(upper);
52
+ }
53
+ }
54
+ else if (!customExactKeys.has(upper)) {
55
+ customExactKeys.add(upper);
56
+ addedExact.push(upper);
57
+ }
58
+ }
59
+ return () => {
60
+ for (const k of addedExact)
61
+ customExactKeys.delete(k);
62
+ for (const p of addedPrefixes)
63
+ customPrefixes.delete(p);
64
+ };
65
+ }
66
+ /** Clears custom protected env rules in unit tests. */
67
+ export function resetProtectedEnvKeysForTests() {
68
+ customExactKeys.clear();
69
+ customPrefixes.clear();
70
+ }
71
+ /** True when `key` is a host-protected secret variable that tools must not inherit. */
72
+ export function isProtectedHostEnvKey(key) {
73
+ const upper = key.trim().toUpperCase();
74
+ if (!upper)
75
+ return false;
76
+ if (DEFAULT_PROTECTED_EXACT_KEYS.has(upper) || customExactKeys.has(upper)) {
77
+ return true;
78
+ }
79
+ for (const prefix of DEFAULT_PROTECTED_PREFIXES) {
80
+ if (upper.startsWith(prefix))
81
+ return true;
82
+ }
83
+ for (const prefix of customPrefixes) {
84
+ if (upper.startsWith(prefix))
85
+ return true;
86
+ }
87
+ for (const suffix of DEFAULT_PROTECTED_SUFFIXES) {
88
+ if (upper.endsWith(suffix))
89
+ return true;
90
+ }
91
+ return false;
92
+ }
93
+ function registerUrlPasswordIfPresent(raw) {
94
+ try {
95
+ const parsed = new URL(raw);
96
+ if (parsed.password) {
97
+ registerGlobalSecret(decodeURIComponent(parsed.password));
98
+ }
99
+ }
100
+ catch {
101
+ // Non-URL secret value; full string registration already covers it.
102
+ }
103
+ }
104
+ /**
105
+ * Builds a clean child-process environment from `sourceEnv`, stripping
106
+ * host-protected keys (and registering their values into `SecretRedactor`),
107
+ * then applying caller-supplied `extraEnv`.
108
+ */
109
+ export function scrubToolSubprocessEnv(sourceEnv = process.env, extraEnv) {
110
+ const clean = {};
111
+ for (const [key, value] of Object.entries(sourceEnv)) {
112
+ if (typeof value !== 'string')
113
+ continue;
114
+ if (isProtectedHostEnvKey(key)) {
115
+ if (value.trim().length > 0) {
116
+ registerGlobalSecret(value);
117
+ registerUrlPasswordIfPresent(value);
118
+ }
119
+ continue;
120
+ }
121
+ clean[key] = value;
122
+ }
123
+ if (extraEnv) {
124
+ for (const [key, value] of Object.entries(extraEnv)) {
125
+ if (typeof value === 'string') {
126
+ clean[key] = value;
127
+ }
128
+ }
129
+ }
130
+ return clean;
131
+ }
132
+ /** Scrubs any registered global/host secrets from subprocess text output. */
133
+ export function redactSubprocessText(text) {
134
+ if (!text)
135
+ return text;
136
+ const redactor = new SecretRedactor();
137
+ return redactor.hasSecrets ? redactor.redactString(text) : text;
138
+ }
@@ -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,
@@ -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,
@@ -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
  }
@@ -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
  */
@@ -11,6 +11,7 @@ import { adaptCommandForPowerShell } from './shell-adapt.js';
11
11
  import { evaluateExecPolicy, planSshArgv, } from './shell-exec.js';
12
12
  import { nodeShellBackend } from './shell-process.js';
13
13
  import { closeShellSession, readShellSession, shellSessionStatus, startPtySession, } from './shell-session.js';
14
+ import { redactSubprocessText, scrubToolSubprocessEnv } from './env-sanitizer.js';
14
15
  import { applyEdits, EditError } from './local-edit.js';
15
16
  // `he` ships as CommonJS and does not expose ESM named exports, so we have to
16
17
  // take the default import and destructure at runtime in this ESM module.
@@ -242,14 +243,7 @@ const BUILTIN_DANGEROUS = [
242
243
  { id: 'win_rd_force', pattern: '\\brd\\s+\\/s\\s+\\/q\\s+[a-z]:\\\\', platform: 'windows' },
243
244
  ];
244
245
  function stringEnv(extra) {
245
- const env = {};
246
- for (const [key, value] of Object.entries(process.env)) {
247
- if (typeof value === 'string')
248
- env[key] = value;
249
- }
250
- if (extra)
251
- Object.assign(env, extra);
252
- return env;
246
+ return scrubToolSubprocessEnv(process.env, extra);
253
247
  }
254
248
  function toWslPath(input) {
255
249
  const normalized = input.replace(/\\/g, '/');
@@ -418,7 +412,7 @@ export class LocalExecutor {
418
412
  }
419
413
  const timeout = Math.max(1000, rawTimeout);
420
414
  const cwd = this.resolveCwd(request.cwd, resolvedShell.type);
421
- const env = { ...process.env, ...(request.env || {}) };
415
+ const env = scrubToolSubprocessEnv(process.env, request.env);
422
416
  if (this.shellBackend || useSsh || request.pty) {
423
417
  return await this.runPlannedShell({
424
418
  command,
@@ -506,9 +500,9 @@ export class LocalExecutor {
506
500
  clearTimeout(timer);
507
501
  resolve({
508
502
  success: false,
509
- stdout: Buffer.concat(stdoutChunks).toString('utf-8'),
510
- stderr: Buffer.concat(stderrChunks).toString('utf-8'),
511
- error: err.message,
503
+ stdout: redactSubprocessText(Buffer.concat(stdoutChunks).toString('utf-8')),
504
+ stderr: redactSubprocessText(Buffer.concat(stderrChunks).toString('utf-8')),
505
+ error: redactSubprocessText(err.message),
512
506
  truncated,
513
507
  shell: resolvedShell.type,
514
508
  platform: process.platform,
@@ -518,8 +512,8 @@ export class LocalExecutor {
518
512
  clearTimeout(timer);
519
513
  resolve({
520
514
  success: exitCode === 0,
521
- stdout: Buffer.concat(stdoutChunks).toString('utf-8'),
522
- stderr: Buffer.concat(stderrChunks).toString('utf-8'),
515
+ stdout: redactSubprocessText(Buffer.concat(stdoutChunks).toString('utf-8')),
516
+ stderr: redactSubprocessText(Buffer.concat(stderrChunks).toString('utf-8')),
523
517
  exitCode: exitCode ?? -1,
524
518
  truncated,
525
519
  shell: resolvedShell.type,
@@ -878,9 +872,13 @@ export class LocalExecutor {
878
872
  error: `不支持的语言: ${request.language}(目前支持 python / node;其他语言请用 local_exec_shell 自行调用)`,
879
873
  };
880
874
  }
875
+ const scratchDir = this.getCodeScratchDir();
876
+ await mkdir(scratchDir, { recursive: true });
881
877
  let interpreter;
882
878
  if (language === 'python') {
883
- interpreter = this.pythonVenvPath ?? (await this.resolveInterpreter('python'));
879
+ interpreter =
880
+ (await this.resolveScratchVenvPython(scratchDir)) ??
881
+ (await this.resolveInterpreter('python'));
884
882
  if (!interpreter) {
885
883
  return {
886
884
  success: false,
@@ -901,8 +899,6 @@ export class LocalExecutor {
901
899
  };
902
900
  }
903
901
  }
904
- const scratchDir = this.getCodeScratchDir();
905
- await mkdir(scratchDir, { recursive: true });
906
902
  const installed = [];
907
903
  if (language === 'python' && request.pipPackages?.length) {
908
904
  const bad = request.pipPackages.find((p) => !PIP_PACKAGE_RE.test(p));
@@ -923,16 +919,18 @@ export class LocalExecutor {
923
919
  }
924
920
  const pkgs = request.npmPackages.map((p) => `"${p}"`).join(' ');
925
921
  const install = await this.executeShell({
926
- command: `npm install --silent --no-audit --no-fund --prefix "${scratchDir}" ${pkgs}`,
927
- 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,
928
924
  });
929
925
  if (!install.success) {
926
+ const detail = install.timedOut
927
+ ? `npm 依赖安装超时(90s):${request.npmPackages.join(', ')}。当前网络或镜像源下载过慢,请勿重复安装同一批大型依赖`
928
+ : `npm 依赖安装失败:${(install.stderr || install.error || '').slice(0, 1500)}`;
930
929
  return {
931
930
  success: false,
932
931
  language,
933
932
  interpreter,
934
- error: `npm 依赖安装失败:${(install.stderr || install.error || '').slice(0, 1500)}` +
935
- '。可考虑换用 python 实现,或把失败原因如实告诉用户。',
933
+ error: `${detail}。可考虑换用无需第三方包的方案,或把失败原因如实告诉用户。`,
936
934
  };
937
935
  }
938
936
  installed.push(...request.npmPackages);
@@ -966,8 +964,39 @@ export class LocalExecutor {
966
964
  /** 解释器探测缓存:undefined=未探测,null=探测过但没有。 */
967
965
  pythonCommand = undefined;
968
966
  nodeCommand = undefined;
969
- /** PEP 668 兜底 venv 的解释器路径;一旦建立,后续 python 运行都用它。 */
967
+ uvCommand = undefined;
968
+ /** PEP 668 / uv scratch venv 的解释器路径;一旦建立,后续 python 运行都用它。 */
970
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
+ }
971
1000
  async resolveInterpreter(kind) {
972
1001
  if (kind === 'python' && this.pythonCommand !== undefined)
973
1002
  return this.pythonCommand;
@@ -1008,29 +1037,68 @@ export class LocalExecutor {
1008
1037
  });
1009
1038
  }
1010
1039
  /**
1011
- * pip 安装:`--user` 优先;遇到 PEP 668(externally-managed-environment,
1012
- * Homebrew/系统 Python 的默认限制)就在 scratch 目录建 venv 兜底,
1013
- * 并把 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 拖死。
1014
1045
  *
1015
1046
  * 返回的 `python` 字段是后续运行脚本应使用的解释器(可能已被 venv 替换)。
1016
1047
  */
1017
1048
  async installPythonPackages(packages, scratchDir, python) {
1018
1049
  const callOperator = process.platform === 'win32' ? '& ' : '';
1019
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
+ }
1020
1087
  const inVenv = this.pythonVenvPath !== null;
1021
1088
  const targetPython = this.pythonVenvPath ?? python;
1022
1089
  const userFlag = inVenv ? '' : '--user ';
1023
1090
  const install = await this.executeShell({
1024
- command: `${callOperator}"${targetPython}" -m pip install ${userFlag}--quiet ${pkgs}`,
1025
- timeout: 180_000,
1091
+ command: `${callOperator}"${targetPython}" -m pip install ${userFlag}${pipFastFailFlags} ${pkgs}`,
1092
+ timeout: installTimeoutMs,
1026
1093
  });
1027
1094
  if (install.success)
1028
1095
  return { success: true, python: targetPython };
1096
+ if (install.timedOut)
1097
+ return { success: false, error: formatTimeoutError() };
1029
1098
  const installError = (install.stderr || install.error || '').slice(0, 1500);
1030
1099
  if (!inVenv && /externally[- ]managed|PEP\s*668/i.test(installError)) {
1031
- const venvDir = path.join(scratchDir, '.venv');
1032
1100
  const create = await this.executeShell({
1033
- command: `${callOperator}"${python}" -m venv "${venvDir}"`,
1101
+ command: `${callOperator}"${python}" -m venv --clear "${venvDir}"`,
1034
1102
  timeout: 120_000,
1035
1103
  });
1036
1104
  if (!create.success) {
@@ -1039,14 +1107,13 @@ export class LocalExecutor {
1039
1107
  error: `pip --user 被 PEP 668 拒绝,且创建 venv 失败:${(create.stderr || create.error || '').slice(0, 1000)}`,
1040
1108
  };
1041
1109
  }
1042
- const venvPython = process.platform === 'win32'
1043
- ? path.join(venvDir, 'Scripts', 'python.exe')
1044
- : path.join(venvDir, 'bin', 'python');
1045
1110
  const retry = await this.executeShell({
1046
- command: `${callOperator}"${venvPython}" -m pip install --quiet ${pkgs}`,
1047
- timeout: 180_000,
1111
+ command: `${callOperator}"${venvPython}" -m pip install ${pipFastFailFlags} ${pkgs}`,
1112
+ timeout: installTimeoutMs,
1048
1113
  });
1049
1114
  if (!retry.success) {
1115
+ if (retry.timedOut)
1116
+ return { success: false, error: formatTimeoutError() };
1050
1117
  return {
1051
1118
  success: false,
1052
1119
  error: `venv 内 pip 安装失败:${(retry.stderr || retry.error || '').slice(0, 1500)}`,
@@ -4,24 +4,19 @@
4
4
  */
5
5
  import { randomUUID } from 'node:crypto';
6
6
  import * as pty from 'node-pty';
7
+ import { redactSubprocessText, scrubToolSubprocessEnv } from './env-sanitizer.js';
7
8
  import { stripAnsi } from './shell-process.js';
8
9
  const MAX_SESSION_MS = 10 * 60 * 1000;
9
10
  const QUIET_MS = 200;
10
11
  const MAX_YIELD_MS = 120_000;
11
12
  const sessions = new Map();
12
13
  function stringEnv(env) {
13
- const next = {};
14
- for (const [key, value] of Object.entries(process.env)) {
15
- if (typeof value === 'string')
16
- next[key] = value;
17
- }
18
- if (env)
19
- Object.assign(next, env);
14
+ const next = scrubToolSubprocessEnv(process.env, env);
20
15
  next.TERM = 'xterm-256color';
21
16
  return next;
22
17
  }
23
18
  function takeNew(live) {
24
- const fresh = stripAnsi(live.raw.slice(live.cursor));
19
+ const fresh = redactSubprocessText(stripAnsi(live.raw.slice(live.cursor)));
25
20
  live.cursor = live.raw.length;
26
21
  return fresh;
27
22
  }
@@ -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.1",
3
+ "version": "0.14.3",
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.1",
57
- "@steerable/agent-protocol": "0.14.1",
58
- "@steerable/agent-runtime": "0.14.1",
59
- "@steerable/pack-sdk": "0.14.1"
56
+ "@steerable/agent-harness": "0.14.3",
57
+ "@steerable/agent-protocol": "0.14.3",
58
+ "@steerable/agent-runtime": "0.14.3",
59
+ "@steerable/pack-sdk": "0.14.3"
60
60
  },
61
61
  "devDependencies": {
62
62
  "@types/better-sqlite3": "^7.6.13",