@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,110 @@
1
+ /**
2
+ * 打包后的 CPython 不在 Node 的默认搜索路径上。
3
+ *
4
+ * Tauri 宿主会设置 STEERABLE_SIDECAR_PYTHON。Windows 安装包冒烟直接启动
5
+ * node-host,没有这个变量,sidecar 就会报 portable runtime not found。
6
+ * Linux AppImage 里 linuxdeploy 把 libpython 放进 usr/lib,CPython 据此把
7
+ * prefix 算成 usr/,stdlib 的 encodings 就找不到。bin/python3 的 PYTHONHOME
8
+ * 必须是 python/(bin 的父目录),不能是被搬走的 libpython 所在目录。
9
+ *
10
+ * 但 PYTHONHOME 是全局 env:容器/桌面里解释器本来能自己定位 stdlib,凭空
11
+ * 导出会泄漏给所有子进程,让 local_run_snippet 用 PATH 上另一个 python3
12
+ * (如容器系统 3.11)跑代码时崩在 "No module named 'encodings'"。所以只在
13
+ * 解释器确实起不来(AppImage 布局)时才钉 prefix。
14
+ */
15
+ import { execFileSync } from 'node:child_process';
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import { fileURLToPath, pathToFileURL } from 'node:url';
19
+ function platformTag() {
20
+ if (process.platform === 'darwin') {
21
+ return process.arch === 'arm64' ? 'darwin-arm64' : 'darwin-x64';
22
+ }
23
+ if (process.platform === 'win32')
24
+ return 'win32-x64';
25
+ if (process.platform === 'linux')
26
+ return 'linux-x64';
27
+ return 'unsupported';
28
+ }
29
+ function pythonCandidates(runtimeRoot) {
30
+ const exe = process.platform === 'win32' ? 'python.exe' : 'python3';
31
+ const base = path.join(runtimeRoot, 'python-runtime', platformTag());
32
+ return [
33
+ path.join(base, 'python', exe),
34
+ path.join(base, 'python', 'bin', exe),
35
+ path.join(base, exe),
36
+ path.join(base, 'bin', exe),
37
+ ];
38
+ }
39
+ /**
40
+ * 从产品模块向上找 python-runtime。
41
+ * 打包平面里它与应用根并列;仓库平面里 prepare-sidecar 写在 resources/ 下。
42
+ */
43
+ export function findBundledPython(moduleUrl) {
44
+ const here = path.dirname(fileURLToPath(moduleUrl));
45
+ for (let up = 0; up <= 8; up++) {
46
+ const root = path.resolve(here, ...Array(up).fill('..'));
47
+ const hit = [root, path.join(root, 'resources')]
48
+ .flatMap((runtimeRoot) => pythonCandidates(runtimeRoot))
49
+ .find((candidate) => fs.existsSync(candidate));
50
+ if (hit)
51
+ return hit;
52
+ }
53
+ return null;
54
+ }
55
+ /**
56
+ * 在 sidecar 启动前补上解释器路径和 posix prefix。
57
+ * 已由宿主设置的 STEERABLE_SIDECAR_PYTHON 保持不动。
58
+ */
59
+ export function pinBundledPython(moduleUrl) {
60
+ const fromEnv = process.env.STEERABLE_SIDECAR_PYTHON;
61
+ const python = fromEnv && fs.existsSync(fromEnv) ? fromEnv : findBundledPython(moduleUrl);
62
+ if (!python)
63
+ return;
64
+ if (!process.env.STEERABLE_SIDECAR_PYTHON) {
65
+ process.env.STEERABLE_SIDECAR_PYTHON = python;
66
+ }
67
+ const parent = path.dirname(python);
68
+ const prefix = path.dirname(parent);
69
+ // linuxdeploy 把 libpython 放进 AppImage 的 usr/lib,运行时还会把
70
+ // PYTHONHOME 设成 usr/。bin/python3 的 prefix 必须改回 python/。
71
+ // uv/venv 的 bin/python3 旁边有 pyvenv.cfg,prefix 必须留给解释器自己解析。
72
+ if (path.basename(parent) === 'bin' && !fs.existsSync(path.join(prefix, 'pyvenv.cfg'))) {
73
+ // 标准布局里解释器自己能找到 stdlib,不要凭空导出 PYTHONHOME(会泄漏给
74
+ // snippet 等子进程)。只有解释器确实起不来时才钉 prefix。
75
+ if (interpreterResolvesStdlib(python) !== true) {
76
+ process.env.PYTHONHOME = prefix;
77
+ }
78
+ }
79
+ if (process.platform === 'win32') {
80
+ const dllDir = path.join(parent, 'DLLs');
81
+ const lead = [parent, dllDir].filter((dir) => fs.existsSync(dir));
82
+ if (lead.length > 0) {
83
+ process.env.PATH = [...lead, process.env.PATH].filter(Boolean).join(';');
84
+ }
85
+ }
86
+ }
87
+ export function bundledPythonModuleUrl(filePath) {
88
+ return pathToFileURL(filePath).href;
89
+ }
90
+ /**
91
+ * 探测解释器能否在当前环境下自己找到 stdlib。
92
+ *
93
+ * true/false;无法执行(文件缺失/不可执行/超时)时返回 null,调用方按
94
+ * “不确定”处理,保持旧的保守行为(设 PYTHONHOME)。
95
+ */
96
+ function interpreterResolvesStdlib(python) {
97
+ try {
98
+ execFileSync(python, ['-c', 'import encodings'], {
99
+ stdio: 'ignore',
100
+ timeout: 5000,
101
+ });
102
+ return true;
103
+ }
104
+ catch (error) {
105
+ const code = error?.code;
106
+ if (code === 'ENOENT' || code === 'EACCES' || code === 'EPERM')
107
+ return null;
108
+ return false;
109
+ }
110
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * 产品组装根加载应用层语言包。
3
+ *
4
+ * 源码平面读仓库 `locales/shell/zh.json` 和 `products/<id>/locales/zh.json`。
5
+ * 打包平面读 copy-skills 拷到本模块旁的 `locales/shell.zh.json` 与 `locales/zh.json`。
6
+ */
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { configureI18n, registerLocale } from '@steerable/agent-shell/i18n';
10
+ function readCatalog(file) {
11
+ if (!fs.existsSync(file))
12
+ return {};
13
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
14
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
15
+ return {};
16
+ const messages = {};
17
+ for (const [key, value] of Object.entries(parsed)) {
18
+ if (typeof value === 'string')
19
+ messages[key] = value;
20
+ }
21
+ return messages;
22
+ }
23
+ export function loadZhCatalog(moduleDir) {
24
+ const shell = readCatalog(path.join(moduleDir, 'locales', 'shell.zh.json'));
25
+ const shellFromRepo = readCatalog(path.resolve(moduleDir, '..', '..', 'locales', 'shell', 'zh.json'));
26
+ const overlay = readCatalog(path.join(moduleDir, 'locales', 'zh.json'));
27
+ return { ...(Object.keys(shell).length > 0 ? shell : shellFromRepo), ...overlay };
28
+ }
29
+ export function applyProductI18n(moduleDir, i18n) {
30
+ const locales = i18n?.locales && i18n.locales.length > 0 ? i18n.locales : ['en'];
31
+ if (locales.includes('zh'))
32
+ registerLocale('zh', loadZhCatalog(moduleDir));
33
+ configureI18n({
34
+ locales,
35
+ defaultLocale: i18n?.defaultLocale ?? locales[0] ?? 'en',
36
+ systemLocale: process.env.LANG ?? process.env.LC_ALL ?? null,
37
+ });
38
+ }
@@ -0,0 +1,13 @@
1
+ {
2
+ "$comment": "产品组装清单:flavor → 激活的场景包 id 列表。应用层数据(3.2 起住在 products/,不进框架 shell);构建脚本(copy-skills.mjs 等)与产品组装根共用的唯一真源。",
3
+ "flavors": {
4
+ "steer": [],
5
+ "arena": [],
6
+ "ciflog": [
7
+ "cflog"
8
+ ],
9
+ "etown": [
10
+ "etown"
11
+ ]
12
+ }
13
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Product bin copy of the command-line Node check.
3
+ *
4
+ * The product compile root cannot import the steerable module. `REQUIRED_NODE`
5
+ * and `nodeDoctorLine` must stay equal to `@steerable/agent-cli`
6
+ * `src/node-version.ts`. The bin imports this file and nothing else from the product.
7
+ *
8
+ * This is the floor for every product command. The terminal interface has its
9
+ * own higher floor for the renderer, and `steerable-cli tui` checks that one
10
+ * itself, so gating the whole product on 26.4 would deny `run` and `doctor` to
11
+ * users whose Node is new enough for them.
12
+ */
13
+ import { existsSync, readFileSync } from 'node:fs';
14
+ import path from 'node:path';
15
+ import { Writable } from 'node:stream';
16
+ import { pathToFileURL } from 'node:url';
17
+ export const REQUIRED_NODE = '22.19.0';
18
+ /**
19
+ * Floor for the terminal interface, set by the renderer's `engines`.
20
+ * `@steerable/agent-cli` checks it in `tui` itself; this file only reports it
21
+ * in `doctor`, so the two copies stay identical.
22
+ */
23
+ export const REQUIRED_NODE_TUI = '26.4.0';
24
+ /** @param current Installed version, with or without a leading `v`. @param required `major.minor.patch`. @returns Whether `current` is at least `required`. */
25
+ export function satisfies(current, required) {
26
+ const left = readVersion(current);
27
+ const right = readVersion(required);
28
+ if (!left || !right)
29
+ return false;
30
+ for (let index = 0; index < 3; index += 1) {
31
+ if (left[index] !== right[index])
32
+ return left[index] > right[index];
33
+ }
34
+ return true;
35
+ }
36
+ /** @param current Installed version. @param stderr Where the failure text is written. @param product Command name, such as `steer`. @returns `0` when the version is new enough, otherwise `1`. */
37
+ export function ensureSupportedNode(current, stderr, product) {
38
+ if (satisfies(current, REQUIRED_NODE))
39
+ return 0;
40
+ const shown = current.replace(/^v/, '');
41
+ stderr.write(`${product} 需要 Node.js ${REQUIRED_NODE} 或更高版本,当前为 ${shown}。\n升级方法:https://nodejs.org/\n`);
42
+ return 1;
43
+ }
44
+ /** @param current Installed version. @returns One doctor row, including whether it meets {@link REQUIRED_NODE}. */
45
+ /**
46
+ * @param current Installed version.
47
+ * @returns Whether the terminal interface can run on it.
48
+ */
49
+ export function supportsTui(current) {
50
+ return satisfies(current, REQUIRED_NODE_TUI);
51
+ }
52
+ export function nodeDoctorLine(current) {
53
+ const shown = current.replace(/^v/, '');
54
+ const mark = satisfies(current, REQUIRED_NODE) ? '✓' : '✗';
55
+ const tui = supportsTui(current) ? '' : `;tui 需要 ≥ ${REQUIRED_NODE_TUI}`;
56
+ return `Node.js: ${shown}(需要 ≥ ${REQUIRED_NODE}${tui}) ${mark}\n`;
57
+ }
58
+ export async function runProductCli(createCli, options = {}) {
59
+ const argv = process.argv.slice(2);
60
+ if (options.version &&
61
+ argv.length > 0 &&
62
+ argv.every((arg) => arg === '--version' || arg === '-v' || arg === '--verbose') &&
63
+ argv.some((arg) => arg === '--version' || arg === '-v')) {
64
+ process.stdout.write(`${options.version}\n`);
65
+ return 0;
66
+ }
67
+ const doctor = process.argv[2] === 'doctor'
68
+ && !process.argv.includes('--help')
69
+ && !process.argv.includes('-h');
70
+ if (!doctor)
71
+ return createCli({ installSignals: true, ...options });
72
+ const chunks = [];
73
+ const stdout = new Writable({
74
+ write(chunk, _encoding, callback) {
75
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
76
+ callback();
77
+ },
78
+ });
79
+ const code = await createCli({ installSignals: true, ...options, stdout });
80
+ let text = Buffer.concat(chunks).toString('utf8');
81
+ if (!text.includes('Node.js:'))
82
+ text = nodeDoctorLine(process.versions.node) + text;
83
+ process.stdout.write(text);
84
+ return code;
85
+ }
86
+ const AGENT_CLI_DIST = 'steerable/packages/agent-cli/ts/dist/index.js';
87
+ /**
88
+ * Local checkout of `@steerable/agent-cli`, when this repo sits next to it.
89
+ * Source files live in `products/<flavor>/`; `tsc` emits them under `dist/`.
90
+ *
91
+ * @param here Directory of the product `cli-main` module.
92
+ * @returns A `file:` URL of the checkout build, or the package name.
93
+ */
94
+ export function agentCliSpecifier(here) {
95
+ const candidates = [
96
+ path.resolve(here, '../../..', AGENT_CLI_DIST),
97
+ path.resolve(here, '../../../..', AGENT_CLI_DIST),
98
+ ];
99
+ const found = candidates.find((candidate) => existsSync(candidate));
100
+ return found ? pathToFileURL(found).href : '@steerable/agent-cli';
101
+ }
102
+ /**
103
+ * Resolves the product release version from the nearest enclosing package.json
104
+ * (the `@steerable/steer` package root or repository root), skipping `0.0.0`
105
+ * workspace placeholders.
106
+ */
107
+ export function readProductVersion(here) {
108
+ for (const rel of ['../..', '../../..', '../../../..']) {
109
+ const candidate = path.resolve(here, rel, 'package.json');
110
+ if (!existsSync(candidate))
111
+ continue;
112
+ try {
113
+ const parsed = JSON.parse(readFileSync(candidate, 'utf8'));
114
+ if (typeof parsed.version === 'string' &&
115
+ /^\d+\.\d+\.\d+/.test(parsed.version) &&
116
+ parsed.version !== '0.0.0') {
117
+ return parsed.version;
118
+ }
119
+ }
120
+ catch {
121
+ continue;
122
+ }
123
+ }
124
+ return undefined;
125
+ }
126
+ function readVersion(value) {
127
+ const match = /v?(\d+)\.(\d+)\.(\d+)/.exec(value.trim());
128
+ if (!match)
129
+ return null;
130
+ return [Number(match[1]), Number(match[2]), Number(match[3])];
131
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Steer 产品组装根:无场景包——纯 shell 产品。
3
+ * Markdown、文件预览、本轮变更、浏览器、电脑操作、权限申请和按需读技能是本产品自己的路由和工具。
4
+ * PPT / Word 文档预览来自私有包 @deeppath/doc-preview,作为右侧标签。
5
+ *
6
+ * 本模块必须是产品入口(./main.ts / ./server.ts)的第一个 import:
7
+ * `LocalStore` 单例在 `storage/index.js` 模块求值时构造并跑迁移,
8
+ * 包迁移必须先于它注册。ESM 按 import 顺序深度优先求值。
9
+ *
10
+ * 与 products/manifest.json 的 flavors 映射一致,
11
+ * tests/packs-manifest.test.ts 守门。
12
+ */
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import { fileURLToPath } from 'node:url';
16
+ import { setProductBrand } from '@steerable/agent-shell/brand';
17
+ import { registerPackAssembly } from '@steerable/agent-shell/host/pack-assembly';
18
+ import { setProductConfig } from '@steerable/agent-shell/product-config';
19
+ import { registerPackMigrations } from '@steerable/agent-shell/storage/pack-migrations';
20
+ import { applyProductI18n } from '../load-locale.js';
21
+ import { setAppRootDir } from '@steerable/agent-shell/runtime';
22
+ import { pinBundledPython } from '../bundled-python.js';
23
+ import { assembleDocumentPreview, DOCUMENT_PREVIEW_MIGRATIONS, } from '../../packages/doc-preview/src/index.js';
24
+ import { migrateLegacyAroliData } from './migrate-legacy-data.js';
25
+ import { registerSteerBrowser } from './browser.js';
26
+ import { registerSteerComputer } from './computer.js';
27
+ import { registerSteerFilePreview } from './file-preview.js';
28
+ import { registerSteerMarkdownPreview } from './markdown-preview.js';
29
+ import { registerSteerPermissions } from './permissions.js';
30
+ import { registerSteerSkillRead } from './skill-read.js';
31
+ import { registerSteerTurnChanges } from './turn-changes.js';
32
+ /** 读同目录的 product.json(src 与 dist 同相对位置;构建期由 copy-skills.mjs 拷入 dist)。 */
33
+ function readProductJson() {
34
+ const here = path.dirname(fileURLToPath(import.meta.url));
35
+ return JSON.parse(fs.readFileSync(path.join(here, 'product.json'), 'utf8'));
36
+ }
37
+ const product = readProductJson();
38
+ registerPackMigrations('doc-preview', DOCUMENT_PREVIEW_MIGRATIONS);
39
+ registerPackAssembly('doc-preview', assembleDocumentPreview);
40
+ // Steer 品牌由产品注入(3.1 起 shell 默认品牌是中性占位)。
41
+ if (product.brand)
42
+ setProductBrand(product.brand);
43
+ const productConfig = {
44
+ insightsApiBase: product.insightsApiBase,
45
+ links: product.links,
46
+ dataDirName: product.dataDirName,
47
+ dbFileName: product.dbFileName,
48
+ hostTools: product.hostTools,
49
+ approval: product.approval,
50
+ egressApproval: product.egressApproval,
51
+ chatModes: product.chatModes,
52
+ settings: product.settings,
53
+ portable: product.portable === true,
54
+ builtinAgents: product.builtinAgents,
55
+ builtinSkills: product.builtinSkills,
56
+ builtinMcp: product.builtinMcp,
57
+ orchestration: product.orchestration,
58
+ i18n: product.i18n,
59
+ };
60
+ setProductConfig(productConfig);
61
+ migrateLegacyAroliData();
62
+ applyProductI18n(path.dirname(fileURLToPath(import.meta.url)), product.i18n);
63
+ /**
64
+ * 3.2 上提后 shell 是预编译依赖:应用根与包技能根由产品组装根注入。
65
+ * - appRoot:向上找含 products/manifest.json 的目录(source 平面 up2;
66
+ * 产品 dist 平面 up5)。
67
+ * - 无 pack-skills:Steer 没有场景包,不挂包技能根。copy-skills
68
+ * --all 把技能按 flavor 分栏,但这里仍不挂,避免再吃到他包身份。
69
+ */
70
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
71
+ function probeAppRoot() {
72
+ // 取最外层匹配:dev/dist 平面里 <dist>/products/manifest.json 与仓库根的
73
+ // 都命中时,仓库根才是真应用根(技能 @app/ 与 engine 制品定位等);
74
+ // 打包平面只有 app-dist 一层命中(更外层是 .app/Contents/Resources 等,
75
+ // 不含 manifest),自然落对。
76
+ let found = null;
77
+ for (let up = 2; up <= 6; up++) {
78
+ const segs = Array(up).fill('..');
79
+ const candidate = path.resolve(HERE, ...segs);
80
+ if (fs.existsSync(path.join(candidate, 'products', 'manifest.json')))
81
+ found = candidate;
82
+ }
83
+ return found ?? path.resolve(HERE, '..', '..');
84
+ }
85
+ setAppRootDir(probeAppRoot());
86
+ pinBundledPython(import.meta.url);
87
+ registerSteerMarkdownPreview();
88
+ registerSteerFilePreview();
89
+ registerSteerTurnChanges();
90
+ registerSteerBrowser();
91
+ registerSteerComputer();
92
+ registerSteerPermissions();
93
+ registerSteerSkillRead();
@@ -0,0 +1,230 @@
1
+ /**
2
+ * Steer browser executable detection, CDP loopback endpoint validation, and
3
+ * durable settings storage (`<user-data>/steer-browser-settings.json`).
4
+ */
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { getUserDataDir } from '@steerable/agent-shell/runtime';
8
+ export const BROWSER_EXECUTABLE_IDS = [
9
+ 'auto',
10
+ 'chrome',
11
+ 'msedge',
12
+ 'brave',
13
+ 'arc',
14
+ 'chromium',
15
+ 'custom',
16
+ ];
17
+ export const DEFAULT_CDP_ENDPOINT = 'http://127.0.0.1:9222';
18
+ export const DEFAULT_STEER_BROWSER_SETTINGS = {
19
+ browser: 'auto',
20
+ customExecutablePath: '',
21
+ sessionMode: 'isolated',
22
+ cdpEndpoint: DEFAULT_CDP_ENDPOINT,
23
+ allowPrivateNetwork: false,
24
+ };
25
+ const BROWSER_ID_SET = new Set(BROWSER_EXECUTABLE_IDS);
26
+ const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1', '[::1]']);
27
+ function candidatePathsForPlatform(platform, env) {
28
+ if (platform === 'darwin') {
29
+ const homeApps = env.HOME ? path.join(env.HOME, 'Applications') : '';
30
+ const appPaths = (appBundle, binName) => [
31
+ `/Applications/${appBundle}/Contents/MacOS/${binName}`,
32
+ homeApps ? path.join(homeApps, `${appBundle}/Contents/MacOS/${binName}`) : '',
33
+ ].filter(Boolean);
34
+ return {
35
+ chrome: {
36
+ label: 'Google Chrome',
37
+ paths: appPaths('Google Chrome.app', 'Google Chrome'),
38
+ },
39
+ msedge: {
40
+ label: 'Microsoft Edge',
41
+ paths: appPaths('Microsoft Edge.app', 'Microsoft Edge'),
42
+ },
43
+ brave: {
44
+ label: 'Brave Browser',
45
+ paths: appPaths('Brave Browser.app', 'Brave Browser'),
46
+ },
47
+ arc: {
48
+ label: 'Arc',
49
+ paths: appPaths('Arc.app', 'Arc'),
50
+ },
51
+ chromium: {
52
+ label: 'Chromium',
53
+ paths: appPaths('Chromium.app', 'Chromium'),
54
+ },
55
+ };
56
+ }
57
+ if (platform === 'win32') {
58
+ const roots = [
59
+ env.PROGRAMFILES,
60
+ env['PROGRAMFILES(X86)'],
61
+ env.LOCALAPPDATA,
62
+ ].filter((root) => Boolean(root));
63
+ const winPaths = (rel) => roots.map((root) => path.win32.join(root, rel));
64
+ return {
65
+ chrome: {
66
+ label: 'Google Chrome',
67
+ paths: winPaths('Google\\Chrome\\Application\\chrome.exe'),
68
+ },
69
+ msedge: {
70
+ label: 'Microsoft Edge',
71
+ paths: winPaths('Microsoft\\Edge\\Application\\msedge.exe'),
72
+ },
73
+ brave: {
74
+ label: 'Brave Browser',
75
+ paths: winPaths('BraveSoftware\\Brave-Browser\\Application\\brave.exe'),
76
+ },
77
+ arc: {
78
+ label: 'Arc',
79
+ paths: env.LOCALAPPDATA
80
+ ? [path.win32.join(env.LOCALAPPDATA, 'Packages\\TheBrowserCompany.Arc_ttt1ap7aakyb4\\LocalCache\\Local\\Arc\\Arc.exe')]
81
+ : [],
82
+ },
83
+ chromium: {
84
+ label: 'Chromium',
85
+ paths: winPaths('Chromium\\Application\\chrome.exe'),
86
+ },
87
+ };
88
+ }
89
+ return {
90
+ chrome: {
91
+ label: 'Google Chrome',
92
+ paths: ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable'],
93
+ },
94
+ msedge: {
95
+ label: 'Microsoft Edge',
96
+ paths: ['/usr/bin/microsoft-edge', '/usr/bin/microsoft-edge-stable'],
97
+ },
98
+ brave: {
99
+ label: 'Brave Browser',
100
+ paths: ['/usr/bin/brave-browser', '/usr/bin/brave'],
101
+ },
102
+ arc: {
103
+ label: 'Arc',
104
+ paths: [],
105
+ },
106
+ chromium: {
107
+ label: 'Chromium',
108
+ paths: ['/usr/bin/chromium', '/usr/bin/chromium-browser', '/snap/bin/chromium'],
109
+ },
110
+ };
111
+ }
112
+ export function detectInstalledBrowsers(options = {}) {
113
+ const platform = options.platform ?? process.platform;
114
+ const env = options.env ?? process.env;
115
+ const exists = options.existsSync ?? fs.existsSync;
116
+ const catalog = candidatePathsForPlatform(platform, env);
117
+ const order = [
118
+ 'chrome',
119
+ 'msedge',
120
+ 'brave',
121
+ 'arc',
122
+ 'chromium',
123
+ ];
124
+ return order.map((id) => {
125
+ const entry = catalog[id];
126
+ const found = entry.paths.find((candidate) => exists(candidate)) ?? null;
127
+ return {
128
+ id,
129
+ label: entry.label,
130
+ executablePath: found,
131
+ installed: found !== null,
132
+ };
133
+ });
134
+ }
135
+ export function validateCdpLoopbackEndpoint(rawEndpoint) {
136
+ const trimmed = rawEndpoint.trim() || DEFAULT_CDP_ENDPOINT;
137
+ const withScheme = /^\d+$/.test(trimmed)
138
+ ? `http://127.0.0.1:${trimmed}`
139
+ : /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)
140
+ ? trimmed
141
+ : `http://${trimmed}`;
142
+ let parsed;
143
+ try {
144
+ parsed = new URL(withScheme);
145
+ }
146
+ catch {
147
+ throw new Error('Enter a valid local CDP endpoint such as http://127.0.0.1:9222.');
148
+ }
149
+ if (!['http:', 'https:', 'ws:', 'wss:'].includes(parsed.protocol)) {
150
+ throw new Error('CDP endpoint must use http, https, ws, or wss.');
151
+ }
152
+ if (parsed.username || parsed.password) {
153
+ throw new Error('CDP endpoint must not contain embedded credentials.');
154
+ }
155
+ const host = parsed.hostname.toLowerCase();
156
+ if (!LOOPBACK_HOSTS.has(host)) {
157
+ throw new Error('CDP attach only connects to this computer (127.0.0.1, localhost, or ::1).');
158
+ }
159
+ const port = parsed.port
160
+ ? Number(parsed.port)
161
+ : parsed.protocol === 'https:' || parsed.protocol === 'wss:'
162
+ ? 443
163
+ : 80;
164
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
165
+ throw new Error('CDP endpoint port must be between 1 and 65535.');
166
+ }
167
+ return {
168
+ normalizedUrl: parsed.toString().replace(/\/$/, ''),
169
+ port,
170
+ };
171
+ }
172
+ export function normalizeSteerBrowserSettings(raw) {
173
+ const obj = raw && typeof raw === 'object' && !Array.isArray(raw)
174
+ ? raw
175
+ : {};
176
+ const browser = typeof obj.browser === 'string' && BROWSER_ID_SET.has(obj.browser)
177
+ ? obj.browser
178
+ : 'auto';
179
+ const customExecutablePath = typeof obj.customExecutablePath === 'string' ? obj.customExecutablePath.trim() : '';
180
+ const sessionMode = obj.sessionMode === 'attach' ? 'attach' : 'isolated';
181
+ const rawEndpoint = typeof obj.cdpEndpoint === 'string' && obj.cdpEndpoint.trim()
182
+ ? obj.cdpEndpoint.trim()
183
+ : DEFAULT_CDP_ENDPOINT;
184
+ const allowPrivateNetwork = obj.allowPrivateNetwork === true;
185
+ return {
186
+ browser,
187
+ customExecutablePath,
188
+ sessionMode,
189
+ cdpEndpoint: rawEndpoint,
190
+ allowPrivateNetwork,
191
+ };
192
+ }
193
+ function settingsFilePath(userDataDir = getUserDataDir()) {
194
+ return path.join(userDataDir, 'steer-browser-settings.json');
195
+ }
196
+ function legacySettingsFilePath(userDataDir = getUserDataDir()) {
197
+ return path.join(userDataDir, 'aroli-browser-settings.json');
198
+ }
199
+ export function readSteerBrowserSettings(userDataDir) {
200
+ const dir = userDataDir ?? getUserDataDir();
201
+ const file = settingsFilePath(dir);
202
+ const candidate = fs.existsSync(file) ? file : legacySettingsFilePath(dir);
203
+ try {
204
+ if (!fs.existsSync(candidate))
205
+ return { ...DEFAULT_STEER_BROWSER_SETTINGS };
206
+ const parsed = JSON.parse(fs.readFileSync(candidate, 'utf8'));
207
+ return normalizeSteerBrowserSettings(parsed);
208
+ }
209
+ catch {
210
+ return { ...DEFAULT_STEER_BROWSER_SETTINGS };
211
+ }
212
+ }
213
+ export function writeSteerBrowserSettings(patch, userDataDir) {
214
+ const dir = userDataDir ?? getUserDataDir();
215
+ const current = readSteerBrowserSettings(dir);
216
+ const merged = normalizeSteerBrowserSettings({ ...current, ...patch });
217
+ if (merged.sessionMode === 'attach' || patch.cdpEndpoint !== undefined) {
218
+ const validated = validateCdpLoopbackEndpoint(merged.cdpEndpoint);
219
+ merged.cdpEndpoint = validated.normalizedUrl;
220
+ }
221
+ if (merged.browser === 'custom' && !merged.customExecutablePath) {
222
+ throw new Error('Enter the path to the custom browser executable.');
223
+ }
224
+ fs.mkdirSync(dir, { recursive: true });
225
+ const file = settingsFilePath(dir);
226
+ const tmp = `${file}.tmp-${process.pid}`;
227
+ fs.writeFileSync(tmp, `${JSON.stringify(merged, null, 2)}\n`, 'utf8');
228
+ fs.renameSync(tmp, file);
229
+ return merged;
230
+ }
@@ -0,0 +1,2 @@
1
+ /** Browser page selected by model-facing Browser Use tools. */
2
+ export const PRIMARY_BROWSER_ID = 'primary';