@andorra-labs/code 0.1.4 → 0.1.6

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 (171) hide show
  1. package/dist/src/account-presentation.js +3 -3
  2. package/dist/src/agent-execution.d.ts +2 -0
  3. package/dist/src/agent-execution.js +126 -20
  4. package/dist/src/agent-mcp.d.ts +18 -1
  5. package/dist/src/agent-mcp.js +103 -8
  6. package/dist/src/app-server/protocol.d.ts +33 -3
  7. package/dist/src/app-server/protocol.js +14 -1
  8. package/dist/src/app-server/workspace.d.ts +1 -0
  9. package/dist/src/app-server/workspace.js +7 -1
  10. package/dist/src/app-server.d.ts +115 -41
  11. package/dist/src/app-server.js +1229 -219
  12. package/dist/src/automation-runner.d.ts +9 -0
  13. package/dist/src/automation-runner.js +22 -1
  14. package/dist/src/automation-tool.js +8 -1
  15. package/dist/src/automations.js +1 -1
  16. package/dist/src/browser-captcha-tool.d.ts +54 -0
  17. package/dist/src/browser-captcha-tool.js +374 -0
  18. package/dist/src/browser-panel-tool.d.ts +7 -0
  19. package/dist/src/browser-panel-tool.js +74 -3
  20. package/dist/src/browser-runner.js +19 -4
  21. package/dist/src/browser-server.js +21 -1
  22. package/dist/src/browser-session.d.ts +16 -0
  23. package/dist/src/browser-session.js +35 -0
  24. package/dist/src/browser-ui/app.js +193 -3
  25. package/dist/src/browser-ui/style.css +15 -1
  26. package/dist/src/browser-view.d.ts +72 -4
  27. package/dist/src/browser-view.js +229 -17
  28. package/dist/src/capabilities.js +13 -2
  29. package/dist/src/capsolver.d.ts +60 -0
  30. package/dist/src/capsolver.js +101 -0
  31. package/dist/src/claude-provider.d.ts +6 -0
  32. package/dist/src/claude-provider.js +34 -3
  33. package/dist/src/cli-executable.d.ts +33 -0
  34. package/dist/src/cli-executable.js +64 -0
  35. package/dist/src/cli-process.d.ts +47 -0
  36. package/dist/src/cli-process.js +113 -0
  37. package/dist/src/cli-sign-in.d.ts +68 -0
  38. package/dist/src/cli-sign-in.js +224 -0
  39. package/dist/src/cli.js +54 -23
  40. package/dist/src/code-intelligence/CodeIntelligenceManager.d.ts +1 -1
  41. package/dist/src/code-intelligence/CodeIntelligenceManager.js +5 -5
  42. package/dist/src/coding-tools.js +44 -5
  43. package/dist/src/command-output-tap.d.ts +16 -0
  44. package/dist/src/command-output-tap.js +45 -0
  45. package/dist/src/command-screens.js +3 -3
  46. package/dist/src/commands.d.ts +10 -1
  47. package/dist/src/commands.js +7 -7
  48. package/dist/src/completion.d.ts +23 -5
  49. package/dist/src/completion.js +334 -17
  50. package/dist/src/config.d.ts +13 -0
  51. package/dist/src/config.js +28 -2
  52. package/dist/src/deadline.js +6 -0
  53. package/dist/src/extensions.d.ts +1 -0
  54. package/dist/src/extensions.js +16 -3
  55. package/dist/src/graph-provider-portability.js +2 -2
  56. package/dist/src/graph-quota.d.ts +1 -1
  57. package/dist/src/graph-quota.js +1 -1
  58. package/dist/src/graph-runner.js +35 -21
  59. package/dist/src/graph-selection.d.ts +6 -0
  60. package/dist/src/graph-selection.js +10 -0
  61. package/dist/src/graph-server.d.ts +7 -0
  62. package/dist/src/graph-server.js +61 -3
  63. package/dist/src/graph-sync.d.ts +50 -0
  64. package/dist/src/graph-sync.js +383 -12
  65. package/dist/src/graph-ui/app.js +61 -8
  66. package/dist/src/graph-ui/icons.js +1 -0
  67. package/dist/src/graph-ui/index.html +1 -1
  68. package/dist/src/graph-ui/skill-picker.js +242 -0
  69. package/dist/src/graph-ui/style.css +19 -0
  70. package/dist/src/graphs.d.ts +46 -4
  71. package/dist/src/graphs.js +152 -27
  72. package/dist/src/grok-provider.d.ts +50 -0
  73. package/dist/src/grok-provider.js +186 -0
  74. package/dist/src/handoffs.d.ts +13 -0
  75. package/dist/src/handoffs.js +31 -1
  76. package/dist/src/managed-sign-in.d.ts +38 -0
  77. package/dist/src/managed-sign-in.js +169 -0
  78. package/dist/src/markdown.d.ts +5 -0
  79. package/dist/src/markdown.js +5 -2
  80. package/dist/src/mcp.js +11 -0
  81. package/dist/src/membership.d.ts +8 -1
  82. package/dist/src/membership.js +15 -5
  83. package/dist/src/model-metadata.js +14 -2
  84. package/dist/src/model-override.d.ts +10 -0
  85. package/dist/src/model-override.js +20 -0
  86. package/dist/src/opencode-cli-provider.d.ts +122 -0
  87. package/dist/src/opencode-cli-provider.js +415 -0
  88. package/dist/src/opencode-provider.js +23 -8
  89. package/dist/src/palette.d.ts +2 -0
  90. package/dist/src/palette.js +2 -0
  91. package/dist/src/permissions.d.ts +19 -1
  92. package/dist/src/permissions.js +30 -1
  93. package/dist/src/powershell-pool.d.ts +2 -2
  94. package/dist/src/powershell-pool.js +18 -5
  95. package/dist/src/provider-connection.js +36 -0
  96. package/dist/src/provider-engine.d.ts +2 -1
  97. package/dist/src/provider-engine.js +64 -13
  98. package/dist/src/provider-import.js +6 -1
  99. package/dist/src/provider-settings.js +22 -3
  100. package/dist/src/providers.d.ts +12 -1
  101. package/dist/src/providers.js +27 -8
  102. package/dist/src/pull-requests.d.ts +111 -17
  103. package/dist/src/pull-requests.js +308 -76
  104. package/dist/src/qa/qa-authorize.js +9 -1
  105. package/dist/src/react-runtime.js +76 -5
  106. package/dist/src/remote/engine-pool.js +1 -1
  107. package/dist/src/run-progress.js +6 -1
  108. package/dist/src/run-records.d.ts +133 -27
  109. package/dist/src/run-records.js +320 -40
  110. package/dist/src/runtime.d.ts +38 -1
  111. package/dist/src/runtime.js +27 -4
  112. package/dist/src/save-lock.d.ts +11 -0
  113. package/dist/src/save-lock.js +29 -2
  114. package/dist/src/sessions.js +4 -1
  115. package/dist/src/shell.js +4 -1
  116. package/dist/src/side-panel.d.ts +1 -1
  117. package/dist/src/side-panel.js +1 -1
  118. package/dist/src/skill-commands.d.ts +2 -0
  119. package/dist/src/skill-commands.js +2 -0
  120. package/dist/src/skills/bundled/create-agent/SKILL.md +81 -0
  121. package/dist/src/skills/bundled/create-skill/SKILL.md +81 -0
  122. package/dist/src/skills/bundled/doctor/SKILL.md +43 -0
  123. package/dist/src/skills/bundled/graph-manager/SKILL.md +97 -0
  124. package/dist/src/skills/bundled/graph-manager/errors.md +38 -0
  125. package/dist/src/skills/bundled/graph-manager/patterns.md +78 -0
  126. package/dist/src/skills/bundled/manage-mcp/SKILL.md +75 -0
  127. package/dist/src/skills/bundled/manage-mcp/probe.md +165 -0
  128. package/dist/src/skills/bundled/manage-skills/SKILL.md +67 -0
  129. package/dist/src/skills/bundled/provenance.json +50 -0
  130. package/dist/src/skills/bundled/write-instructions/SKILL.md +42 -0
  131. package/dist/src/skills/invocable-skills.d.ts +41 -0
  132. package/dist/src/skills/invocable-skills.js +49 -0
  133. package/dist/src/skills/prompt-skills.d.ts +1 -0
  134. package/dist/src/skills/prompt-skills.js +33 -0
  135. package/dist/src/skills/runtime-skills.d.ts +4 -0
  136. package/dist/src/skills/runtime-skills.js +21 -0
  137. package/dist/src/structured-step.d.ts +55 -0
  138. package/dist/src/structured-step.js +85 -0
  139. package/dist/src/subagent-run.d.ts +1 -1
  140. package/dist/src/subagent-run.js +29 -33
  141. package/dist/src/telemetry/schema.d.ts +2 -2
  142. package/dist/src/telemetry/schema.js +3 -2
  143. package/dist/src/terminal-ui.d.ts +29 -0
  144. package/dist/src/terminal-ui.js +112 -28
  145. package/dist/src/timers.d.ts +21 -2
  146. package/dist/src/timers.js +12 -4
  147. package/dist/src/tool-names.d.ts +18 -0
  148. package/dist/src/tool-names.js +26 -0
  149. package/dist/src/tools.js +45 -11
  150. package/dist/src/trajectory.js +32 -12
  151. package/dist/src/types.d.ts +23 -0
  152. package/dist/src/update.d.ts +26 -16
  153. package/dist/src/update.js +232 -275
  154. package/docs/agents/install-for-agents.md +15 -24
  155. package/docs/agents/mcp-server.md +13 -1
  156. package/docs/agents/subagent-mode.md +7 -4
  157. package/docs/concepts/security.md +2 -0
  158. package/docs/getting-started/README.md +14 -6
  159. package/docs/getting-started/configure-providers.md +29 -2
  160. package/docs/guides/README.md +1 -1
  161. package/docs/guides/browser.md +12 -0
  162. package/docs/guides/desktop-app.md +45 -9
  163. package/docs/guides/graph-builder.md +8 -0
  164. package/docs/guides/update.md +37 -16
  165. package/docs/reference/cli.md +1 -1
  166. package/docs/reference/config.md +2 -2
  167. package/docs/superpowers/plans/2026-11-06-graph-soft-delete.md +125 -0
  168. package/docs/superpowers/specs/2026-11-01-pr-section-design.md +7 -0
  169. package/docs/superpowers/specs/2026-11-06-bundled-skills-design.md +206 -0
  170. package/package.json +1 -1
  171. package/tests/permissions-test-plan.md +2 -1
@@ -0,0 +1,101 @@
1
+ /**
2
+ * A small CapSolver client: create a task, then poll its result.
3
+ *
4
+ * Only the proxyless task types the browser solve tool uses are modelled. The API key never leaves
5
+ * this module except in the request body sent to CapSolver; error messages never include it.
6
+ */
7
+ export const CAPSOLVER_ENV = 'CAPSOLVER_API_KEY';
8
+ const DEFAULT_BASE_URL = 'https://api.capsolver.com';
9
+ /** CapSolver keeps a task for five minutes and answers 120 result queries; two minutes is ample. */
10
+ const SOLVE_TIMEOUT_MS = 120_000;
11
+ const POLL_INTERVAL_MS = 2_000;
12
+ const REQUEST_TIMEOUT_MS = 30_000;
13
+ /** The key the solve tool uses: the saved one, otherwise the environment's. */
14
+ export function resolveCapsolverKey(config, env = process.env) {
15
+ const saved = config?.browser?.capsolverApiKey;
16
+ if (saved)
17
+ return { key: saved, source: 'config' };
18
+ const fromEnv = env[CAPSOLVER_ENV]?.trim();
19
+ return fromEnv ? { key: fromEnv, source: 'env' } : undefined;
20
+ }
21
+ /**
22
+ * Where requests go. `ANDORRA_CAPSOLVER_BASE_URL` exists so a local stub can stand in for the
23
+ * service during verification; it must be HTTPS, or HTTP on a loopback address, so a stray setting
24
+ * cannot send the key in the clear.
25
+ */
26
+ export function capsolverBaseUrl(env = process.env) {
27
+ const override = env.ANDORRA_CAPSOLVER_BASE_URL?.trim();
28
+ if (!override)
29
+ return DEFAULT_BASE_URL;
30
+ const url = new URL(override);
31
+ const loopback = ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname);
32
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback))
33
+ throw new Error('ANDORRA_CAPSOLVER_BASE_URL must be HTTPS, or HTTP on a loopback address');
34
+ return url.href.replace(/\/+$/, '');
35
+ }
36
+ export class CapsolverError extends Error {
37
+ code;
38
+ constructor(message, code) {
39
+ super(message);
40
+ this.code = code;
41
+ }
42
+ }
43
+ async function call(path, body, options) {
44
+ const doFetch = options.fetch ?? fetch;
45
+ const signal = AbortSignal.any([options.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]);
46
+ let response;
47
+ try {
48
+ response = await doFetch(`${options.baseUrl ?? capsolverBaseUrl()}/${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), signal });
49
+ }
50
+ catch (error) {
51
+ options.signal.throwIfAborted();
52
+ throw new CapsolverError(`CapSolver request failed: ${error instanceof Error ? error.message : String(error)}`.slice(0, 500));
53
+ }
54
+ const raw = await response.text();
55
+ let data;
56
+ try {
57
+ data = JSON.parse(raw);
58
+ }
59
+ catch {
60
+ throw new CapsolverError(`CapSolver answered HTTP ${response.status} without JSON`);
61
+ }
62
+ if (data.errorId) {
63
+ const code = data.errorCode || undefined;
64
+ throw new CapsolverError(`CapSolver refused the task${code ? ` (${code})` : ''}: ${(data.errorDescription || 'no description').slice(0, 400)}`, code);
65
+ }
66
+ if (!response.ok)
67
+ throw new CapsolverError(`CapSolver answered HTTP ${response.status}`);
68
+ return data;
69
+ }
70
+ /** Solve one task and return CapSolver's `solution` object. */
71
+ export async function solveCapsolverTask(key, task, options) {
72
+ const started = Date.now();
73
+ const timeoutMs = options.timeoutMs ?? SOLVE_TIMEOUT_MS;
74
+ const created = await call('createTask', { clientKey: key, task }, options);
75
+ // Recognition tasks (ImageToText) answer synchronously.
76
+ if (created.status === 'ready' && created.solution)
77
+ return created.solution;
78
+ if (!created.taskId)
79
+ throw new CapsolverError('CapSolver returned neither a solution nor a task id');
80
+ const interval = options.pollIntervalMs ?? POLL_INTERVAL_MS;
81
+ for (;;) {
82
+ if (Date.now() - started >= timeoutMs)
83
+ throw new CapsolverError(`CapSolver did not solve the task within ${Math.round(timeoutMs / 1000)} seconds`);
84
+ await new Promise((resolve, reject) => {
85
+ const timer = setTimeout(() => { options.signal.removeEventListener('abort', abort); resolve(); }, interval);
86
+ const abort = () => { clearTimeout(timer); reject(options.signal.reason); };
87
+ if (options.signal.aborted)
88
+ abort();
89
+ else
90
+ options.signal.addEventListener('abort', abort, { once: true });
91
+ });
92
+ const result = await call('getTaskResult', { clientKey: key, taskId: created.taskId }, options);
93
+ if (result.status === 'ready') {
94
+ if (!result.solution || typeof result.solution !== 'object')
95
+ throw new CapsolverError('CapSolver reported the task ready without a solution');
96
+ return result.solution;
97
+ }
98
+ if (result.status === 'failed')
99
+ throw new CapsolverError('CapSolver could not solve the captcha');
100
+ }
101
+ }
@@ -16,6 +16,12 @@ export interface ClaudeDependencies {
16
16
  }
17
17
  /** Bounded subprocess transport. Prompts and images travel only on stdin, never through a shell. */
18
18
  export declare const runClaudeProcess: ClaudeRun;
19
+ /** Whether the CLI holds a Claude subscription login, and the display fields it reports for it. */
20
+ export declare function readClaudeSignIn(signal: AbortSignal, dependencies?: ClaudeDependencies): Promise<{
21
+ signedIn: boolean;
22
+ email?: string;
23
+ planType?: string;
24
+ }>;
19
25
  /** Read the CLI's managed login status and its current supported model catalog without inference. */
20
26
  export declare function readClaudeCatalog(signal: AbortSignal, dependencies?: ClaudeDependencies): Promise<{
21
27
  signedIn: boolean;
@@ -133,7 +133,10 @@ export const runClaudeProcess = async (args, input, signal, options = {}) => {
133
133
  return output;
134
134
  }
135
135
  finally {
136
- await rm(cwd, { recursive: true, force: true });
136
+ // Claude Code's print mode starts short-lived helpers (tasklist, PowerShell, git) in this cwd that
137
+ // can outlive it, and Windows refuses to remove a directory a running process is using. Retry for a
138
+ // few seconds, and never let cleanup of an empty scratch directory replace the CLI's answer or error.
139
+ await rm(cwd, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }).catch(() => { });
137
140
  }
138
141
  };
139
142
  function parseJson(text) {
@@ -145,10 +148,25 @@ function parseJson(text) {
145
148
  }
146
149
  }
147
150
  function frames(text) { return text.split(/\r?\n/).filter(line => line.trim()).map(parseJson); }
148
- async function signedIn(run, signal) {
149
- const status = parseJson(await run(['--safe-mode', '--setting-sources', '', '--settings', '{}', 'auth', 'status', '--json'], '', signal, { acceptedExitCodes: [0, 1] }));
151
+ async function readStatus(run, signal) {
152
+ return parseJson(await run(['--safe-mode', '--setting-sources', '', '--settings', '{}', 'auth', 'status', '--json'], '', signal, { acceptedExitCodes: [0, 1] }));
153
+ }
154
+ function subscriptionLogin(status) {
150
155
  return status?.loggedIn === true && status.authMethod === 'claude.ai' && status.apiProvider === 'firstParty';
151
156
  }
157
+ async function signedIn(run, signal) {
158
+ return subscriptionLogin(await readStatus(run, signal));
159
+ }
160
+ /** Whether the CLI holds a Claude subscription login, and the display fields it reports for it. */
161
+ export async function readClaudeSignIn(signal, dependencies = {}) {
162
+ const status = await readStatus(dependencies.run ?? runClaudeProcess, AbortSignal.any([signal, AbortSignal.timeout(30_000)]));
163
+ if (!subscriptionLogin(status))
164
+ return { signedIn: false };
165
+ const text = (value, max) => typeof value === 'string' && value.length <= max && !/[\u0000-\u001f\u007f]/.test(value) ? value : undefined;
166
+ const email = text(status.email, 320);
167
+ const planType = text(status.subscriptionType, 100);
168
+ return { signedIn: true, ...(email ? { email } : {}), ...(planType ? { planType } : {}) };
169
+ }
152
170
  /** Read the CLI's managed login status and its current supported model catalog without inference. */
153
171
  export async function readClaudeCatalog(signal, dependencies = {}) {
154
172
  const run = dependencies.run ?? runClaudeProcess;
@@ -228,6 +246,7 @@ export function parseClaudeResponse(output, tools = []) {
228
246
  const messageIds = new Set();
229
247
  const texts = [];
230
248
  let schemaResponse;
249
+ let schemaId;
231
250
  for (const event of events.filter(frame => frame?.type === 'assistant')) {
232
251
  if (event.parent_tool_use_id || typeof event.message?.id !== 'string' || !event.message.id || !Array.isArray(event.message.content))
233
252
  throw new Error('Claude returned an invalid assistant step');
@@ -247,6 +266,7 @@ export function parseClaudeResponse(output, tools = []) {
247
266
  if (schemaResponse)
248
267
  throw new Error('Claude returned multiple structured responses');
249
268
  schemaResponse = structuredResponse(block.input, names);
269
+ schemaId = block.id;
250
270
  }
251
271
  else {
252
272
  if (!names.has(block.name))
@@ -261,6 +281,8 @@ export function parseClaudeResponse(output, tools = []) {
261
281
  `<tool_use_error>Error: No such tool available: ${block.name}</tool_use_error>`,
262
282
  `<tool_use_error>Error: No such tool available: ${block.name}.</tool_use_error>`,
263
283
  `<tool_use_error>Error: No such tool available: ${block.name}. ${block.name} is disabled for this session, in subagents as well as here.</tool_use_error>`,
284
+ // Claude Code 2.1.177 words it this way for a native tool name it ships but this session disabled.
285
+ `<tool_use_error>Error: No such tool available: ${block.name}. ${block.name} exists but is not enabled in this context. Use one of the available tools instead.</tool_use_error>`,
264
286
  ];
265
287
  if (observations.length !== 1 || observations[0].is_error !== true || typeof observations[0].content !== 'string'
266
288
  || !unavailable.includes(observations[0].content)) {
@@ -274,9 +296,18 @@ export function parseClaudeResponse(output, tools = []) {
274
296
  throw new Error('Claude returned conflicting structured responses');
275
297
  if (direct.length && structured && !sameCalls(direct, structured.toolCalls))
276
298
  throw new Error('Claude returned conflicting Andorra tool requests');
299
+ // Claude Code counts acknowledging StructuredOutput as a turn, so under --max-turns 1 a complete
300
+ // structured step can end at the turn limit without result.structured_output. Accept that step only
301
+ // when the CLI acknowledged that one StructuredOutput call exactly once and without an error.
302
+ const acknowledgements = schemaId === undefined ? [] : events.filter(frame => frame?.type === 'user')
303
+ .flatMap(frame => Array.isArray(frame.message?.content) ? frame.message.content : [])
304
+ .filter((item) => item?.type === 'tool_result' && item.tool_use_id === schemaId);
305
+ const acknowledged = acknowledgements.length === 1 && acknowledgements[0].is_error !== true;
277
306
  let response;
278
307
  if (success && structured)
279
308
  response = structured;
309
+ else if (turnLimit && structured && result.structured_output === undefined && acknowledged)
310
+ response = structured;
280
311
  else if (turnLimit && direct.length && !structured)
281
312
  response = { text: texts.join('\n'), toolCalls: direct };
282
313
  else
@@ -0,0 +1,33 @@
1
+ /** How to find one vendor CLI that Andorra drives as a subprocess. */
2
+ export interface CliExecutableSpec {
3
+ /** Command names without an extension, tried in order. */
4
+ names: readonly string[];
5
+ /** Names an explicit executable, as a path or as a name looked up on PATH. */
6
+ overrideEnv: string;
7
+ /** Install directories under the user's home that the vendor's own installer uses. */
8
+ homeDirectories?: readonly string[];
9
+ /**
10
+ * The native binary behind a Windows npm shim, relative to the shim's directory. A `.cmd` shim is
11
+ * never executed: it would run through `cmd.exe`, where arguments are reinterpreted.
12
+ */
13
+ shimTargets?: readonly string[];
14
+ /** What the user is told when nothing runnable is found. */
15
+ installMessage: string;
16
+ }
17
+ /** The vendor CLI could not be found; the message says how to install it. */
18
+ export declare class CliUnavailableError extends Error {
19
+ constructor(message: string);
20
+ }
21
+ /**
22
+ * Locate a vendor CLI without ever executing a Windows command shim.
23
+ *
24
+ * The override wins when it is set. A `.js` or `.mjs` override runs with this Node, which is how
25
+ * tests stand a scripted CLI in for the real one.
26
+ */
27
+ export declare function resolveCliExecutable(spec: CliExecutableSpec, options?: {
28
+ platform?: NodeJS.Platform;
29
+ env?: NodeJS.ProcessEnv;
30
+ }): Promise<{
31
+ command: string;
32
+ args: string[];
33
+ }>;
@@ -0,0 +1,64 @@
1
+ import { access } from 'node:fs/promises';
2
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
3
+ async function exists(path) {
4
+ try {
5
+ await access(path);
6
+ return true;
7
+ }
8
+ catch {
9
+ return false;
10
+ }
11
+ }
12
+ /** The vendor CLI could not be found; the message says how to install it. */
13
+ export class CliUnavailableError extends Error {
14
+ constructor(message) { super(message); this.name = 'CliUnavailableError'; }
15
+ }
16
+ /**
17
+ * Locate a vendor CLI without ever executing a Windows command shim.
18
+ *
19
+ * The override wins when it is set. A `.js` or `.mjs` override runs with this Node, which is how
20
+ * tests stand a scripted CLI in for the real one.
21
+ */
22
+ export async function resolveCliExecutable(spec, options = {}) {
23
+ const platform = options.platform ?? process.platform;
24
+ const env = options.env ?? process.env;
25
+ const pathValue = Object.entries(env).find(([key]) => key.toLowerCase() === 'path')?.[1] ?? '';
26
+ const directories = pathValue.split(platform === 'win32' ? ';' : ':').filter(Boolean).map(value => value.replace(/^"|"$/g, ''));
27
+ const executableName = (name) => platform === 'win32' ? `${name}.exe` : name;
28
+ const candidates = [];
29
+ const override = env[spec.overrideEnv];
30
+ if (override) {
31
+ if (isAbsolute(override) || /[\\/]/.test(override))
32
+ candidates.push(resolve(override));
33
+ else
34
+ for (const directory of directories)
35
+ candidates.push(join(directory, override));
36
+ }
37
+ else {
38
+ const home = env.USERPROFILE ?? env.HOME;
39
+ for (const name of spec.names) {
40
+ if (home)
41
+ for (const directory of spec.homeDirectories ?? [])
42
+ candidates.push(join(home, directory, executableName(name)));
43
+ for (const directory of directories)
44
+ candidates.push(join(directory, executableName(name)));
45
+ if (platform === 'win32')
46
+ for (const directory of directories)
47
+ candidates.push(join(directory, `${name}.cmd`));
48
+ }
49
+ }
50
+ for (const candidate of candidates) {
51
+ if (!await exists(candidate))
52
+ continue;
53
+ if (/\.m?js$/i.test(candidate))
54
+ return { command: process.execPath, args: [candidate] };
55
+ if (!/\.(?:cmd|bat|ps1)$/i.test(candidate))
56
+ return { command: candidate, args: [] };
57
+ for (const target of spec.shimTargets ?? []) {
58
+ const binary = join(dirname(candidate), target);
59
+ if (await exists(binary))
60
+ return { command: binary, args: [] };
61
+ }
62
+ }
63
+ throw new CliUnavailableError(spec.installMessage);
64
+ }
@@ -0,0 +1,47 @@
1
+ import { type ChildProcess } from 'node:child_process';
2
+ /**
3
+ * Stop a child and everything it started.
4
+ *
5
+ * Vendor CLIs ship as launchers that start a native binary, so killing the direct child alone leaves
6
+ * the binary running and holding its port or its lock. Windows needs `taskkill /T`; elsewhere the
7
+ * child leads its own process group, which can outlive the launcher: the group is signalled even
8
+ * when the direct child has already exited, or a descendant keeps the pipes open.
9
+ *
10
+ * Every pipe is then closed on this side, so a caller waiting for `close` settles even when a
11
+ * descendant survived (on Windows, `taskkill /T` cannot reach one whose parent already exited).
12
+ */
13
+ export declare function stopProcessTree(child: ChildProcess, taskkill: string | undefined): Promise<void>;
14
+ export interface BoundedCliOptions {
15
+ /** The complete child environment; callers build it from their own sanitizer. */
16
+ env: NodeJS.ProcessEnv;
17
+ /** The product name errors name, e.g. `Grok CLI`. */
18
+ label: string;
19
+ /** Written to stdin, then stdin is closed. */
20
+ input?: string;
21
+ /** Files written into the private working directory before the child starts. */
22
+ files?: Record<string, string>;
23
+ outputLimit?: number;
24
+ acceptedExitCodes?: number[];
25
+ /**
26
+ * Return stderr alongside stdout. Off by default: CLIs print account details and credential
27
+ * fragments there, so only callers that parse a known status line ask for it.
28
+ */
29
+ captureStderr?: boolean;
30
+ }
31
+ export interface BoundedCliResult {
32
+ stdout: string;
33
+ stderr: string;
34
+ code: number | null;
35
+ cwd: string;
36
+ }
37
+ /**
38
+ * Run one vendor CLI command in a private, empty working directory under a byte bound.
39
+ *
40
+ * Arguments never pass through a shell. The directory is removed afterwards, so a prompt written
41
+ * there for `--prompt-file` does not outlive the request. Cancellation and the output bound stop the
42
+ * whole process tree.
43
+ */
44
+ export declare function runBoundedCli(executable: {
45
+ command: string;
46
+ args: string[];
47
+ }, args: (cwd: string) => string[], signal: AbortSignal, options: BoundedCliOptions): Promise<BoundedCliResult>;
@@ -0,0 +1,113 @@
1
+ import { execFile, spawn } from 'node:child_process';
2
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { promisify } from 'node:util';
6
+ import { resolveTrustedTaskkill } from './shell.js';
7
+ const executeFile = promisify(execFile);
8
+ const DEFAULT_OUTPUT_LIMIT = 8 * 1024 * 1024;
9
+ /**
10
+ * Stop a child and everything it started.
11
+ *
12
+ * Vendor CLIs ship as launchers that start a native binary, so killing the direct child alone leaves
13
+ * the binary running and holding its port or its lock. Windows needs `taskkill /T`; elsewhere the
14
+ * child leads its own process group, which can outlive the launcher: the group is signalled even
15
+ * when the direct child has already exited, or a descendant keeps the pipes open.
16
+ *
17
+ * Every pipe is then closed on this side, so a caller waiting for `close` settles even when a
18
+ * descendant survived (on Windows, `taskkill /T` cannot reach one whose parent already exited).
19
+ */
20
+ export async function stopProcessTree(child, taskkill) {
21
+ if (child.pid) {
22
+ const exited = child.exitCode !== null || child.signalCode !== null;
23
+ if (taskkill) {
24
+ if (!exited) {
25
+ try {
26
+ await executeFile(taskkill, ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, timeout: 20_000 });
27
+ }
28
+ catch {
29
+ child.kill('SIGKILL');
30
+ }
31
+ }
32
+ }
33
+ else {
34
+ try {
35
+ process.kill(-child.pid, 'SIGKILL');
36
+ }
37
+ catch {
38
+ if (!exited)
39
+ child.kill('SIGKILL');
40
+ }
41
+ }
42
+ }
43
+ for (const stream of [child.stdin, child.stdout, child.stderr])
44
+ stream?.destroy();
45
+ }
46
+ /**
47
+ * Run one vendor CLI command in a private, empty working directory under a byte bound.
48
+ *
49
+ * Arguments never pass through a shell. The directory is removed afterwards, so a prompt written
50
+ * there for `--prompt-file` does not outlive the request. Cancellation and the output bound stop the
51
+ * whole process tree.
52
+ */
53
+ export async function runBoundedCli(executable, args, signal, options) {
54
+ signal.throwIfAborted();
55
+ const cwd = await mkdtemp(join(tmpdir(), 'andorra-cli-'));
56
+ try {
57
+ for (const [name, content] of Object.entries(options.files ?? {})) {
58
+ if (!/^[\w.-]+$/.test(name))
59
+ throw new Error('Invalid CLI working file name');
60
+ await writeFile(join(cwd, name), content, { mode: 0o600 });
61
+ }
62
+ const taskkill = process.platform === 'win32' ? await resolveTrustedTaskkill(cwd) : undefined;
63
+ signal.throwIfAborted();
64
+ const child = spawn(executable.command, [...executable.args, ...args(cwd)], { cwd, env: options.env, windowsHide: true, shell: false,
65
+ detached: process.platform !== 'win32', stdio: 'pipe' });
66
+ let stdout = '';
67
+ let stderr = '';
68
+ let bytes = 0;
69
+ let failure;
70
+ let stopping;
71
+ const stop = () => stopping ??= stopProcessTree(child, taskkill);
72
+ const abort = () => { failure ??= new Error(signal.reason?.name === 'TimeoutError' ? `${options.label} timed out` : `${options.label} request cancelled`); void stop(); };
73
+ const limit = options.outputLimit ?? DEFAULT_OUTPUT_LIMIT;
74
+ let code = null;
75
+ await new Promise((resolve, reject) => {
76
+ child.once('error', () => { failure ??= new Error(`Could not start the ${options.label}`); });
77
+ child.once('close', exitCode => {
78
+ code = exitCode;
79
+ signal.removeEventListener('abort', abort);
80
+ if (failure)
81
+ reject(failure);
82
+ else if (!(options.acceptedExitCodes ?? [0]).includes(exitCode ?? -1))
83
+ reject(new Error(`${options.label} failed. Check its sign-in and selected model.`));
84
+ else
85
+ resolve();
86
+ });
87
+ const count = (chunk) => {
88
+ bytes += Buffer.byteLength(chunk);
89
+ if (bytes <= limit)
90
+ return true;
91
+ failure ??= new Error(`${options.label} output exceeded the safety limit`);
92
+ void stop();
93
+ return false;
94
+ };
95
+ child.stdout.setEncoding('utf8');
96
+ child.stderr.setEncoding('utf8');
97
+ child.stdout.on('data', (text) => { if (count(text))
98
+ stdout += text; });
99
+ child.stderr.on('data', (text) => { if (count(text) && options.captureStderr)
100
+ stderr += text; });
101
+ child.stdin.on('error', () => { failure ??= new Error(`${options.label} closed its input unexpectedly`); void stop(); });
102
+ signal.addEventListener('abort', abort, { once: true });
103
+ if (signal.aborted)
104
+ abort();
105
+ else
106
+ child.stdin.end(options.input ?? '');
107
+ }).finally(async () => { signal.removeEventListener('abort', abort); await stopping; });
108
+ return { stdout, stderr, code, cwd };
109
+ }
110
+ finally {
111
+ await rm(cwd, { recursive: true, force: true }).catch(() => { });
112
+ }
113
+ }
@@ -0,0 +1,68 @@
1
+ /** What a sign-in panel shows; every field is display data, never a credential. */
2
+ export interface ManagedSignInState {
3
+ state: 'signedOut' | 'starting' | 'waiting' | 'signedIn' | 'cancelled' | 'error';
4
+ reason?: 'unavailable' | 'timeout' | 'denied' | 'unsupported' | 'busy' | 'unverified' | 'logoutFailed';
5
+ attemptId?: string;
6
+ message?: string;
7
+ email?: string;
8
+ planType?: string;
9
+ /** The vendor's sign-in page. Only the start request that began the attempt carries it. */
10
+ authUrl?: string;
11
+ /** A device code the person confirms on that page. */
12
+ userCode?: string;
13
+ /** The vendor may show a code the person pastes back here instead of redirecting. */
14
+ acceptsCode?: boolean;
15
+ }
16
+ /** One vendor CLI whose own login command Andorra runs and whose stored login it reads back. */
17
+ export interface CliSignInSpec {
18
+ /** The product name messages use, e.g. `Claude` or `Grok`. */
19
+ product: string;
20
+ resolveExecutable(): Promise<{
21
+ command: string;
22
+ args: string[];
23
+ }>;
24
+ env(): NodeJS.ProcessEnv;
25
+ loginArgs: readonly string[];
26
+ logoutArgs: readonly string[];
27
+ /** Read the CLI's stored login, without inference. */
28
+ status(signal: AbortSignal): Promise<{
29
+ signedIn: boolean;
30
+ email?: string;
31
+ planType?: string;
32
+ }>;
33
+ /** Hosts a sign-in page may be on; any other URL the CLI prints is withheld. */
34
+ pageHosts: readonly string[];
35
+ /** The CLI prints a device code the person confirms on the page. */
36
+ deviceCode?: boolean;
37
+ /** Whether the CLI reads a pasted code from stdin while it waits. */
38
+ acceptsCode?: boolean;
39
+ timeoutMs?: number;
40
+ }
41
+ /** The first sign-in page and device code in what the CLI printed, held to the allowed hosts. */
42
+ export declare function readSignInPrompt(output: string, pageHosts: readonly string[]): {
43
+ authUrl?: string;
44
+ userCode?: string;
45
+ };
46
+ /**
47
+ * Runs one vendor CLI's own login command and reports what it left behind.
48
+ *
49
+ * The browser ceremony and the tokens belong to the vendor CLI, which stores them where it always
50
+ * does; Andorra never reads or copies them. This class starts the command, surfaces the page and
51
+ * code it prints, forwards a pasted code, stops it on cancel, and asks the CLI who is signed in.
52
+ */
53
+ export declare class CliSignIn {
54
+ private readonly spec;
55
+ private attempt?;
56
+ private closed;
57
+ constructor(spec: CliSignInSpec);
58
+ private failed;
59
+ start(attemptId: string): Promise<ManagedSignInState>;
60
+ /** Forward a code the sign-in page showed to the waiting CLI. */
61
+ submitCode(attemptId: string, code: string): Promise<ManagedSignInState>;
62
+ status(attemptId?: string): Promise<ManagedSignInState>;
63
+ cancel(attemptId: string): Promise<ManagedSignInState>;
64
+ /** Run the CLI's own sign-out, then report what its stored login now says. */
65
+ logout(): Promise<ManagedSignInState>;
66
+ private stop;
67
+ close(): Promise<void>;
68
+ }