@steerable/steer 0.0.0-stage → 0.3.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +35 -2
  3. package/bin/steer.js +2 -0
  4. package/dist/packages/doc-preview/src/assemble.js +183 -0
  5. package/dist/packages/doc-preview/src/edit-failure.js +116 -0
  6. package/dist/packages/doc-preview/src/edit-service.js +879 -0
  7. package/dist/packages/doc-preview/src/edit.js +437 -0
  8. package/dist/packages/doc-preview/src/export.js +540 -0
  9. package/dist/packages/doc-preview/src/index.js +5 -0
  10. package/dist/packages/doc-preview/src/migrations.js +77 -0
  11. package/dist/packages/doc-preview/src/office-converter.js +186 -0
  12. package/dist/packages/doc-preview/src/office-file-preview.js +457 -0
  13. package/dist/packages/doc-preview/src/office-media.js +80 -0
  14. package/dist/packages/doc-preview/src/office-raster.js +146 -0
  15. package/dist/packages/doc-preview/src/office-routes.js +191 -0
  16. package/dist/packages/doc-preview/src/office-runtime.js +251 -0
  17. package/dist/packages/doc-preview/src/preview.js +296 -0
  18. package/dist/packages/doc-preview/src/render.js +351 -0
  19. package/dist/packages/doc-preview/src/routes.js +376 -0
  20. package/dist/packages/doc-preview/src/settings.js +58 -0
  21. package/dist/packages/doc-preview/src/store.js +134 -0
  22. package/dist/packages/doc-preview/src/tasks.js +16 -0
  23. package/dist/packages/doc-preview/src/word-font.js +232 -0
  24. package/dist/packages/doc-preview/src/word-preview.js +292 -0
  25. package/dist/packages/doc-preview/src/word-render.js +283 -0
  26. package/dist/packages/doc-preview/src/word-routes.js +203 -0
  27. package/dist/packages/doc-preview/src/workspace.js +100 -0
  28. package/dist/products/bundled-python.js +110 -0
  29. package/dist/products/load-locale.js +38 -0
  30. package/dist/products/manifest.json +13 -0
  31. package/dist/products/node-gate.js +131 -0
  32. package/dist/products/steer/active.js +93 -0
  33. package/dist/products/steer/browser-detect.js +230 -0
  34. package/dist/products/steer/browser-protocol.js +2 -0
  35. package/dist/products/steer/browser-session.js +811 -0
  36. package/dist/products/steer/browser.js +521 -0
  37. package/dist/products/steer/cli-main.js +13 -0
  38. package/dist/products/steer/cli.js +8 -0
  39. package/dist/products/steer/computer-macos.js +126 -0
  40. package/dist/products/steer/computer-session.js +118 -0
  41. package/dist/products/steer/computer.js +186 -0
  42. package/dist/products/steer/file-preview.js +392 -0
  43. package/dist/products/steer/locales/shell.zh.json +1120 -0
  44. package/dist/products/steer/locales/zh.json +95 -0
  45. package/dist/products/steer/markdown-preview.js +139 -0
  46. package/dist/products/steer/migrate-legacy-data.js +238 -0
  47. package/dist/products/steer/permissions.js +174 -0
  48. package/dist/products/steer/product.json +85 -0
  49. package/dist/products/steer/server.js +8 -0
  50. package/dist/products/steer/skill-read.js +105 -0
  51. package/dist/products/steer/turn-changes.js +187 -0
  52. package/package.json +38 -4
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Steer 电脑操作会话。一个会话一份允许名单。
3
+ * 不在名单里的应用不能点击或输入。点击和输入之后重新截取窗口,右侧看到新画面。
4
+ * 真正的键鼠由可替换的驱动执行,测试不操作本机桌面。
5
+ */
6
+ export class ComputerActionError extends Error {
7
+ status;
8
+ constructor(message, status = 400) {
9
+ super(message);
10
+ this.name = 'ComputerActionError';
11
+ this.status = status;
12
+ }
13
+ }
14
+ const APP_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,200}$/;
15
+ const MAX_TEXT = 4_000;
16
+ /** 应用标识只接受包名这种字符,避免写进系统脚本时被拼进别的语句。 */
17
+ export function assertComputerAppId(appId) {
18
+ const trimmed = appId.trim();
19
+ if (!APP_ID.test(trimmed)) {
20
+ throw new ComputerActionError('Enter an application id such as com.example.notes.');
21
+ }
22
+ return trimmed;
23
+ }
24
+ function assertPoint(x, y) {
25
+ if (!Number.isFinite(x) || !Number.isFinite(y) || x < 0 || y < 0 || x > 20_000 || y > 20_000) {
26
+ throw new ComputerActionError('Click coordinates are out of range.');
27
+ }
28
+ return { x: Math.round(x), y: Math.round(y) };
29
+ }
30
+ function blank() {
31
+ return { allowed: [], appId: null, title: '', screenshotBase64: null };
32
+ }
33
+ function present(chat) {
34
+ return {
35
+ allowed: [...chat.allowed],
36
+ appId: chat.appId,
37
+ title: chat.title,
38
+ screenshotBase64: chat.screenshotBase64,
39
+ };
40
+ }
41
+ export function createComputerController(driver) {
42
+ const chats = new Map();
43
+ const chatFor = (chatId) => {
44
+ const existing = chats.get(chatId);
45
+ if (existing)
46
+ return existing;
47
+ const created = blank();
48
+ chats.set(chatId, created);
49
+ return created;
50
+ };
51
+ const requireAllowed = (chat, appId) => {
52
+ const id = assertComputerAppId(appId);
53
+ if (!chat.allowed.includes(id)) {
54
+ throw new ComputerActionError(`App "${id}" is not on the allowlist.`, 403);
55
+ }
56
+ return id;
57
+ };
58
+ const capture = async (chat, appId) => {
59
+ const shot = await driver.screenshot(appId);
60
+ chat.appId = appId;
61
+ chat.title = shot.title;
62
+ chat.screenshotBase64 = shot.pngBase64;
63
+ return present(chat);
64
+ };
65
+ return {
66
+ async allow(chatId, appId) {
67
+ const id = assertComputerAppId(appId);
68
+ const chat = chatFor(chatId);
69
+ if (!chat.allowed.includes(id))
70
+ chat.allowed.push(id);
71
+ return capture(chat, id);
72
+ },
73
+ async allowFrontmost(chatId) {
74
+ const front = await driver.frontmost();
75
+ if (!front?.appId)
76
+ throw new ComputerActionError('No application is in front.');
77
+ const id = assertComputerAppId(front.appId);
78
+ const chat = chatFor(chatId);
79
+ if (!chat.allowed.includes(id))
80
+ chat.allowed.push(id);
81
+ const shot = await driver.screenshot(id);
82
+ chat.appId = id;
83
+ chat.title = shot.title || front.title;
84
+ chat.screenshotBase64 = shot.pngBase64;
85
+ return present(chat);
86
+ },
87
+ async click(chatId, appId, x, y) {
88
+ const chat = chatFor(chatId);
89
+ const id = requireAllowed(chat, appId);
90
+ const point = assertPoint(x, y);
91
+ await driver.click(id, point.x, point.y);
92
+ return capture(chat, id);
93
+ },
94
+ async typeText(chatId, appId, text) {
95
+ const chat = chatFor(chatId);
96
+ const id = requireAllowed(chat, appId);
97
+ if (!text)
98
+ throw new ComputerActionError('Enter text to type.');
99
+ if (text.length > MAX_TEXT)
100
+ throw new ComputerActionError('That text is too long to type.');
101
+ await driver.typeText(id, text);
102
+ return capture(chat, id);
103
+ },
104
+ async screenshot(chatId, appId) {
105
+ const chat = chatFor(chatId);
106
+ const id = appId && appId.trim() ? requireAllowed(chat, appId) : chat.appId;
107
+ if (!id)
108
+ throw new ComputerActionError('No application is selected.');
109
+ if (!chat.allowed.includes(id)) {
110
+ throw new ComputerActionError(`App "${id}" is not on the allowlist.`, 403);
111
+ }
112
+ return capture(chat, id);
113
+ },
114
+ view(chatId) {
115
+ return present(chatFor(chatId));
116
+ },
117
+ };
118
+ }
@@ -0,0 +1,186 @@
1
+ /**
2
+ * Steer 的电脑操作栏。用户把应用放进允许名单,智能体只能点击和输入这些应用。
3
+ * 右侧屏幕和工具共用一个会话。不进框架,其他产品不注册这些工具和路由。
4
+ */
5
+ import { getPackAssemblies, registerPackAssembly, } from '@steerable/agent-shell/host/pack-assembly';
6
+ import { matchPackBackendRoute, registerPackBackendRoutes, } from '@steerable/agent-shell/local-backend/pack-backend-routes';
7
+ import { normalizeToolImagePayload, } from '@steerable/agent-shell/attachments/image-normalizer';
8
+ import { createMacComputerDriver } from './computer-macos.js';
9
+ import { ComputerActionError, createComputerController, } from './computer-session.js';
10
+ export const COMPUTER_ROUTE = '/api/v2/steer/computer';
11
+ const sharedComputer = createComputerController(createMacComputerDriver());
12
+ function validChatId(chatId) {
13
+ return /^[0-9a-zA-Z_-]{1,200}$/.test(chatId);
14
+ }
15
+ function readRecord(body) {
16
+ if (!body || typeof body !== 'object' || Array.isArray(body))
17
+ return {};
18
+ return body;
19
+ }
20
+ function chatIdFrom(query, body) {
21
+ const record = readRecord(body);
22
+ const fromBody = typeof record.chatId === 'string' ? record.chatId : '';
23
+ return fromBody || query.get('chatId') || '';
24
+ }
25
+ function toolView(view) {
26
+ const normalizedShot = view.screenshotBase64
27
+ ? normalizeToolImagePayload({
28
+ b64: view.screenshotBase64,
29
+ media_type: 'image/png',
30
+ }).b64
31
+ : view.screenshotBase64;
32
+ return {
33
+ success: true,
34
+ appId: view.appId,
35
+ title: view.title,
36
+ screenshotBase64: normalizedShot,
37
+ allowed: view.allowed,
38
+ };
39
+ }
40
+ async function runTool(context, action) {
41
+ if (!context.chatId)
42
+ return { success: false, error: 'No chat is open.' };
43
+ try {
44
+ return toolView(await action(context.chatId));
45
+ }
46
+ catch (err) {
47
+ const message = err instanceof Error ? err.message : String(err);
48
+ return { success: false, error: message || 'Computer action failed.' };
49
+ }
50
+ }
51
+ function numberArg(value) {
52
+ return typeof value === 'number' ? value : Number.NaN;
53
+ }
54
+ /** 模型可见的电脑操作工具。允许名单只能由用户在屏幕栏里添加。 */
55
+ export function createSteerComputerTools(controller) {
56
+ return [
57
+ {
58
+ name: 'computer_click',
59
+ description: 'Click inside an application the user has already allowed. x and y are screen coordinates. '
60
+ + 'The user watches this click in the screen tab, which then shows the updated window. '
61
+ + 'If the app is not on the allowlist, ask the user to allow it in that tab. Do not invent an allow step.',
62
+ mode: 'local',
63
+ inputSchema: {
64
+ type: 'object',
65
+ properties: {
66
+ appId: { type: 'string', description: 'Application id, such as com.example.notes.' },
67
+ x: { type: 'number', description: 'Horizontal screen coordinate.' },
68
+ y: { type: 'number', description: 'Vertical screen coordinate.' },
69
+ },
70
+ required: ['appId', 'x', 'y'],
71
+ additionalProperties: false,
72
+ },
73
+ handler: (args, context) => runTool(context, (chatId) => controller.click(chatId, typeof args.appId === 'string' ? args.appId : '', numberArg(args.x), numberArg(args.y))),
74
+ },
75
+ {
76
+ name: 'computer_type',
77
+ description: 'Type text into an application the user has already allowed. The screen tab shows the window afterward.',
78
+ mode: 'local',
79
+ inputSchema: {
80
+ type: 'object',
81
+ properties: {
82
+ appId: { type: 'string', description: 'Application id, such as com.example.notes.' },
83
+ text: { type: 'string', description: 'Text to type. Newlines become Return.' },
84
+ },
85
+ required: ['appId', 'text'],
86
+ additionalProperties: false,
87
+ },
88
+ handler: (args, context) => runTool(context, (chatId) => controller.typeText(chatId, typeof args.appId === 'string' ? args.appId : '', typeof args.text === 'string' ? args.text : '')),
89
+ },
90
+ {
91
+ name: 'computer_screenshot',
92
+ description: 'Capture the current window of an allowed application and show it in the screen tab.',
93
+ mode: 'read',
94
+ inputSchema: {
95
+ type: 'object',
96
+ properties: {
97
+ appId: { type: 'string', description: 'Application id. Omit to capture the app already on screen.' },
98
+ },
99
+ additionalProperties: false,
100
+ },
101
+ handler: (args, context) => runTool(context, (chatId) => controller.screenshot(chatId, typeof args.appId === 'string' ? args.appId : undefined)),
102
+ },
103
+ ];
104
+ }
105
+ export async function handleSteerComputer(method, pathname, query, body, controller = sharedComputer) {
106
+ const chatId = chatIdFrom(query, body);
107
+ if (!validChatId(chatId))
108
+ return { status: 400, data: { detail: '缺少会话' } };
109
+ const record = readRecord(body);
110
+ const appId = typeof record.appId === 'string' ? record.appId : '';
111
+ try {
112
+ if (method === 'GET' && pathname === COMPUTER_ROUTE) {
113
+ return { status: 200, data: controller.view(chatId) };
114
+ }
115
+ if (method === 'POST' && pathname === `${COMPUTER_ROUTE}/allow`) {
116
+ return { status: 200, data: await controller.allow(chatId, appId) };
117
+ }
118
+ if (method === 'POST' && pathname === `${COMPUTER_ROUTE}/allow-frontmost`) {
119
+ return { status: 200, data: await controller.allowFrontmost(chatId) };
120
+ }
121
+ if (method === 'POST' && pathname === `${COMPUTER_ROUTE}/click`) {
122
+ return {
123
+ status: 200,
124
+ data: await controller.click(chatId, appId, numberArg(record.x), numberArg(record.y)),
125
+ };
126
+ }
127
+ if (method === 'POST' && pathname === `${COMPUTER_ROUTE}/type`) {
128
+ const text = typeof record.text === 'string' ? record.text : '';
129
+ return { status: 200, data: await controller.typeText(chatId, appId, text) };
130
+ }
131
+ if (method === 'POST' && pathname === `${COMPUTER_ROUTE}/screenshot`) {
132
+ return { status: 200, data: await controller.screenshot(chatId, appId || undefined) };
133
+ }
134
+ return { status: 404, data: { detail: '没有这个电脑操作' } };
135
+ }
136
+ catch (err) {
137
+ if (err instanceof ComputerActionError)
138
+ return { status: err.status, data: { detail: err.message } };
139
+ const message = err instanceof Error ? err.message : String(err);
140
+ return { status: 500, data: { detail: message || '电脑操作失败' } };
141
+ }
142
+ }
143
+ export function assembleSteerComputer(deps) {
144
+ deps.registerTools(createSteerComputerTools(sharedComputer));
145
+ }
146
+ /** 宿主启动时注册。重复调用安全。 */
147
+ export function registerSteerComputer() {
148
+ if (!getPackAssemblies().has('steer-computer')) {
149
+ registerPackAssembly('steer-computer', assembleSteerComputer);
150
+ }
151
+ if (matchPackBackendRoute('GET', COMPUTER_ROUTE))
152
+ return;
153
+ const handler = (pathname) => async (request) => handleSteerComputer('POST', pathname, request.query, request.body);
154
+ registerPackBackendRoutes('steer-computer', COMPUTER_ROUTE, [
155
+ {
156
+ method: 'GET',
157
+ path: COMPUTER_ROUTE,
158
+ handler: ({ query, body }) => handleSteerComputer('GET', COMPUTER_ROUTE, query, body),
159
+ },
160
+ {
161
+ method: 'POST',
162
+ path: `${COMPUTER_ROUTE}/allow`,
163
+ handler: handler(`${COMPUTER_ROUTE}/allow`),
164
+ },
165
+ {
166
+ method: 'POST',
167
+ path: `${COMPUTER_ROUTE}/allow-frontmost`,
168
+ handler: handler(`${COMPUTER_ROUTE}/allow-frontmost`),
169
+ },
170
+ {
171
+ method: 'POST',
172
+ path: `${COMPUTER_ROUTE}/click`,
173
+ handler: handler(`${COMPUTER_ROUTE}/click`),
174
+ },
175
+ {
176
+ method: 'POST',
177
+ path: `${COMPUTER_ROUTE}/type`,
178
+ handler: handler(`${COMPUTER_ROUTE}/type`),
179
+ },
180
+ {
181
+ method: 'POST',
182
+ path: `${COMPUTER_ROUTE}/screenshot`,
183
+ handler: handler(`${COMPUTER_ROUTE}/screenshot`),
184
+ },
185
+ ]);
186
+ }
@@ -0,0 +1,392 @@
1
+ /**
2
+ * Steer 的 PDF、表格和图片预览。只服务本产品:从当前会话的回合产物里
3
+ * 读出这一份文件交给右侧栏位。不进框架,其他产品不注册这条路由。
4
+ *
5
+ * PDF、工作簿与图片均通过原生二进制流端点(/raw)直传,不走 base64,
6
+ * 也不调用 LibreOffice / pdftoppm / swiftc。
7
+ */
8
+ import { readFile, realpath, stat } from 'node:fs/promises';
9
+ import path from 'node:path';
10
+ import { matchPackBackendRoute, registerPackBackendRoutes, } from '@steerable/agent-shell/local-backend/pack-backend-routes';
11
+ export const FILE_PREVIEW_ROUTE = '/api/v2/steer/file-preview';
12
+ export const FILE_PREVIEW_RAW_ROUTE = '/api/v2/steer/file-preview/raw';
13
+ const MAX_IMAGE_BYTES = 12 * 1024 * 1024;
14
+ const MAX_TABLE_BYTES = 1024 * 1024;
15
+ const MAX_WORKBOOK_BYTES = 16 * 1024 * 1024;
16
+ /**
17
+ * PDF 直出给 pdf.js,走 HTTP Range 分片:首页只拉 6~7 MiB,其余按滚动补。
18
+ * 实测一份 86.5 MiB、33 页的演示稿,首页 25 次分片共 6.33 MiB、92ms 出页,
19
+ * 所以上限按「整份都能打开」而不是「首屏能装下」来定。
20
+ */
21
+ const MAX_PDF_BYTES = 200 * 1024 * 1024;
22
+ const MAX_TABLE_ROWS = 200;
23
+ const MAX_TABLE_COLS = 40;
24
+ const IMAGE_MIME = {
25
+ '.png': 'image/png',
26
+ '.jpg': 'image/jpeg',
27
+ '.jpeg': 'image/jpeg',
28
+ '.webp': 'image/webp',
29
+ '.gif': 'image/gif',
30
+ };
31
+ const RAW_MIME = {
32
+ ...IMAGE_MIME,
33
+ '.pdf': 'application/pdf',
34
+ '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
35
+ '.xlsm': 'application/vnd.ms-excel.sheet.macroEnabled.12',
36
+ '.xls': 'application/vnd.ms-excel',
37
+ '.csv': 'text/csv; charset=utf-8',
38
+ '.tsv': 'text/tab-separated-values; charset=utf-8',
39
+ };
40
+ /** 绝对路径才预览。PPT、Word、Markdown 交给各自的栏位。 */
41
+ export function filePreviewKind(filePath) {
42
+ if (!filePath || filePath.includes('\0') || !path.isAbsolute(filePath))
43
+ return null;
44
+ const ext = path.extname(filePath).toLowerCase();
45
+ if (ext === '.pdf')
46
+ return 'pdf';
47
+ if (ext === '.xlsx' || ext === '.xls' || ext === '.xlsm' || ext === '.csv' || ext === '.tsv')
48
+ return 'sheet';
49
+ if (ext in IMAGE_MIME)
50
+ return 'image';
51
+ return null;
52
+ }
53
+ function workbookKind(filePath) {
54
+ const ext = path.extname(filePath).toLowerCase();
55
+ return ext === '.xlsx' || ext === '.xls' || ext === '.xlsm';
56
+ }
57
+ function tableDelimiter(filePath) {
58
+ const ext = path.extname(filePath).toLowerCase();
59
+ if (ext === '.csv')
60
+ return ',';
61
+ if (ext === '.tsv')
62
+ return '\t';
63
+ return null;
64
+ }
65
+ /** 把 CSV / TSV 拆成表头和数据行。引号里的分隔符和换行留在单元格里。 */
66
+ export function parseDelimitedTable(text, delimiter, limits = { maxRows: MAX_TABLE_ROWS, maxCols: MAX_TABLE_COLS }) {
67
+ const records = parseRecords(text.replace(/^\uFEFF/, ''), delimiter);
68
+ const header = records[0] ?? [];
69
+ const columns = header.slice(0, limits.maxCols);
70
+ const body = records.slice(1);
71
+ const truncated = body.length > limits.maxRows || header.length > limits.maxCols || body.some((row) => row.length > limits.maxCols);
72
+ const rows = body.slice(0, limits.maxRows).map((row) => {
73
+ const cells = row.slice(0, limits.maxCols);
74
+ while (cells.length < columns.length)
75
+ cells.push('');
76
+ return cells;
77
+ });
78
+ return { columns, rows, truncated };
79
+ }
80
+ function parseRecords(text, delimiter) {
81
+ const normalized = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
82
+ const rows = [];
83
+ let row = [];
84
+ let cell = '';
85
+ let quoted = false;
86
+ for (let index = 0; index < normalized.length; index += 1) {
87
+ const char = normalized[index];
88
+ if (quoted) {
89
+ if (char === '"') {
90
+ if (normalized[index + 1] === '"') {
91
+ cell += '"';
92
+ index += 1;
93
+ }
94
+ else {
95
+ quoted = false;
96
+ }
97
+ }
98
+ else {
99
+ cell += char ?? '';
100
+ }
101
+ continue;
102
+ }
103
+ if (char === '"' && cell === '') {
104
+ quoted = true;
105
+ continue;
106
+ }
107
+ if (char === delimiter) {
108
+ row.push(cell);
109
+ cell = '';
110
+ continue;
111
+ }
112
+ if (char === '\n') {
113
+ row.push(cell);
114
+ rows.push(row);
115
+ row = [];
116
+ cell = '';
117
+ continue;
118
+ }
119
+ cell += char ?? '';
120
+ }
121
+ if (cell.length > 0 || row.length > 0) {
122
+ row.push(cell);
123
+ rows.push(row);
124
+ }
125
+ return rows.filter((record) => !(record.length === 1 && record[0] === ''));
126
+ }
127
+ function turnFilePaths(raw) {
128
+ if (!raw)
129
+ return [];
130
+ let parsed;
131
+ try {
132
+ parsed = JSON.parse(raw);
133
+ }
134
+ catch {
135
+ return [];
136
+ }
137
+ if (!parsed || typeof parsed !== 'object')
138
+ return [];
139
+ const files = parsed.turnFiles;
140
+ if (!Array.isArray(files))
141
+ return [];
142
+ const found = [];
143
+ for (const item of files) {
144
+ if (!item || typeof item !== 'object')
145
+ continue;
146
+ const filePath = item.path;
147
+ if (typeof filePath === 'string' && path.isAbsolute(filePath))
148
+ found.push(path.resolve(filePath));
149
+ }
150
+ return found;
151
+ }
152
+ function listedPaths(messages) {
153
+ const seen = new Set();
154
+ const files = [];
155
+ for (const message of messages) {
156
+ for (const filePath of turnFilePaths(message.messageMetadata)) {
157
+ if (seen.has(filePath))
158
+ continue;
159
+ seen.add(filePath);
160
+ files.push(filePath);
161
+ }
162
+ }
163
+ return files;
164
+ }
165
+ function isListed(filePath, realPath, messages) {
166
+ const wanted = new Set([path.resolve(filePath), path.resolve(realPath)]);
167
+ return listedPaths(messages).some((listed) => wanted.has(listed));
168
+ }
169
+ function validChatId(chatId) {
170
+ return /^[0-9a-zA-Z_-]{1,200}$/.test(chatId);
171
+ }
172
+ function detail(status, message) {
173
+ return { status, data: { detail: message } };
174
+ }
175
+ function rawPreviewPath(chatId, realPath) {
176
+ const params = new URLSearchParams({ chatId, path: realPath });
177
+ return `${FILE_PREVIEW_RAW_ROUTE}?${params.toString()}`;
178
+ }
179
+ async function newestPreviewable(messages) {
180
+ for (const filePath of listedPaths(messages)) {
181
+ if (!filePreviewKind(filePath))
182
+ continue;
183
+ try {
184
+ const fileStat = await stat(filePath);
185
+ if (fileStat.isFile())
186
+ return filePath;
187
+ }
188
+ catch {
189
+ continue;
190
+ }
191
+ }
192
+ return null;
193
+ }
194
+ async function resolvePreviewFile(input) {
195
+ const chatId = input.chatId.trim();
196
+ if (!validChatId(chatId))
197
+ return { ok: false, status: 400, message: 'chatId is required' };
198
+ const requested = input.filePath?.trim() || (input.requireExplicitPath ? '' : await newestPreviewable(input.messages));
199
+ if (!requested) {
200
+ return input.requireExplicitPath
201
+ ? { ok: false, status: 400, message: '需要文件的绝对路径' }
202
+ : { ok: true, empty: true };
203
+ }
204
+ if (!path.isAbsolute(requested) || requested.includes('\0')) {
205
+ return { ok: false, status: 400, message: '需要文件的绝对路径' };
206
+ }
207
+ const kind = filePreviewKind(requested);
208
+ if (!kind)
209
+ return { ok: false, status: 400, message: '这个文件不能在这里预览' };
210
+ let realPath;
211
+ let fileStat;
212
+ try {
213
+ realPath = await realpath(requested);
214
+ fileStat = await stat(realPath);
215
+ }
216
+ catch {
217
+ return { ok: false, status: 404, message: '找不到这个文件' };
218
+ }
219
+ if (!fileStat.isFile())
220
+ return { ok: false, status: 404, message: '找不到这个文件' };
221
+ if (!isListed(requested, realPath, input.messages)) {
222
+ return { ok: false, status: 404, message: '这个文件不属于当前对话' };
223
+ }
224
+ return {
225
+ ok: true,
226
+ chatId,
227
+ realPath,
228
+ fileName: path.basename(realPath),
229
+ kind,
230
+ size: fileStat.size,
231
+ };
232
+ }
233
+ function sizeLimitFor(realPath, kind) {
234
+ if (kind === 'image')
235
+ return MAX_IMAGE_BYTES;
236
+ if (kind === 'pdf')
237
+ return MAX_PDF_BYTES;
238
+ if (workbookKind(realPath))
239
+ return MAX_WORKBOOK_BYTES;
240
+ return MAX_TABLE_BYTES;
241
+ }
242
+ export async function loadFilePreview(input) {
243
+ const resolved = await resolvePreviewFile({
244
+ chatId: input.chatId,
245
+ filePath: input.filePath,
246
+ messages: input.messages,
247
+ });
248
+ if (!resolved.ok)
249
+ return detail(resolved.status, resolved.message);
250
+ if ('empty' in resolved)
251
+ return { status: 200, data: { file: null } };
252
+ const { chatId, realPath, fileName, kind, size } = resolved;
253
+ if (size > sizeLimitFor(realPath, kind)) {
254
+ return detail(400, '文件太大,无法预览');
255
+ }
256
+ const ext = path.extname(realPath).toLowerCase();
257
+ if (kind === 'image') {
258
+ const mime = IMAGE_MIME[ext] ?? 'application/octet-stream';
259
+ return {
260
+ status: 200,
261
+ data: {
262
+ file: {
263
+ kind: 'image',
264
+ fileName,
265
+ path: realPath,
266
+ mime,
267
+ size,
268
+ rawPath: rawPreviewPath(chatId, realPath),
269
+ },
270
+ },
271
+ };
272
+ }
273
+ if (kind === 'pdf') {
274
+ return {
275
+ status: 200,
276
+ data: {
277
+ file: {
278
+ kind: 'pdf',
279
+ fileName,
280
+ path: realPath,
281
+ mime: 'application/pdf',
282
+ size,
283
+ rawPath: rawPreviewPath(chatId, realPath),
284
+ },
285
+ },
286
+ };
287
+ }
288
+ const delimiter = tableDelimiter(realPath);
289
+ if (delimiter) {
290
+ const text = await readFile(realPath, 'utf8');
291
+ const table = parseDelimitedTable(text, delimiter);
292
+ return {
293
+ status: 200,
294
+ data: { file: { kind: 'sheet', fileName, path: realPath, ...table } },
295
+ };
296
+ }
297
+ if (!workbookKind(realPath)) {
298
+ return detail(400, '这个文件不能在这里预览');
299
+ }
300
+ return {
301
+ status: 200,
302
+ data: {
303
+ file: {
304
+ kind: 'workbook',
305
+ fileName,
306
+ path: realPath,
307
+ ext,
308
+ size,
309
+ rawPath: rawPreviewPath(chatId, realPath),
310
+ },
311
+ },
312
+ };
313
+ }
314
+ export async function loadFilePreviewRaw(input) {
315
+ const resolved = await resolvePreviewFile({
316
+ chatId: input.chatId,
317
+ filePath: input.filePath,
318
+ messages: input.messages,
319
+ requireExplicitPath: true,
320
+ });
321
+ if (!resolved.ok)
322
+ return detail(resolved.status, resolved.message);
323
+ if ('empty' in resolved)
324
+ return detail(400, '需要文件的绝对路径');
325
+ const { realPath, fileName, kind, size } = resolved;
326
+ if (size > sizeLimitFor(realPath, kind)) {
327
+ return detail(400, '文件太大,无法预览');
328
+ }
329
+ const ext = path.extname(realPath).toLowerCase();
330
+ const contentType = RAW_MIME[ext] ?? 'application/octet-stream';
331
+ return {
332
+ status: 200,
333
+ kind: 'file',
334
+ filePath: realPath,
335
+ contentType,
336
+ fileName,
337
+ };
338
+ }
339
+ export async function handleSteerFilePreview(query, listMessages) {
340
+ const chatId = query.get('chatId') ?? '';
341
+ try {
342
+ const messages = await listMessages(chatId);
343
+ return await loadFilePreview({
344
+ chatId,
345
+ filePath: query.get('path'),
346
+ messages,
347
+ });
348
+ }
349
+ catch (err) {
350
+ const message = err instanceof Error ? err.message : String(err);
351
+ return detail(500, message || '无法生成预览');
352
+ }
353
+ }
354
+ export async function handleSteerFilePreviewRaw(query, listMessages) {
355
+ const chatId = query.get('chatId') ?? '';
356
+ try {
357
+ const messages = await listMessages(chatId);
358
+ return await loadFilePreviewRaw({
359
+ chatId,
360
+ filePath: query.get('path'),
361
+ messages,
362
+ });
363
+ }
364
+ catch (err) {
365
+ const message = err instanceof Error ? err.message : String(err);
366
+ return detail(500, message || '无法读取文件');
367
+ }
368
+ }
369
+ /** 宿主启动时注册。存储要等 initializeStorage 之后才能用,所以放在请求里再取。 */
370
+ export function registerSteerFilePreview() {
371
+ if (matchPackBackendRoute('GET', FILE_PREVIEW_ROUTE))
372
+ return;
373
+ const listMessages = async (chatId) => {
374
+ const { getScopedStore, LOCAL_SCOPE } = await import('@steerable/agent-shell/storage/driver');
375
+ const messages = await getScopedStore(LOCAL_SCOPE).listMessages(chatId, 200);
376
+ return messages.map((message) => ({
377
+ messageMetadata: typeof message.messageMetadata === 'string' ? message.messageMetadata : null,
378
+ }));
379
+ };
380
+ registerPackBackendRoutes('steer-files', FILE_PREVIEW_ROUTE, [
381
+ {
382
+ method: 'GET',
383
+ path: FILE_PREVIEW_ROUTE,
384
+ handler: ({ query }) => handleSteerFilePreview(query, listMessages),
385
+ },
386
+ {
387
+ method: 'GET',
388
+ path: FILE_PREVIEW_RAW_ROUTE,
389
+ handler: ({ query }) => handleSteerFilePreviewRaw(query, listMessages),
390
+ },
391
+ ]);
392
+ }