@andorra-labs/code 0.1.5 → 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 (164) 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 +53 -22
  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/docs/agents/mcp-server.md +13 -1
  153. package/docs/agents/subagent-mode.md +7 -4
  154. package/docs/concepts/security.md +2 -0
  155. package/docs/getting-started/configure-providers.md +29 -2
  156. package/docs/guides/browser.md +12 -0
  157. package/docs/guides/desktop-app.md +10 -3
  158. package/docs/guides/graph-builder.md +8 -0
  159. package/docs/reference/config.md +2 -2
  160. package/docs/superpowers/plans/2026-11-06-graph-soft-delete.md +125 -0
  161. package/docs/superpowers/specs/2026-11-01-pr-section-design.md +7 -0
  162. package/docs/superpowers/specs/2026-11-06-bundled-skills-design.md +206 -0
  163. package/package.json +1 -1
  164. package/tests/permissions-test-plan.md +2 -1
@@ -5,6 +5,8 @@ import { readOpenCodeModels } from './opencode-catalog.js';
5
5
  import { readCodexCatalog } from './codex-provider.js';
6
6
  import { codexConnectFor } from './codex-rpc.js';
7
7
  import { readClaudeCatalog } from './claude-provider.js';
8
+ import { readGrokCatalog } from './grok-provider.js';
9
+ import { readOpenCodeCatalog } from './opencode-cli-provider.js';
8
10
  /** Resolve metadata for a specific model without borrowing another model's saved limit. */
9
11
  export async function resolveModelContext(provider, model, signal) {
10
12
  return refreshModelContext(configuredModelSnapshot(provider, model), signal);
@@ -47,7 +49,7 @@ export function withEvaluationReasoningEffort(snapshot, effort) {
47
49
  export async function refreshModelContext(provider, signal) {
48
50
  const snapshot = configuredModelSnapshot(provider, undefined);
49
51
  signal.throwIfAborted();
50
- if (snapshot.type === 'codex' || snapshot.type === 'claude')
52
+ if (snapshot.type === 'codex' || snapshot.type === 'claude' || snapshot.type === 'grok')
51
53
  return snapshot;
52
54
  try {
53
55
  const models = await discoverModelMetadata(snapshot, signal);
@@ -102,6 +104,14 @@ export async function discoverModelMetadata(provider, signal) {
102
104
  return (await readCodexCatalog(signal, codexConnectFor(provider))).models.map(id => ({ id }));
103
105
  if (provider.type === 'claude')
104
106
  return (await readClaudeCatalog(signal)).models.map(id => ({ id }));
107
+ if (provider.type === 'grok') {
108
+ const catalog = await readGrokCatalog(signal);
109
+ if (!catalog.signedIn)
110
+ throw new Error('Sign in to Grok on this machine before listing its models.');
111
+ return catalog.models.map(id => ({ id }));
112
+ }
113
+ if (provider.type === 'opencode')
114
+ return (await readOpenCodeCatalog(signal)).models.map(model => ({ id: model.id, ...(model.contextWindow ? { contextWindow: model.contextWindow } : {}) }));
105
115
  if (provider.type === 'opencode-go')
106
116
  return readOpenCodeModels(signal, fetch, provider.requestTimeoutMs);
107
117
  // A listing is bounded by the same ceiling the adapter uses, and by a provider that asked for
@@ -252,8 +262,10 @@ export async function discoverModelMetadata(provider, signal) {
252
262
  }
253
263
  }
254
264
  signal.throwIfAborted();
265
+ // A catalog with any SparkDeck entry is a SparkDeck server, which has no LM Studio
266
+ // listing; its other entries (embedding models under their upstream owner) stay unknown.
255
267
  if (provider.type === 'openai-compatible' && base.hostname !== 'api.openai.com' && /\/v1\/?$/.test(base.pathname)
256
- && models.some(model => model.contextWindow === undefined && !sparkdeckModels.has(model.id))) {
268
+ && sparkdeckModels.size === 0 && models.some(model => model.contextWindow === undefined)) {
257
269
  // Optional LM Studio native metadata, confined to the same origin/path
258
270
  // prefix. No redirect following, extra credentials, or broad server probes.
259
271
  const native = new URL(base);
@@ -29,6 +29,16 @@ export declare function pinnedModelSelections(graph: Graph): PinnedModelSelectio
29
29
  * retry fallback would return to the graph's own choice after a failure.
30
30
  */
31
31
  export declare function applyModelOverride(graph: Graph, target: ModelOverrideTarget): Graph;
32
+ /**
33
+ * The graph with the named nodes carrying the given pairs, as a run-scoped copy like
34
+ * `applyModelOverride`.
35
+ *
36
+ * Only the node's own field is written: a delegation policy or a role that pins its own pair keeps
37
+ * it, and an unpinned child inherits the node's new pair because the child resolves against its
38
+ * parent. A retry fallback keeps the graph's choice, so a failed attempt still has somewhere
39
+ * resilient to land.
40
+ */
41
+ export declare function applyNodeModelOverrides(graph: Graph, targets: Record<string, ModelOverrideTarget>): Graph;
32
42
  /** Pin every agent node to the target profile, make every delegation follow its node, and point every retry fallback at it too. */
33
43
  export declare function overrideModelSelections(graph: Graph, target: ModelOverrideTarget): void;
34
44
  export type ModelOverrideOutcome = {
@@ -69,6 +69,26 @@ export function applyModelOverride(graph, target) {
69
69
  }
70
70
  return copy;
71
71
  }
72
+ /**
73
+ * The graph with the named nodes carrying the given pairs, as a run-scoped copy like
74
+ * `applyModelOverride`.
75
+ *
76
+ * Only the node's own field is written: a delegation policy or a role that pins its own pair keeps
77
+ * it, and an unpinned child inherits the node's new pair because the child resolves against its
78
+ * parent. A retry fallback keeps the graph's choice, so a failed attempt still has somewhere
79
+ * resilient to land.
80
+ */
81
+ export function applyNodeModelOverrides(graph, targets) {
82
+ const copy = structuredClone(graph);
83
+ for (const [id, target] of Object.entries(targets)) {
84
+ const node = copy.nodes[id];
85
+ if (node?.type !== 'agent')
86
+ continue;
87
+ node.provider = target.provider;
88
+ node.model = target.model;
89
+ }
90
+ return copy;
91
+ }
72
92
  /** Pin every agent node to the target profile, make every delegation follow its node, and point every retry fallback at it too. */
73
93
  export function overrideModelSelections(graph, target) {
74
94
  for (const node of Object.values(graph.nodes)) {
@@ -0,0 +1,122 @@
1
+ import { type CliExecutableSpec } from './cli-executable.js';
2
+ import { parseStructuredStep } from './structured-step.js';
3
+ import type { ModelAdapter, ModelResponse } from './types.js';
4
+ /** A marker, not an endpoint: requests go through a local OpenCode server this engine starts. */
5
+ export declare const OPENCODE_BASE_URL = "https://opencode.ai";
6
+ export declare const OPENCODE_EXECUTABLE: CliExecutableSpec;
7
+ /**
8
+ * The configuration layered over the user's own for every server this engine starts.
9
+ *
10
+ * The user's connected providers and credentials stay as OpenCode stores them. Andorra adds two
11
+ * agents with every built-in tool off: the structured one keeps only OpenCode's StructuredOutput
12
+ * tool, which is how a JSON-schema answer is returned. Snapshots, sharing and updates are off so a
13
+ * request cannot snapshot a repository, publish a session, or upgrade the CLI underneath a run.
14
+ */
15
+ export declare function openCodeServerConfig(): Record<string, unknown>;
16
+ export interface OpenCodeServerLike {
17
+ request(path: string, init: {
18
+ method?: string;
19
+ body?: unknown;
20
+ signal: AbortSignal;
21
+ }): Promise<{
22
+ status: number;
23
+ body: unknown;
24
+ }>;
25
+ close(): Promise<void>;
26
+ }
27
+ /**
28
+ * One `opencode serve` child, started on first use and stopped after it has been idle a while.
29
+ *
30
+ * It listens on loopback behind a random password, so another local process cannot drive the
31
+ * user's OpenCode accounts through it. The child is detached from this process's event loop: a CLI
32
+ * run that finishes exits normally, and the exit hook stops the server tree on the way out.
33
+ */
34
+ export declare class OpenCodeServer implements OpenCodeServerLike {
35
+ private readonly options;
36
+ private starting?;
37
+ private child?;
38
+ private cwd?;
39
+ private taskkill?;
40
+ private idle?;
41
+ private active;
42
+ private readonly exitHook;
43
+ constructor(options?: {
44
+ resolveExecutable?: () => Promise<{
45
+ command: string;
46
+ args: string[];
47
+ }>;
48
+ env?: NodeJS.ProcessEnv;
49
+ idleStopMs?: number;
50
+ });
51
+ private start;
52
+ request(path: string, init: {
53
+ method?: string;
54
+ body?: unknown;
55
+ signal: AbortSignal;
56
+ }): Promise<{
57
+ status: number;
58
+ body: unknown;
59
+ }>;
60
+ private killNow;
61
+ private stop;
62
+ close(): Promise<void>;
63
+ }
64
+ /** The one server this process drives OpenCode through. */
65
+ export declare function sharedOpenCodeServer(): OpenCodeServer;
66
+ export interface OpenCodeModelEntry {
67
+ id: string;
68
+ name?: string;
69
+ contextWindow?: number;
70
+ }
71
+ export interface OpenCodeCatalog {
72
+ available: boolean;
73
+ connected: {
74
+ id: string;
75
+ name: string;
76
+ }[];
77
+ models: OpenCodeModelEntry[];
78
+ }
79
+ /** The providers OpenCode has connected and every model they serve, named `provider/model`. */
80
+ export declare function readOpenCodeCatalog(signal: AbortSignal, server?: OpenCodeServerLike): Promise<OpenCodeCatalog>;
81
+ /** Validate a prompt reply: one assistant message, no native tool other than structured output. */
82
+ export declare function parseOpenCodeReply(body: unknown, tools: Parameters<typeof parseStructuredStep>[1], providerID: string, structured: boolean): ModelResponse;
83
+ export interface OpenCodeDependencies {
84
+ server?: OpenCodeServerLike;
85
+ retryPollMs?: number;
86
+ }
87
+ /**
88
+ * OpenCode produces one model response through whichever provider the model names; Andorra owns
89
+ * tool execution, graph state, and permissions. Each request is its own throwaway session.
90
+ */
91
+ export declare function createOpenCodeCliAdapter(_config: {
92
+ model: string;
93
+ }, dependencies?: OpenCodeDependencies): ModelAdapter;
94
+ /** One way OpenCode can sign in to an upstream provider from a browser. */
95
+ export interface OpenCodeSignInOption {
96
+ providerId: string;
97
+ providerName: string;
98
+ method: number;
99
+ label: string;
100
+ connected: boolean;
101
+ }
102
+ /**
103
+ * The browser sign-ins OpenCode offers, with the inputs Andorra can answer itself.
104
+ *
105
+ * A method that asks a free-text question (an enterprise URL, an account ID) needs OpenCode's own
106
+ * prompt, so it is left out; a method whose only questions are selections takes their first,
107
+ * public option.
108
+ */
109
+ export declare function listOpenCodeSignIns(signal: AbortSignal, server?: OpenCodeServerLike): Promise<OpenCodeSignInOption[]>;
110
+ /** Answers for a method's prompts, or `undefined` when one needs typed input. */
111
+ export declare function openCodeInputs(entry: Record<string, any>): Record<string, string> | undefined;
112
+ export interface OpenCodeAuthorization {
113
+ url: string;
114
+ method: 'auto' | 'code';
115
+ instructions?: string;
116
+ }
117
+ /** Begin one provider's browser sign-in inside OpenCode; the server keeps the pending exchange. */
118
+ export declare function authorizeOpenCode(providerId: string, method: number, signal: AbortSignal, server?: OpenCodeServerLike): Promise<OpenCodeAuthorization>;
119
+ /** Finish a sign-in: `auto` waits for OpenCode's own callback, `code` submits what the page showed. */
120
+ export declare function completeOpenCode(providerId: string, method: number, code: string | undefined, signal: AbortSignal, server?: OpenCodeServerLike): Promise<boolean>;
121
+ /** Remove one upstream provider's stored OpenCode credential. */
122
+ export declare function signOutOpenCode(providerId: string, signal: AbortSignal, server?: OpenCodeServerLike): Promise<boolean>;
@@ -0,0 +1,415 @@
1
+ import { spawn, spawnSync } from 'node:child_process';
2
+ import { randomBytes } from 'node:crypto';
3
+ import { mkdtemp, rm } from 'node:fs/promises';
4
+ import { tmpdir } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { resolveCliExecutable } from './cli-executable.js';
7
+ import { stopProcessTree } from './cli-process.js';
8
+ import { resolveTrustedTaskkill } from './shell.js';
9
+ import { allowanceInstruction, boundTextStep, parseStructuredStep, STRUCTURED_STEP_PROMPT, STRUCTURED_STEP_SCHEMA, structuredStepPrompt, TEXT_STEP_PROMPT } from './structured-step.js';
10
+ /** A marker, not an endpoint: requests go through a local OpenCode server this engine starts. */
11
+ export const OPENCODE_BASE_URL = 'https://opencode.ai';
12
+ export const OPENCODE_EXECUTABLE = {
13
+ names: ['opencode'], overrideEnv: 'ANDORRA_OPENCODE_PATH', homeDirectories: [join('.opencode', 'bin')],
14
+ shimTargets: [join('node_modules', 'opencode-ai', 'bin', 'opencode.exe'), join('node_modules', 'opencode-ai', 'bin', 'opencode')],
15
+ installMessage: 'Install the OpenCode CLI (npm install -g opencode-ai), then retry the OpenCode provider.',
16
+ };
17
+ const START_TIMEOUT_MS = 60_000;
18
+ const IDLE_STOP_MS = 5 * 60_000;
19
+ const REQUEST_TIMEOUT_MS = 10 * 60_000;
20
+ const CATALOG_TIMEOUT_MS = 30_000;
21
+ const RETRY_POLL_MS = 2_000;
22
+ const STRUCTURED_AGENT = 'andorra';
23
+ const TEXT_AGENT = 'andorra-text';
24
+ /**
25
+ * The configuration layered over the user's own for every server this engine starts.
26
+ *
27
+ * The user's connected providers and credentials stay as OpenCode stores them. Andorra adds two
28
+ * agents with every built-in tool off: the structured one keeps only OpenCode's StructuredOutput
29
+ * tool, which is how a JSON-schema answer is returned. Snapshots, sharing and updates are off so a
30
+ * request cannot snapshot a repository, publish a session, or upgrade the CLI underneath a run.
31
+ */
32
+ export function openCodeServerConfig() {
33
+ return {
34
+ snapshot: false, share: 'disabled', autoupdate: false,
35
+ agent: {
36
+ [STRUCTURED_AGENT]: { mode: 'primary', prompt: STRUCTURED_STEP_PROMPT, tools: { '*': false, StructuredOutput: true }, permission: { '*': 'deny' } },
37
+ [TEXT_AGENT]: { mode: 'primary', prompt: TEXT_STEP_PROMPT, tools: { '*': false }, permission: { '*': 'deny' } },
38
+ },
39
+ };
40
+ }
41
+ /**
42
+ * One `opencode serve` child, started on first use and stopped after it has been idle a while.
43
+ *
44
+ * It listens on loopback behind a random password, so another local process cannot drive the
45
+ * user's OpenCode accounts through it. The child is detached from this process's event loop: a CLI
46
+ * run that finishes exits normally, and the exit hook stops the server tree on the way out.
47
+ */
48
+ export class OpenCodeServer {
49
+ options;
50
+ starting;
51
+ child;
52
+ cwd;
53
+ taskkill;
54
+ idle;
55
+ active = 0;
56
+ exitHook = () => this.killNow();
57
+ constructor(options = {}) {
58
+ this.options = options;
59
+ }
60
+ async start() {
61
+ const executable = await (this.options.resolveExecutable ?? (() => resolveCliExecutable(OPENCODE_EXECUTABLE)))();
62
+ const password = randomBytes(24).toString('hex');
63
+ const cwd = await mkdtemp(join(tmpdir(), 'andorra-opencode-'));
64
+ this.cwd = cwd;
65
+ const source = this.options.env ?? process.env;
66
+ const env = Object.fromEntries(Object.entries(source).filter(([key]) => !/^(?:NODE_OPTIONS|OPENCODE_SERVER_(?:PASSWORD|USERNAME)|OPENCODE_CONFIG_CONTENT)$/i.test(key)));
67
+ env.OPENCODE_SERVER_PASSWORD = password;
68
+ env.OPENCODE_CONFIG_CONTENT = JSON.stringify(openCodeServerConfig());
69
+ if (process.platform === 'win32')
70
+ this.taskkill = await resolveTrustedTaskkill(cwd).catch(() => undefined);
71
+ const child = spawn(executable.command, [...executable.args, 'serve', '--port', '0', '--hostname', '127.0.0.1', '--pure'], {
72
+ cwd, env, windowsHide: true, shell: false, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe'],
73
+ });
74
+ this.child = child;
75
+ process.once('exit', this.exitHook);
76
+ const url = await new Promise((resolve, reject) => {
77
+ let seen = '';
78
+ const timer = setTimeout(() => reject(new Error('The OpenCode server did not start in time.')), START_TIMEOUT_MS);
79
+ const read = (chunk) => {
80
+ // Only the listening line is read; the rest of the log is drained and dropped.
81
+ if (seen.length < 64 * 1024)
82
+ seen += chunk.toString('utf8');
83
+ const match = seen.match(/listening on (http:\/\/127\.0\.0\.1:\d+)/);
84
+ if (match) {
85
+ clearTimeout(timer);
86
+ resolve(match[1]);
87
+ }
88
+ };
89
+ child.stdout.on('data', read);
90
+ child.stderr.on('data', read);
91
+ child.once('error', () => { clearTimeout(timer); reject(new Error(OPENCODE_EXECUTABLE.installMessage)); });
92
+ child.once('exit', () => { clearTimeout(timer); reject(new Error('The OpenCode server exited before it was ready.')); });
93
+ }).catch(async (error) => { await this.stop(); throw error; });
94
+ child.once('exit', () => { if (this.child === child)
95
+ void this.stop(); });
96
+ child.unref();
97
+ child.stdout.unref?.();
98
+ child.stderr.unref?.();
99
+ return { url, auth: `Basic ${Buffer.from(`opencode:${password}`).toString('base64')}` };
100
+ }
101
+ async request(path, init) {
102
+ init.signal.throwIfAborted();
103
+ this.active++;
104
+ clearTimeout(this.idle);
105
+ try {
106
+ const server = await (this.starting ??= this.start().catch(error => { this.starting = undefined; throw error; }));
107
+ init.signal.throwIfAborted();
108
+ const response = await fetch(`${server.url}${path}`, {
109
+ method: init.method ?? 'GET', signal: init.signal, redirect: 'error',
110
+ headers: { authorization: server.auth, ...(init.body === undefined ? {} : { 'content-type': 'application/json' }) },
111
+ ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),
112
+ });
113
+ const text = await response.text();
114
+ let body = text;
115
+ try {
116
+ body = text ? JSON.parse(text) : undefined;
117
+ }
118
+ catch { /* non-JSON bodies are reported by status */ }
119
+ return { status: response.status, body };
120
+ }
121
+ finally {
122
+ this.active--;
123
+ if (this.active === 0) {
124
+ this.idle = setTimeout(() => { void this.stop(); }, this.options.idleStopMs ?? IDLE_STOP_MS);
125
+ this.idle.unref?.();
126
+ }
127
+ }
128
+ }
129
+ killNow() {
130
+ const child = this.child;
131
+ if (!child?.pid || child.exitCode !== null)
132
+ return;
133
+ if (this.taskkill)
134
+ spawnSync(this.taskkill, ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, timeout: 10_000 });
135
+ else {
136
+ try {
137
+ process.kill(-child.pid, 'SIGKILL');
138
+ }
139
+ catch {
140
+ child.kill('SIGKILL');
141
+ }
142
+ }
143
+ }
144
+ async stop() {
145
+ clearTimeout(this.idle);
146
+ const child = this.child;
147
+ const cwd = this.cwd;
148
+ this.child = undefined;
149
+ this.cwd = undefined;
150
+ this.starting = undefined;
151
+ process.removeListener('exit', this.exitHook);
152
+ if (child)
153
+ await stopProcessTree(child, this.taskkill);
154
+ if (cwd)
155
+ await rm(cwd, { recursive: true, force: true }).catch(() => { });
156
+ }
157
+ async close() { await this.stop(); }
158
+ }
159
+ let shared;
160
+ /** The one server this process drives OpenCode through. */
161
+ export function sharedOpenCodeServer() { return shared ??= new OpenCodeServer(); }
162
+ function object(value) {
163
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
164
+ }
165
+ /** Short, single-line text from the server, for messages that name what went wrong upstream. */
166
+ function note(value) {
167
+ if (typeof value !== 'string')
168
+ return undefined;
169
+ const line = value.replace(/[\u0000-\u001f\u007f]+/g, ' ').trim();
170
+ return line ? (line.length > 200 ? `${line.slice(0, 199)}…` : line) : undefined;
171
+ }
172
+ /** The providers OpenCode has connected and every model they serve, named `provider/model`. */
173
+ export async function readOpenCodeCatalog(signal, server = sharedOpenCodeServer()) {
174
+ const bounded = AbortSignal.any([signal, AbortSignal.timeout(CATALOG_TIMEOUT_MS)]);
175
+ const reply = await server.request('/provider', { signal: bounded });
176
+ const body = object(reply.body);
177
+ if (reply.status !== 200 || !body || !Array.isArray(body.all) || !Array.isArray(body.connected))
178
+ throw new Error('OpenCode did not return its provider catalog.');
179
+ const connectedIds = new Set(body.connected.filter((id) => typeof id === 'string'));
180
+ const connected = [];
181
+ const models = [];
182
+ for (const raw of body.all) {
183
+ const provider = object(raw);
184
+ if (!provider || typeof provider.id !== 'string' || !connectedIds.has(provider.id) || !/^[\w.@-]{1,100}$/.test(provider.id))
185
+ continue;
186
+ connected.push({ id: provider.id, name: note(provider.name) ?? provider.id });
187
+ for (const [modelId, rawModel] of Object.entries(object(provider.models) ?? {})) {
188
+ const model = object(rawModel);
189
+ if (!modelId.trim() || modelId.length > 400 || model?.status === 'deprecated')
190
+ continue;
191
+ const window = model?.limit?.context;
192
+ models.push({ id: `${provider.id}/${modelId}`, ...(note(model?.name) ? { name: note(model?.name) } : {}),
193
+ ...(Number.isSafeInteger(window) && window > 0 ? { contextWindow: window } : {}) });
194
+ if (models.length >= 5000)
195
+ break;
196
+ }
197
+ }
198
+ return { available: true, connected, models };
199
+ }
200
+ /** `provider/model`: the provider id never contains a slash, while model ids may. */
201
+ function splitModel(model) {
202
+ const slash = model.indexOf('/');
203
+ if (slash <= 0 || slash === model.length - 1)
204
+ throw new Error('OpenCode models are named provider/model. Choose one from Discover Models.');
205
+ return { providerID: model.slice(0, slash), modelID: model.slice(slash + 1) };
206
+ }
207
+ function usage(tokens) {
208
+ const count = (value) => Number.isSafeInteger(value) && value >= 0 ? value : undefined;
209
+ const input = count(tokens?.input);
210
+ const output = count(tokens?.output);
211
+ const reasoning = count(tokens?.reasoning);
212
+ const read = count(tokens?.cache?.read);
213
+ const write = count(tokens?.cache?.write);
214
+ if (input === undefined && output === undefined)
215
+ return { requests: 1 };
216
+ return { requests: 1,
217
+ ...(input === undefined ? {} : { inputTokens: input + (read ?? 0) + (write ?? 0) }),
218
+ ...(output === undefined ? {} : { outputTokens: output + (reasoning ?? 0) }),
219
+ // Presence, not positivity: count() answers undefined for an unreported or malformed counter,
220
+ // and an explicit zero is a cold-cache measurement the local cache aggregate counts.
221
+ ...(read === undefined ? {} : { cacheRead: read }), ...(write === undefined ? {} : { cacheWrite: write }) };
222
+ }
223
+ function upstreamFailure(error, providerID) {
224
+ const name = typeof error?.name === 'string' ? error.name : '';
225
+ if (name === 'ProviderAuthError')
226
+ return new Error(`OpenCode is not signed in to ${providerID}. Sign in from the provider settings, then retry.`);
227
+ if (name === 'StructuredOutputError')
228
+ return new Error('The OpenCode model did not return a structured Andorra step. Choose a model with tool support.');
229
+ if (name === 'MessageAbortedError')
230
+ return new Error('OpenCode request cancelled');
231
+ const detail = note(error?.data?.message);
232
+ return new Error(detail ? `OpenCode request failed: ${detail}` : 'OpenCode request failed. Check the model and its provider in OpenCode.');
233
+ }
234
+ /** Validate a prompt reply: one assistant message, no native tool other than structured output. */
235
+ export function parseOpenCodeReply(body, tools, providerID, structured) {
236
+ const reply = object(body);
237
+ const info = object(reply?.info);
238
+ if (!reply || !info || info.role !== 'assistant' || !Array.isArray(reply.parts))
239
+ throw new Error('OpenCode returned an invalid reply.');
240
+ if (info.error)
241
+ throw upstreamFailure(info.error, providerID);
242
+ for (const part of reply.parts) {
243
+ if (object(part)?.type === 'tool' && part.tool !== 'StructuredOutput')
244
+ throw new Error('OpenCode ran a native tool');
245
+ }
246
+ let response;
247
+ if (structured) {
248
+ if (info.structured === undefined)
249
+ throw new Error('The OpenCode model did not return a structured Andorra step. Choose a model with tool support.');
250
+ response = parseStructuredStep(info.structured, tools, 'OpenCode');
251
+ }
252
+ else {
253
+ response = { text: reply.parts.filter((part) => part?.type === 'text' && typeof part.text === 'string' && !part.synthetic).map((part) => part.text).join(''), toolCalls: [] };
254
+ }
255
+ const measured = usage(info.tokens);
256
+ if (measured)
257
+ response.usage = measured;
258
+ return response;
259
+ }
260
+ /**
261
+ * OpenCode produces one model response through whichever provider the model names; Andorra owns
262
+ * tool execution, graph state, and permissions. Each request is its own throwaway session.
263
+ */
264
+ export function createOpenCodeCliAdapter(_config, dependencies = {}) {
265
+ const server = () => dependencies.server ?? sharedOpenCodeServer();
266
+ return {
267
+ async listModels(signal) { return (await readOpenCodeCatalog(signal, server())).models.map(model => model.id); },
268
+ async generate(request) {
269
+ request.signal.throwIfAborted();
270
+ const auxiliary = request.maxTokens !== undefined;
271
+ if (auxiliary && (!Number.isSafeInteger(request.maxTokens) || request.maxTokens < 1))
272
+ throw new Error('Invalid auxiliary output allowance.');
273
+ if (auxiliary && request.tools.length)
274
+ throw new Error('OpenCode cannot apply an auxiliary output allowance to tool-bearing requests.');
275
+ const { providerID, modelID } = splitModel(request.model);
276
+ const signal = AbortSignal.any([request.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]);
277
+ const created = await server().request('/session', { method: 'POST', body: { title: 'Andorra model step' }, signal });
278
+ const sessionId = object(created.body)?.id;
279
+ if (created.status !== 200 || typeof sessionId !== 'string' || !/^[\w-]{1,200}$/.test(sessionId))
280
+ throw new Error('OpenCode could not open a session.');
281
+ const parts = [{ type: 'text', text: structuredStepPrompt(request) }];
282
+ request.messages.forEach((message, index) => message.images?.forEach((image, imageIndex) => {
283
+ parts.push({ type: 'text', text: `Image ${imageIndex + 1} from conversation message ${index + 1}:` }, { type: 'file', mime: image.mimeType, url: `data:${image.mimeType};base64,${image.data}`, filename: `image-${index + 1}-${imageIndex + 1}` });
284
+ }));
285
+ // OpenCode retries a rate-limited upstream on its own schedule, which can be hours away. The
286
+ // status is watched alongside the request so a run fails with the provider's reason instead.
287
+ const watch = new AbortController();
288
+ let retried;
289
+ const poll = (async () => {
290
+ while (!watch.signal.aborted) {
291
+ await new Promise(resolve => setTimeout(resolve, dependencies.retryPollMs ?? RETRY_POLL_MS));
292
+ if (watch.signal.aborted)
293
+ return;
294
+ const status = await server().request('/session/status', { signal: AbortSignal.any([signal, watch.signal]) }).catch(() => undefined);
295
+ const state = object(object(status?.body)?.[sessionId]);
296
+ if (state?.type === 'retry') {
297
+ retried = note(state.message) ?? 'the provider asked to retry later';
298
+ watch.abort();
299
+ return;
300
+ }
301
+ }
302
+ })();
303
+ const stopped = AbortSignal.any([signal, watch.signal]);
304
+ try {
305
+ request.onRequest?.();
306
+ let reply;
307
+ try {
308
+ reply = await server().request(`/session/${sessionId}/message`, { method: 'POST', signal: stopped, body: {
309
+ model: { providerID, modelID }, agent: auxiliary ? TEXT_AGENT : STRUCTURED_AGENT, parts,
310
+ // OpenCode sets no output cap per request, so the allowance is stated and enforced below.
311
+ ...(auxiliary ? { system: allowanceInstruction(request.maxTokens) } : {}),
312
+ ...(auxiliary ? {} : { format: { type: 'json_schema', schema: STRUCTURED_STEP_SCHEMA, retryCount: 1 } }),
313
+ } });
314
+ }
315
+ catch (error) {
316
+ if (retried)
317
+ throw new Error(`OpenCode request failed: ${retried}`);
318
+ throw error;
319
+ }
320
+ if (retried)
321
+ throw new Error(`OpenCode request failed: ${retried}`);
322
+ if (reply.status !== 200)
323
+ throw upstreamFailure(object(reply.body), providerID);
324
+ const response = parseOpenCodeReply(reply.body, request.tools, providerID, !auxiliary);
325
+ if (!auxiliary)
326
+ return response;
327
+ const visible = reply.body.info?.tokens?.output;
328
+ return boundTextStep(response, request.maxTokens, Number.isSafeInteger(visible) ? visible : undefined);
329
+ }
330
+ finally {
331
+ // Read before the watcher is stopped: stopping it aborts `stopped` too.
332
+ const interrupted = stopped.aborted;
333
+ watch.abort();
334
+ await poll;
335
+ const cleanup = AbortSignal.timeout(10_000);
336
+ if (interrupted)
337
+ await server().request(`/session/${sessionId}/abort`, { method: 'POST', signal: cleanup }).catch(() => { });
338
+ await server().request(`/session/${sessionId}`, { method: 'DELETE', signal: cleanup }).catch(() => { });
339
+ }
340
+ },
341
+ };
342
+ }
343
+ /**
344
+ * The browser sign-ins OpenCode offers, with the inputs Andorra can answer itself.
345
+ *
346
+ * A method that asks a free-text question (an enterprise URL, an account ID) needs OpenCode's own
347
+ * prompt, so it is left out; a method whose only questions are selections takes their first,
348
+ * public option.
349
+ */
350
+ export async function listOpenCodeSignIns(signal, server = sharedOpenCodeServer()) {
351
+ const bounded = AbortSignal.any([signal, AbortSignal.timeout(CATALOG_TIMEOUT_MS)]);
352
+ const [auth, providers] = await Promise.all([server.request('/provider/auth', { signal: bounded }), server.request('/provider', { signal: bounded })]);
353
+ const methods = object(auth.body);
354
+ const catalog = object(providers.body);
355
+ if (auth.status !== 200 || !methods || providers.status !== 200 || !catalog || !Array.isArray(catalog.all))
356
+ throw new Error('OpenCode did not return its sign-in options.');
357
+ const names = new Map(catalog.all.map((item) => [String(item?.id), note(item?.name) ?? String(item?.id)]));
358
+ const connected = new Set(Array.isArray(catalog.connected) ? catalog.connected : []);
359
+ const options = [];
360
+ for (const [providerId, list] of Object.entries(methods)) {
361
+ if (!/^[\w.@-]{1,100}$/.test(providerId) || !Array.isArray(list))
362
+ continue;
363
+ list.forEach((raw, method) => {
364
+ const entry = object(raw);
365
+ if (entry?.type !== 'oauth' || openCodeInputs(entry) === undefined)
366
+ return;
367
+ options.push({ providerId, providerName: names.get(providerId) ?? providerId, method, label: note(entry.label) ?? 'Sign in', connected: connected.has(providerId) });
368
+ });
369
+ }
370
+ return options;
371
+ }
372
+ /** Answers for a method's prompts, or `undefined` when one needs typed input. */
373
+ export function openCodeInputs(entry) {
374
+ const inputs = {};
375
+ for (const prompt of Array.isArray(entry.prompts) ? entry.prompts : []) {
376
+ const when = object(prompt?.when);
377
+ if (when && !(when.op === 'eq' && inputs[when.key] === when.value))
378
+ continue;
379
+ const first = Array.isArray(prompt?.options) ? object(prompt.options[0]) : undefined;
380
+ if (prompt?.type !== 'select' || typeof prompt.key !== 'string' || typeof first?.value !== 'string')
381
+ return undefined;
382
+ inputs[prompt.key] = first.value;
383
+ }
384
+ return inputs;
385
+ }
386
+ /** Begin one provider's browser sign-in inside OpenCode; the server keeps the pending exchange. */
387
+ export async function authorizeOpenCode(providerId, method, signal, server = sharedOpenCodeServer()) {
388
+ if (!/^[\w.@-]{1,100}$/.test(providerId) || !Number.isSafeInteger(method) || method < 0)
389
+ throw new Error('Invalid OpenCode sign-in option.');
390
+ const options = await server.request('/provider/auth', { signal });
391
+ const entry = object(object(options.body)?.[providerId]?.[method]);
392
+ const inputs = entry ? openCodeInputs(entry) : undefined;
393
+ if (entry?.type !== 'oauth' || inputs === undefined)
394
+ throw new Error('OpenCode does not offer that sign-in.');
395
+ const reply = await server.request(`/provider/${encodeURIComponent(providerId)}/oauth/authorize`, { method: 'POST', signal,
396
+ body: { method, ...(Object.keys(inputs).length ? { inputs } : {}) } });
397
+ const body = object(reply.body);
398
+ if (reply.status !== 200 || typeof body?.url !== 'string' || !/^https:\/\//.test(body.url) || (body.method !== 'auto' && body.method !== 'code')) {
399
+ throw new Error('OpenCode could not start that sign-in.');
400
+ }
401
+ return { url: body.url, method: body.method, ...(note(body.instructions) ? { instructions: note(body.instructions) } : {}) };
402
+ }
403
+ /** Finish a sign-in: `auto` waits for OpenCode's own callback, `code` submits what the page showed. */
404
+ export async function completeOpenCode(providerId, method, code, signal, server = sharedOpenCodeServer()) {
405
+ const reply = await server.request(`/provider/${encodeURIComponent(providerId)}/oauth/callback`, { method: 'POST', signal,
406
+ body: { method, ...(code === undefined ? {} : { code }) } });
407
+ return reply.status === 200 && reply.body === true;
408
+ }
409
+ /** Remove one upstream provider's stored OpenCode credential. */
410
+ export async function signOutOpenCode(providerId, signal, server = sharedOpenCodeServer()) {
411
+ if (!/^[\w.@-]{1,100}$/.test(providerId))
412
+ throw new Error('Invalid OpenCode provider.');
413
+ const reply = await server.request(`/auth/${encodeURIComponent(providerId)}`, { method: 'DELETE', signal });
414
+ return reply.status === 200;
415
+ }