arco-workbench 0.2.0 → 0.2.2

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 (48) hide show
  1. package/CONTRIBUTING.md +26 -24
  2. package/client/dist/assets/{PhosphorBackdrop-9jNRO1ZM.js → PhosphorBackdrop-BbR3xmfD.js} +1 -1
  3. package/client/dist/assets/{ThemedBackgroundShaderImpl-tUi3k54Y.js → ThemedBackgroundShaderImpl-UMjbs9ZN.js} +1 -1
  4. package/client/dist/assets/{XtermView-B7BOSnVo.js → XtermView-n135qz-f.js} +1 -1
  5. package/client/dist/assets/{galleryEditor-Ohc2h9cD.js → galleryEditor-CFSke4by.js} +1 -1
  6. package/client/dist/assets/{index-ILGXWriO.js → index-DeoJbjI3.js} +235 -235
  7. package/client/dist/index.html +1 -1
  8. package/client/src/components/HeaderVersionBox.tsx +6 -8
  9. package/client/src/components/SettingsPanel.tsx +44 -6
  10. package/client/src/components/settings/AppVersionSection.tsx +4 -4
  11. package/client/src/help/content/header.tsx +3 -2
  12. package/client/src/help/content/settings.tsx +10 -5
  13. package/client/src/help/manualSections/configuration.tsx +2 -0
  14. package/client/src/help/manualSections/maintenance.tsx +11 -7
  15. package/client/src/stores/appUpdateStore.ts +7 -1
  16. package/docs/HTTP_API.md +2 -2
  17. package/docs/OPERATIONS.md +22 -14
  18. package/docs/PROTOCOL.md +2 -2
  19. package/docs/RESEARCH.md +1 -1
  20. package/docs/SETTINGS.md +11 -7
  21. package/node_modules/@arco/shared/dist/protocol/serverMessages.d.ts +2 -2
  22. package/node_modules/@arco/shared/package.json +1 -1
  23. package/package.json +2 -2
  24. package/scripts/packaging/update.mjs +92 -35
  25. package/server/dist/authLoginSession.js +9 -1
  26. package/server/dist/capabilities.d.ts +6 -0
  27. package/server/dist/capabilities.js +13 -4
  28. package/server/dist/http/diagnosticsRoutes.js +1 -1
  29. package/server/dist/providers/antigravity/index.js +2 -2
  30. package/server/dist/providers/antigravity/status.js +3 -2
  31. package/server/dist/providers/antigravity/usage.js +3 -2
  32. package/server/dist/updateCheck.js +53 -67
  33. package/server/dist/updateManager.d.ts +2 -4
  34. package/server/dist/updateManager.js +4 -1
  35. package/server/dist/windowsCommand.d.ts +15 -0
  36. package/server/dist/windowsCommand.js +85 -4
  37. package/server/package.json +1 -1
  38. package/server/src/authLoginSession.ts +9 -1
  39. package/server/src/capabilities.ts +14 -4
  40. package/server/src/http/diagnosticsRoutes.ts +1 -1
  41. package/server/src/providers/antigravity/index.ts +2 -2
  42. package/server/src/providers/antigravity/status.ts +3 -2
  43. package/server/src/providers/antigravity/usage.ts +3 -2
  44. package/server/src/updateCheck.ts +47 -54
  45. package/server/src/updateManager.ts +5 -2
  46. package/server/src/windowsCommand.ts +83 -4
  47. package/shared/dist/protocol/serverMessages.d.ts +2 -2
  48. package/shared/src/protocol/serverMessages.ts +2 -2
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "node-pty": "1.1.0"
5
5
  },
6
6
  "name": "arco-workbench",
7
- "version": "0.2.0",
7
+ "version": "0.2.2",
8
8
  "repository": {
9
9
  "type": "git",
10
10
  "url": "git+https://github.com/ghreprimand/arco.git"
@@ -67,7 +67,7 @@
67
67
  "word-extractor": "1.0.4",
68
68
  "ws": "8.22.0",
69
69
  "xlsx": "0.20.3",
70
- "@arco/shared": "0.2.0"
70
+ "@arco/shared": "0.2.2"
71
71
  },
72
72
  "bundleDependencies": [
73
73
  "@arco/shared",
@@ -37,7 +37,45 @@ export function writeUpdateResult(resultFile, attemptId, result, now = Date.now)
37
37
  writeFileSync(resultFile, JSON.stringify({ ...attempt, outcome: result.outcome, ...(typeof result.message === 'string' ? { message: result.message } : {}), finishedAt: now() }), { mode: 0o600 });
38
38
  return true;
39
39
  }
40
- export async function updatePackage(manifest, root, deps = {}) {
40
+ // npm diagnostics can contain registry credentials, URLs and local paths.
41
+ const safeErrorCodes = new Set([
42
+ 'E401', 'E403', 'E404', 'E405', 'E429', 'E500', 'E502', 'E503', 'E504',
43
+ 'EACCES', 'EAUTH', 'EAI_AGAIN', 'ECONNREFUSED', 'ECONNRESET', 'EEXIST',
44
+ 'EINTEGRITY', 'EINVAL', 'EIO', 'ENOENT', 'ENOMSG', 'ENOSPC', 'ENOTCACHED',
45
+ 'ENOTEMPTY', 'ENOTFOUND', 'EOVERFLOW', 'EPERM', 'ERESOLVE', 'ETARGET',
46
+ 'ETIMEDOUT', 'ERR_TLS_CERT_ALTNAME_INVALID', 'SELF_SIGNED_CERT_IN_CHAIN',
47
+ ]);
48
+
49
+ function npmFailure(result) {
50
+ const diagnostic = /^npm (?:error|ERR!) code ([A-Z0-9_]+)\r?$/mi;
51
+ const code = result.error?.code ?? diagnostic.exec(result.stderr ?? '')?.[1] ?? diagnostic.exec(result.stdout ?? '')?.[1];
52
+ if (safeErrorCodes.has(code)) return ' (' + code + ')';
53
+ return Number.isInteger(result.status) ? ' (npm exit ' + result.status + ')' : '';
54
+ }
55
+
56
+ const publicRegistry = '--registry=https://registry.npmjs.org/';
57
+
58
+ function stagePackage(call, name, version, scratch) {
59
+ const expectedName = `${name.replace(/^@/, '').replace('/', '-')}-${version}.tgz`;
60
+ const archive = join(scratch, expectedName);
61
+ const result = call('Package download failed', [
62
+ 'pack', `${name}@${version}`, '--json', '--ignore-scripts', '--pack-destination', scratch,
63
+ publicRegistry, '--prefer-online', '--fetch-retries=0', '--fetch-timeout=30000',
64
+ ], { timeout: 90_000 });
65
+ let packed, stat;
66
+ try {
67
+ stat = lstatSync(archive, { throwIfNoEntry: false });
68
+ packed = JSON.parse(result.stdout);
69
+ } catch { /* invalid npm output or archive */ }
70
+ if (!Array.isArray(packed) || packed.length !== 1 || packed[0]?.name !== name
71
+ || packed[0]?.version !== version || packed[0]?.filename !== expectedName || !stat?.isFile() || stat.size === 0) {
72
+ throw new Error('Package download failed: npm did not stage the requested archive');
73
+ }
74
+ return archive;
75
+ }
76
+
77
+ export async function updatePackage(manifest, packageRoot, deps = {}) {
78
+ const root = resolve(packageRoot);
41
79
  const env = deps.env ?? process.env, platform = deps.platform ?? process.platform;
42
80
  const home = deps.home ?? servicePaths(platform, env).home;
43
81
  const prefix = deps.prefix ?? globalPrefix(root, platform);
@@ -56,36 +94,37 @@ export async function updatePackage(manifest, root, deps = {}) {
56
94
  mkdirSync(home, { recursive: true, mode: 0o700 });
57
95
  const lock = join(home, 'package-update.lock'); let lockFd;
58
96
  try { lockFd = openSync(lock, 'wx', 0o600); } catch { throw new Error('Another update may be running. Verify that no update is active before removing package-update.lock from the Arco home.'); }
59
- const scratch = mkdtempSync(join(home, '.update-')); let preserve = false;
60
- let stopped = false, installed = false; const backup = join(scratch, 'previous-package');
61
- const call = (args, options = {}) => {
97
+ let scratch, backup, preserve = false;
98
+ let stopped = false, installAttempted = false;
99
+ const call = (stage, args, options = {}) => {
62
100
  const result = run(process.execPath, [npm, ...args], options);
63
- if (result.error || result.status !== 0) throw new Error(`npm ${args[0]} failed${result.error ? `: ${result.error.message}` : ''}`);
101
+ if (result.error || result.status !== 0) throw new Error(stage + npmFailure(result));
64
102
  return result;
65
103
  };
66
104
  try {
67
- let version = deps.expected?.slice(1);
68
- if (!deps.target && !version) {
69
- const result = call(['view', `${manifest.name}@latest`, 'version', '--json']);
70
- const parsed = JSON.parse(result.stdout || 'null');
71
- version = Array.isArray(parsed) && parsed.length === 1 ? parsed[0] : parsed;
72
- if (typeof version !== 'string' || !/^\d+\.\d+\.\d+$/.test(version)) throw new Error('The registry did not return a stable release version.');
73
- }
105
+ scratch = mkdtempSync(join(home, '.update-'));
106
+ backup = join(scratch, 'previous-package');
107
+ let version;
74
108
  if (!deps.target) {
109
+ const result = call('Could not check npm for updates', [
110
+ 'view', `${manifest.name}@latest`, 'version', '--json', publicRegistry,
111
+ '--prefer-online', '--fetch-retries=0', '--fetch-timeout=5000',
112
+ ], { timeout: 10_000 });
113
+ let parsed;
114
+ try { parsed = JSON.parse(result.stdout); } catch { /* invalid npm output */ }
115
+ version = Array.isArray(parsed) && parsed.length === 1 ? parsed[0] : parsed;
116
+ if (typeof version !== 'string' || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(version)) {
117
+ throw new Error('npm did not return a stable release version');
118
+ }
119
+ if (deps.expected && deps.expected !== `v${version}`) {
120
+ throw new Error('The latest npm version changed. Use CHECK NOW to review it before updating');
121
+ }
75
122
  const order = compareVersions(version, manifest.version);
76
123
  if (order === null) throw new Error('The installed or target package version is invalid.');
77
124
  if (order < 0) throw new Error('The latest package is older than this installation. A downgrade is not performed.');
78
125
  if (order === 0) return { outcome: 'unchanged', message: 'Already on the newest release.' };
79
- if (deps.expected) {
80
- let published;
81
- try {
82
- const result = call(['view', `${manifest.name}@${version}`, 'version', '--json', '--cache', join(scratch, 'registry-cache'), '--prefer-online', '--fetch-retries=0', '--fetch-timeout=5000'], { timeout: 15000 });
83
- published = JSON.parse(result.stdout || 'null');
84
- if (Array.isArray(published) && published.length === 1) published = published[0];
85
- } catch { throw new Error('The confirmed release is not available from the npm registry, or the registry could not be reached. Try again later.'); }
86
- if (published !== version) throw new Error('The confirmed release is not available from the npm registry, or the registry could not be reached. Try again later.');
87
- }
88
126
  }
127
+ const archive = deps.target ?? stagePackage(call, manifest.name, version, scratch);
89
128
  // Dependencies are not all bundled in the tarball. A full local snapshot
90
129
  // permits rollback even when the registry or the network is unavailable.
91
130
  cpSync(root, backup, { recursive: true, dereference: false, verbatimSymlinks: true, errorOnExist: true, force: false });
@@ -98,9 +137,8 @@ export async function updatePackage(manifest, root, deps = {}) {
98
137
  const running = servicePid ? await waitForRecordedPid(servicePid, deps) : await windowsRunning();
99
138
  if (running) throw new Error(servicePid ? `The Arco service process ${servicePid} is still running. Stop it before updating on Windows.` : 'Stop all Arco processes before updating on Windows.');
100
139
  }
101
- const target = deps.target ?? `${manifest.name}@${version}`;
102
- installed = true;
103
- call(['install', '--global', '--ignore-scripts', '--no-audit', '--no-fund', '--prefix', prefix, target], { stdio: 'inherit' });
140
+ installAttempted = true;
141
+ call('Package installation failed', ['install', '--global', '--ignore-scripts', '--no-audit', '--no-fund', '--prefix', prefix, archive]);
104
142
  // The new package may define the service differently. A fresh process loads
105
143
  // the new code to
106
144
  // rewrite an unmodified Arco-owned definition; a failure keeps the old one.
@@ -114,23 +152,42 @@ export async function updatePackage(manifest, root, deps = {}) {
114
152
  return { outcome: 'updated', message: `Updated${version ? ` to v${version}` : ` ${manifest.name}`}; ${managed ? 'service restarted' : 'restart Arco to use the update'}.${refreshNote}` };
115
153
  } catch (error) {
116
154
  const detail = String(error.message).replace(/[.\s]+$/, '');
117
- if (installed) {
155
+ let damaged;
156
+ if (installAttempted) {
118
157
  // Keep both copies until a complete restoration is available. If the
119
158
  // copy fails, retain the snapshot and report its location for recovery.
120
- const damaged = `${root}.arco-update-failed-${process.pid}`;
159
+ damaged = `${root}.arco-update-failed-${process.pid}`;
121
160
  try {
122
- if (existsSync(damaged)) throw new Error('A previous failed update needs manual recovery.');
123
- if (existsSync(root)) renameSync(root, damaged);
161
+ if (lstatSync(damaged, { throwIfNoEntry: false })) throw new Error('A previous failed update needs manual recovery.');
162
+ if (lstatSync(root, { throwIfNoEntry: false })) renameSync(root, damaged);
124
163
  try { cpSync(backup, root, { recursive: true, dereference: false, verbatimSymlinks: true, errorOnExist: true, force: false }); }
125
- catch (copyError) { if (existsSync(root)) rmSync(root, { recursive: true, force: true }); if (existsSync(damaged)) renameSync(damaged, root); throw copyError; }
126
- rmSync(damaged, { recursive: true, force: true });
127
- } catch (rollback) { preserve = true; throw new Error(`Update failed: ${detail}. Rollback failed: ${String(rollback.message).replace(/[.\s]+$/, '')}. Previous package snapshot: ${backup}`); }
164
+ catch (copyError) { rmSync(root, { recursive: true, force: true }); if (lstatSync(damaged, { throwIfNoEntry: false })) renameSync(damaged, root); throw copyError; }
165
+ } catch (rollback) {
166
+ preserve = true;
167
+ const code = safeErrorCodes.has(rollback.code) ? ' (' + rollback.code + ')' : '';
168
+ throw new Error(`Update failed: ${detail}. Could not restore the previous package${code}. Keep Arco stopped and copy the snapshot back to the original package folder. Previous package snapshot: ${backup}`);
169
+ }
170
+ }
171
+ if (stopped) {
172
+ try { await service('start'); }
173
+ catch {
174
+ preserve = true;
175
+ const recovery = installAttempted
176
+ ? `The previous package was restored. Previous package snapshot: ${backup}`
177
+ : 'The installed package was left unchanged.';
178
+ throw new Error(`Update failed: ${detail}. The service could not restart. Check the service and run arco service start after resolving the error. ${recovery}`);
179
+ }
180
+ }
181
+ const recovery = installAttempted ? ' The previous package was restored.' + (stopped ? ' The service was restarted.' : '') : '';
182
+ let cleanupNote = '';
183
+ if (damaged) {
184
+ try { rmSync(damaged, { recursive: true, force: true }); }
185
+ catch { cleanupNote = ' The failed package remains in quarantine beside the installation.'; }
128
186
  }
129
- if (stopped) { try { await service('start'); stopped = false; } catch (restart) { throw new Error(`Update failed: ${detail}. The previous package was restored, but the service could not restart: ${restart.message}`); } }
130
- throw new Error(`Update failed: ${detail}.${installed ? ' The previous package was restored.' : ''}`);
187
+ throw new Error(`Update failed: ${detail}.${recovery}${cleanupNote}`);
131
188
  } finally {
132
- if (!preserve) rmSync(scratch, { recursive: true, force: true });
133
- closeSync(lockFd); try { unlinkSync(lock); } catch { /* stale lock fails closed */ }
189
+ try { if (scratch && !preserve) rmSync(scratch, { recursive: true, force: true }); }
190
+ finally { closeSync(lockFd); try { unlinkSync(lock); } catch { /* stale lock fails closed */ } }
134
191
  }
135
192
  }
136
193
 
@@ -7,6 +7,7 @@
7
7
  import { noteAntigravityLoginCompleted } from './providers/antigravity/status.js';
8
8
  import { noteGeminiResearchSignInExpired } from './providers/antigravity/researchSignIn.js';
9
9
  import { spawn } from 'child_process';
10
+ import { resolveLoginCommand, withSinglePath } from './windowsCommand.js';
10
11
  import { killProcessTree } from './workers/processKill.js';
11
12
  const SESSION_TTL_MS = 15 * 60_000;
12
13
  const OUTPUT_CAP = 16 * 1024;
@@ -71,11 +72,18 @@ export function startLoginSession(provider, command) {
71
72
  };
72
73
  live.set(provider, entry);
73
74
  let child;
75
+ // Windows: find the program the way provider turns do (running PATH, then the
76
+ // PATH a new terminal reads), so sign-in does not depend on cmd.exe alone.
77
+ const resolved = resolveLoginCommand(spec.command ?? command, { fresh: provider === 'antigravity-cli' });
78
+ if ('missing' in resolved) {
79
+ finish(entry, 'failed', `${resolved.missing} was not found on the PATH Arco is running with. Restart Arco from a new terminal after installing it, or run the sign-in command in your terminal.`);
80
+ return snapshot(entry);
81
+ }
74
82
  try {
75
83
  // No browser exists where the server runs; the CLIs print the link anyway.
76
84
  // detached on POSIX makes the shell a process-group leader, so a cancel or
77
85
  // timeout reaches the provider CLI it started, not only the shell.
78
- child = spawn(spec.command ?? command, { shell: true, detached: process.platform !== 'win32', windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'], env: Object.fromEntries(Object.entries({ ...process.env, BROWSER: 'true', NO_BROWSER: 'true', ...(spec.env ?? {}) }).filter(([name]) => !spec.unsetEnv?.includes(name))) });
86
+ child = spawn(resolved.line, { shell: true, detached: process.platform !== 'win32', windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'], env: Object.fromEntries(Object.entries({ ...(resolved.path ? withSinglePath(process.env, resolved.path) : process.env), BROWSER: 'true', NO_BROWSER: 'true', ...(spec.env ?? {}) }).filter(([name]) => !spec.unsetEnv?.includes(name))) });
79
87
  }
80
88
  catch (err) {
81
89
  finish(entry, 'failed', err instanceof Error ? err.message : String(err));
@@ -1,6 +1,12 @@
1
1
  import type { Capabilities, CliUpdateOutcome } from '@arco/shared';
2
2
  import { type CliUpdateDecision, type UpdateCommandResult } from './cliUpdateDecision.js';
3
+ import { type ResolveOptions } from './windowsCommand.js';
3
4
  export type CliProvider = 'claude' | 'codex' | 'cursor' | 'antigravity-cli';
5
+ export declare function probeCommandFor(bin: string, args: string[], opts?: ResolveOptions): {
6
+ command: string;
7
+ args: string[];
8
+ env?: NodeJS.ProcessEnv;
9
+ };
4
10
  export declare function probeVersion(bin: string, flags?: string[], timeoutMs?: number): Promise<string>;
5
11
  export declare function probeCapabilities(): Promise<Capabilities>;
6
12
  export declare function refreshRuntimeVersions(previous: Capabilities): Promise<Capabilities>;
@@ -11,7 +11,7 @@ import { atomicWriteFile } from './atomicFile.js';
11
11
  import { probeCodexUpdate, describeCliUpdate } from './cliUpdateDecision.js';
12
12
  import { compareVersions } from './updateCheck.js';
13
13
  import { arcoHome } from './arcoHome.js';
14
- import { commandArgs } from './windowsCommand.js';
14
+ import { commandArgs, resolveCommand } from './windowsCommand.js';
15
15
  const execFileAsync = promisify(execFile);
16
16
  const CLI_PROBE_OPTIONS = {
17
17
  timeout: 5_000,
@@ -28,9 +28,16 @@ const cliBinary = (provider) => provider === 'cursor' ? 'cursor-agent' : provide
28
28
  // optional dep, so npm exited 0 — and every `codex --version` threw. Collapsing
29
29
  // that into 'unknown' made the whole CODEX row disappear from the popover, which
30
30
  // reads as "not installed" and gives the operator nothing to click or diagnose.
31
+ // Antigravity is found the way its status, usage, sign-in and turns find it: a
32
+ // program installed after Arco started, or on the new-terminal PATH only, still
33
+ // counts. Every other program keeps the plain lookup.
34
+ export function probeCommandFor(bin, args, opts = {}) {
35
+ return resolveCommand(bin, args, bin === 'agy' ? { fresh: true, ...opts } : opts);
36
+ }
31
37
  export async function probeVersion(bin, flags = ['--version'], timeoutMs = 5_000) {
32
38
  try {
33
- const { stdout } = await execFileAsync(...commandArgs(bin, flags), { ...CLI_PROBE_OPTIONS, timeout: timeoutMs });
39
+ const cmd = probeCommandFor(bin, flags);
40
+ const { stdout } = await execFileAsync(cmd.command, cmd.args, { ...CLI_PROBE_OPTIONS, timeout: timeoutMs, ...(cmd.env ? { env: cmd.env } : {}) });
34
41
  const match = stdout.match(/(\d+\.\d+\.\d+(?:[-.][A-Za-z0-9.-]+)?)/);
35
42
  return match ? match[1] : 'unknown';
36
43
  }
@@ -43,7 +50,8 @@ export async function probeVersion(bin, flags = ['--version'], timeoutMs = 5_000
43
50
  // fits the popover's one-line result slot.
44
51
  async function probeFailureReason(bin) {
45
52
  try {
46
- await execFileAsync(...commandArgs(bin, ['--version']), CLI_PROBE_OPTIONS);
53
+ const cmd = probeCommandFor(bin, ['--version']);
54
+ await execFileAsync(cmd.command, cmd.args, { ...CLI_PROBE_OPTIONS, ...(cmd.env ? { env: cmd.env } : {}) });
47
55
  return null;
48
56
  }
49
57
  catch (err) {
@@ -280,7 +288,8 @@ async function runUpdateCommand(cmd, args, provider) {
280
288
  delete env[name];
281
289
  }
282
290
  try {
283
- const { stdout, stderr } = await execFileAsync(...commandArgs(cmd, args), { env, maxBuffer: 4 * 1024 * 1024, timeout: 180_000 });
291
+ const run = probeCommandFor(cmd, args);
292
+ const { stdout, stderr } = await execFileAsync(run.command, run.args, { env: run.env ? { ...env, ...run.env } : env, maxBuffer: 4 * 1024 * 1024, timeout: 180_000 });
284
293
  return { output: (stdout + stderr).trim(), exitCode: 0 };
285
294
  }
286
295
  catch (err) {
@@ -37,7 +37,7 @@ export async function tryHandleDiagnosticsRoutes(req, res) {
37
37
  const path = req.url.split('?')[0];
38
38
  if (path === '/api/diagnostics/research-sandbox') {
39
39
  const [claudeCli, codex, cursor, gemini, geminiSignIn] = await Promise.all([researchSandboxAvailable('claude'), researchSandboxAvailable('codex'), researchSandboxAvailable('cursor'), researchSandboxAvailable('antigravity'), geminiResearchSignInState()]);
40
- return send(200, { claudeCli, codex, cursor, gemini, geminiSignIn, codexVersionReason: codexResearchVersionReason(installedCodexVersion()), cursorVersionReason: cursorIsolationReason() });
40
+ return send(200, { claudeCli, codex, cursor, gemini, geminiSignIn, platform: process.platform, codexVersionReason: codexResearchVersionReason(installedCodexVersion()), cursorVersionReason: cursorIsolationReason() });
41
41
  }
42
42
  if (path === '/api/diagnostics/support-bundle') {
43
43
  try {
@@ -18,7 +18,7 @@ import { spawn } from 'node:child_process';
18
18
  import { EventEmitter } from 'node:events';
19
19
  import { AcpJsonRpcClient, AcpReplyError } from '../acp/acpJsonRpc.js';
20
20
  import { cancelAcpPermissions, requestAcpPermission } from '../acp/permissionGate.js';
21
- import { commandArgs } from '../../windowsCommand.js';
21
+ import { resolveCommand } from '../../windowsCommand.js';
22
22
  import { killProcessTree } from '../../workers/processKill.js';
23
23
  import { probeVersion } from '../../capabilities.js';
24
24
  import { compareVersions } from '../../updateCheck.js';
@@ -146,7 +146,7 @@ class AntigravityTurn extends EventEmitter {
146
146
  }
147
147
  const proc = fenced
148
148
  ? spawn(fenced.command.file, fenced.command.args, { cwd: '/', env: { PATH: '/usr/bin:/bin' }, stdio: ['pipe', 'pipe', 'pipe'], detached: true })
149
- : spawn(...commandArgs('agy', ['acp']), { cwd, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, detached: process.platform !== 'win32' });
149
+ : (() => { const agy = resolveCommand('agy', ['acp'], { fresh: true }); return spawn(agy.command, agy.args, { cwd, ...(agy.env ? { env: agy.env } : {}), stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, detached: process.platform !== 'win32' }); })();
150
150
  if (fenced) {
151
151
  const launch = fenced;
152
152
  proc.once('close', () => { void launch.close().catch(() => this.emit('system_notice', 'Worker isolation cleanup failed.')); });
@@ -1,6 +1,6 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
- import { commandArgs } from '../../windowsCommand.js';
3
+ import { resolveCommand } from '../../windowsCommand.js';
4
4
  let authState = 'unknown';
5
5
  let models = [];
6
6
  let capabilities = {};
@@ -13,7 +13,8 @@ export async function antigravityStatus() {
13
13
  if (Date.now() - lastProbe > 60_000) {
14
14
  lastProbe = Date.now();
15
15
  try {
16
- const { stdout } = await exec(...commandArgs('agy', ['models']), { timeout: 10_000, maxBuffer: 256 * 1024 });
16
+ const agy = resolveCommand('agy', ['models'], { fresh: true });
17
+ const { stdout } = await exec(agy.command, agy.args, { timeout: 10_000, maxBuffer: 256 * 1024, ...(agy.env ? { env: agy.env } : {}) });
17
18
  const ids = stdout.split(/\r?\n/).map(line => line.split(/\s+/)[0]).filter(id => /^gemini-[a-z0-9.-]+$/.test(id));
18
19
  models = [...new Set(ids.map(id => id.replace(/-(low|medium|high|xhigh)$/, '')))];
19
20
  capabilities = Object.fromEntries(models.map(model => { const levels = ['low', 'medium', 'high', 'xhigh'].filter(level => ids.includes(`${model}-${level}`)); return [model, { tools: true, vision: true, thinking: levels.length > 0, thinkingLevels: levels }]; }));
@@ -1,6 +1,6 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
- import { commandArgs } from '../../windowsCommand.js';
3
+ import { resolveCommand } from '../../windowsCommand.js';
4
4
  const exec = promisify(execFile);
5
5
  export function parseAntigravityUsage(text) {
6
6
  try {
@@ -25,7 +25,8 @@ export function parseAntigravityUsage(text) {
25
25
  }
26
26
  export async function getAntigravityUsage() {
27
27
  try {
28
- const { stdout } = await exec(...commandArgs('agy', ['-p', '/usage', '--output-format', 'json']), { timeout: 5000, killSignal: 'SIGKILL', maxBuffer: 256 * 1024, windowsHide: true });
28
+ const agy = resolveCommand('agy', ['-p', '/usage', '--output-format', 'json'], { fresh: true });
29
+ const { stdout } = await exec(agy.command, agy.args, { timeout: 5000, killSignal: 'SIGKILL', maxBuffer: 256 * 1024, windowsHide: true, ...(agy.env ? { env: agy.env } : {}) });
29
30
  return parseAntigravityUsage(stdout);
30
31
  }
31
32
  catch {
@@ -1,4 +1,6 @@
1
- const ENDPOINT = 'https://api.github.com/repos/ghreprimand/arco/releases/latest';
1
+ const GITHUB_LATEST = 'https://api.github.com/repos/ghreprimand/arco/releases/latest';
2
+ const NPM_LATEST = 'https://registry.npmjs.org/arco-workbench/latest';
3
+ const STABLE_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
2
4
  const RELEASE_PREFIX = 'https://github.com/ghreprimand/arco/releases/tag/';
3
5
  const SEMVER = /^(?:v)?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][\da-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][\da-zA-Z-]*))*))?(?:\+[\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*)?$/;
4
6
  export function compareVersions(a, b) {
@@ -40,81 +42,65 @@ export function createUpdateChecker(deps) {
40
42
  async function status() {
41
43
  return { ...cache, enabled: enabled(await deps.settings()) };
42
44
  }
45
+ async function lookup() {
46
+ const response = await request(deps.packaged ? NPM_LATEST : GITHUB_LATEST, {
47
+ headers: { Accept: deps.packaged ? 'application/json' : 'application/vnd.github+json', 'User-Agent': `arco/${deps.current}` },
48
+ signal: AbortSignal.timeout(5000), redirect: 'error',
49
+ });
50
+ if (!response.ok)
51
+ throw new Error('Release check unavailable');
52
+ if (deps.packaged) {
53
+ const pkg = await response.json();
54
+ const version = pkg?.version;
55
+ if (pkg?.name !== 'arco-workbench' || typeof version !== 'string' || !STABLE_VERSION.test(version) ||
56
+ pkg.dist?.tarball !== `https://registry.npmjs.org/arco-workbench/-/arco-workbench-${version}.tgz`)
57
+ throw new Error('Invalid npm release');
58
+ const latest = `v${version}`;
59
+ return { latest, url: RELEASE_PREFIX + latest, publishedAt: null };
60
+ }
61
+ const release = await response.json();
62
+ const tag = release?.tag_name;
63
+ if (typeof tag !== 'string' || !STABLE_VERSION.test(tag.replace(/^v/, '')) ||
64
+ typeof release.html_url !== 'string' || !release.html_url.startsWith(RELEASE_PREFIX) ||
65
+ typeof release.published_at !== 'string' || !Number.isFinite(Date.parse(release.published_at)))
66
+ throw new Error('Invalid GitHub release');
67
+ return { latest: `v${tag.replace(/^v/, '')}`, url: release.html_url, publishedAt: release.published_at };
68
+ }
43
69
  async function perform() {
44
70
  if (!enabled(await deps.settings()))
45
71
  return status();
46
- cache.checkedAt = now().toISOString();
72
+ const checkedAt = now().toISOString();
73
+ let release;
47
74
  try {
48
- const response = await request(ENDPOINT, {
49
- headers: { Accept: 'application/vnd.github+json', 'User-Agent': `arco/${deps.current}` },
50
- signal: AbortSignal.timeout(5000), redirect: 'error',
51
- });
52
- if (!response.ok)
53
- throw new Error('release check unavailable');
54
- const release = await response.json();
55
- const tag = release.tag_name;
56
- if (typeof tag !== 'string' || compareVersions(tag, deps.current) === null ||
57
- typeof release.html_url !== 'string' || !release.html_url.startsWith(RELEASE_PREFIX) ||
58
- typeof release.published_at !== 'string' || !Number.isFinite(Date.parse(release.published_at)))
59
- throw new Error('invalid release');
60
- const latest = `v${tag.replace(/^v/, '')}`;
61
- let packageStatus;
62
- if (deps.packaged && compareVersions(tag, deps.current) > 0) {
63
- try {
64
- const version = tag.replace(/^v/, '');
65
- if (!/^\d+\.\d+\.\d+$/.test(version))
66
- throw new Error('not a stable version');
67
- const npm = await request(`https://registry.npmjs.org/arco-workbench/${version}`, {
68
- headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(5000), redirect: 'error',
69
- });
70
- if (npm.status === 404)
71
- packageStatus = 'unpublished';
72
- else if (!npm.ok)
73
- packageStatus = 'unknown';
74
- else {
75
- const metadata = await npm.json();
76
- packageStatus = metadata.name === 'arco-workbench' && metadata.version === version && !!(metadata.dist && typeof metadata.dist === 'object' && typeof metadata.dist.tarball === 'string') ? 'available' : 'unknown';
77
- }
78
- }
79
- catch {
80
- packageStatus = 'unknown';
81
- }
82
- }
83
- // Re-read preferences: an opt-out or dismissal can arrive during the request.
84
- const settings = await deps.settings();
85
- if (!enabled(settings))
86
- return status();
87
- const wasAvailable = cache.updateAvailable;
88
- const previousLatest = cache.latest;
89
- cache = { ...cache, latest, url: release.html_url, publishedAt: release.published_at, updateAvailable: compareVersions(tag, deps.current) > 0 && (!deps.packaged || packageStatus === 'available'), ...(deps.packaged ? { packageStatus } : {}) };
90
- if (deps.packaged && wasAvailable && !cache.updateAvailable) {
91
- if (previousLatest)
92
- announced.delete(previousLatest);
93
- deps.broadcast({ type: 'app_update_status_changed' });
94
- }
95
- if (cache.updateAvailable && settings.updateCheckDismissed !== latest && !announced.has(latest)) {
96
- announced.add(latest);
97
- const message = { type: 'app_update_available', current: deps.current, latest, url: release.html_url, publishedAt: release.published_at };
98
- deps.broadcast(message);
99
- deps.log?.(`app_update_available ${latest}`);
100
- }
75
+ release = await lookup();
101
76
  }
102
- catch {
103
- if (deps.packaged) {
104
- const wasAvailable = cache.updateAvailable;
105
- cache = { ...cache, updateAvailable: false, packageStatus: 'unknown' };
106
- if (wasAvailable) {
107
- if (cache.latest)
108
- announced.delete(cache.latest);
109
- deps.broadcast({ type: 'app_update_status_changed' });
110
- }
111
- }
77
+ catch { /* Record the source of the failed check without exposing upstream detail. */ }
78
+ const settings = await deps.settings();
79
+ if (!enabled(settings))
80
+ return status();
81
+ const previous = cache;
82
+ if (release) {
83
+ const order = compareVersions(release.latest, deps.current);
84
+ cache = { ...release, current: deps.current, enabled: true, checkedAt, updateAvailable: order === 1 };
85
+ }
86
+ else {
87
+ const checkFailure = deps.packaged ? 'npm' : 'github';
88
+ cache = { ...cache, checkedAt, updateAvailable: false, checkFailure };
112
89
  if (!loggedFailure) {
113
90
  loggedFailure = true;
114
- deps.debug?.('Release check unavailable; retrying on the next scheduled check.');
91
+ deps.debug?.(`Release check unavailable (${checkFailure}); retrying on the next scheduled check.`);
115
92
  }
116
93
  }
117
- return status();
94
+ if (previous.latest !== cache.latest || previous.checkFailure !== cache.checkFailure || previous.updateAvailable !== cache.updateAvailable) {
95
+ deps.broadcast({ type: 'app_update_status_changed' });
96
+ }
97
+ const { latest, url, publishedAt } = cache;
98
+ if (cache.updateAvailable && latest && url && settings.updateCheckDismissed !== latest && !announced.has(latest)) {
99
+ announced.add(latest);
100
+ deps.broadcast({ type: 'app_update_available', current: deps.current, latest, url, publishedAt });
101
+ deps.log?.(`app_update_available ${latest}`);
102
+ }
103
+ return { ...cache, enabled: true };
118
104
  }
119
105
  function check() {
120
106
  if (!pending)
@@ -1,3 +1,4 @@
1
+ import type { UpdateCheckStatus } from '@arco/shared';
1
2
  export type UpdateMode = 'service' | 'foreground' | 'docker';
2
3
  export declare function updateMode(platform?: NodeJS.Platform, env?: NodeJS.ProcessEnv): UpdateMode;
3
4
  type Status = {
@@ -16,10 +17,7 @@ export declare function createUpdateManager(deps?: {
16
17
  root?: string;
17
18
  env?: NodeJS.ProcessEnv;
18
19
  platform?: NodeJS.Platform;
19
- check?: () => Promise<{
20
- latest: string | null;
21
- updateAvailable: boolean;
22
- }>;
20
+ check?: () => Promise<Pick<UpdateCheckStatus, 'latest' | 'updateAvailable' | 'checkFailure'>>;
23
21
  launch?: (command: string, args: string[]) => {
24
22
  status: number | null;
25
23
  error?: Error;
@@ -72,12 +72,15 @@ export function createUpdateManager(deps = {}) {
72
72
  if (previous?.outcome === 'running' && now() - (previous.startedAt ?? 0) < 30 * 60_000)
73
73
  return { ok: false, status: 409, error: 'An update is already running.' };
74
74
  let latest;
75
+ const lookupError = packaged ? 'Could not check npm for updates.' : 'Could not check GitHub for releases.';
75
76
  try {
76
77
  latest = await check();
77
78
  }
78
79
  catch {
79
- return { ok: false, status: 503, error: 'Release check unavailable. Try again or use npm run arco:update.' };
80
+ return { ok: false, status: 503, error: lookupError };
80
81
  }
82
+ if (latest.checkFailure)
83
+ return { ok: false, status: 503, error: lookupError };
81
84
  if (!latest.updateAvailable || !latest.latest || !/^v\d+\.\d+\.\d+$/.test(latest.latest))
82
85
  return { ok: false, status: 409, error: 'No newer stable release is available.' };
83
86
  if (body.expectedLatest !== latest.latest)
@@ -1,6 +1,7 @@
1
1
  export interface ResolvedCommand {
2
2
  command: string;
3
3
  args: string[];
4
+ env?: NodeJS.ProcessEnv;
4
5
  }
5
6
  export interface ResolveOptions {
6
7
  platform?: NodeJS.Platform;
@@ -8,8 +9,22 @@ export interface ResolveOptions {
8
9
  nodePath?: string;
9
10
  isFile?: (path: string) => boolean;
10
11
  readText?: (path: string) => string;
12
+ fresh?: boolean;
13
+ registryPath?: () => string;
11
14
  }
12
15
  export declare function findWindowsCommand(command: string, env: NodeJS.ProcessEnv, isFile: (p: string) => boolean): string | null;
16
+ export declare function readRegistryPath(): string;
17
+ export declare function locateWindowsCommand(command: string, env: NodeJS.ProcessEnv, isFile: (p: string) => boolean, registryPath?: () => string): {
18
+ file: string;
19
+ path?: string;
20
+ } | null;
21
+ export declare function withSinglePath(env: NodeJS.ProcessEnv, path: string): NodeJS.ProcessEnv;
22
+ export declare function resolveLoginCommand(line: string, opts?: ResolveOptions): {
23
+ line: string;
24
+ path?: string;
25
+ } | {
26
+ missing: string;
27
+ };
13
28
  export declare function npmShimTarget(shimPath: string, text: string): string | null;
14
29
  export declare function resolveCommand(command: string, args?: readonly string[], opts?: ResolveOptions): ResolvedCommand;
15
30
  export declare function commandArgs(command: string, args?: readonly string[]): [string, string[]];