@andorra-labs/code 0.1.5 → 0.1.7
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.
- package/dist/src/account-presentation.js +3 -3
- package/dist/src/agent-execution.d.ts +2 -0
- package/dist/src/agent-execution.js +526 -41
- package/dist/src/agent-mcp-catalog.d.ts +21 -0
- package/dist/src/agent-mcp-catalog.js +40 -0
- package/dist/src/agent-mcp.d.ts +36 -3
- package/dist/src/agent-mcp.js +114 -45
- package/dist/src/app-server/protocol.d.ts +57 -5
- package/dist/src/app-server/protocol.js +18 -1
- package/dist/src/app-server/workspace.d.ts +9 -1
- package/dist/src/app-server/workspace.js +50 -3
- package/dist/src/app-server.d.ts +115 -41
- package/dist/src/app-server.js +1316 -221
- package/dist/src/auth/AuthManager.d.ts +33 -1
- package/dist/src/auth/AuthManager.js +138 -10
- package/dist/src/auth/callback-page.d.ts +4 -0
- package/dist/src/auth/callback-page.js +70 -0
- package/dist/src/auth/callback.d.ts +39 -0
- package/dist/src/auth/callback.js +146 -22
- package/dist/src/auth/index.d.ts +10 -6
- package/dist/src/auth/index.js +2 -2
- package/dist/src/auth/store.d.ts +142 -3
- package/dist/src/auth/store.js +334 -13
- package/dist/src/auth/types.d.ts +17 -1
- package/dist/src/auth-commands.d.ts +11 -2
- package/dist/src/auth-commands.js +14 -7
- package/dist/src/automation-runner.d.ts +9 -0
- package/dist/src/automation-runner.js +22 -1
- package/dist/src/automation-tool.js +18 -3
- package/dist/src/automations.d.ts +5 -0
- package/dist/src/automations.js +11 -1
- package/dist/src/browser-captcha-tool.d.ts +54 -0
- package/dist/src/browser-captcha-tool.js +374 -0
- package/dist/src/browser-panel-tool.d.ts +7 -0
- package/dist/src/browser-panel-tool.js +74 -3
- package/dist/src/browser-runner.js +19 -4
- package/dist/src/browser-server.js +21 -1
- package/dist/src/browser-session.d.ts +16 -0
- package/dist/src/browser-session.js +35 -0
- package/dist/src/browser-ui/app.js +193 -3
- package/dist/src/browser-ui/style.css +15 -1
- package/dist/src/browser-view.d.ts +72 -4
- package/dist/src/browser-view.js +229 -17
- package/dist/src/capabilities.d.ts +9 -3
- package/dist/src/capabilities.js +20 -5
- package/dist/src/capsolver.d.ts +60 -0
- package/dist/src/capsolver.js +101 -0
- package/dist/src/claude-provider.d.ts +6 -0
- package/dist/src/claude-provider.js +34 -3
- package/dist/src/cli-executable.d.ts +33 -0
- package/dist/src/cli-executable.js +64 -0
- package/dist/src/cli-process.d.ts +47 -0
- package/dist/src/cli-process.js +113 -0
- package/dist/src/cli-sign-in.d.ts +68 -0
- package/dist/src/cli-sign-in.js +224 -0
- package/dist/src/cli.js +84 -26
- package/dist/src/code-intelligence/CodeIntelligenceManager.d.ts +1 -1
- package/dist/src/code-intelligence/CodeIntelligenceManager.js +5 -5
- package/dist/src/codex-provider.js +12 -0
- package/dist/src/coding-tools.d.ts +5 -0
- package/dist/src/coding-tools.js +98 -53
- package/dist/src/command-output-tap.d.ts +16 -0
- package/dist/src/command-output-tap.js +45 -0
- package/dist/src/command-screens.js +3 -3
- package/dist/src/commands.d.ts +15 -2
- package/dist/src/commands.js +14 -13
- package/dist/src/completion.d.ts +23 -5
- package/dist/src/completion.js +380 -17
- package/dist/src/config.d.ts +61 -0
- package/dist/src/config.js +276 -12
- package/dist/src/context-budget.d.ts +7 -0
- package/dist/src/context-budget.js +18 -1
- package/dist/src/deadline.js +6 -0
- package/dist/src/decision/FactContinuations.d.ts +41 -6
- package/dist/src/decision/FactContinuations.js +211 -64
- package/dist/src/decision/PreparedSteps.js +3 -1
- package/dist/src/decision/checks.d.ts +25 -0
- package/dist/src/decision/checks.js +77 -6
- package/dist/src/delegation-changes.d.ts +109 -0
- package/dist/src/delegation-changes.js +431 -0
- package/dist/src/extensions.d.ts +1 -0
- package/dist/src/extensions.js +16 -3
- package/dist/src/graph-provider-portability.js +2 -2
- package/dist/src/graph-quota.d.ts +1 -1
- package/dist/src/graph-quota.js +1 -1
- package/dist/src/graph-runner.js +35 -21
- package/dist/src/graph-selection.d.ts +6 -0
- package/dist/src/graph-selection.js +10 -0
- package/dist/src/graph-server.d.ts +8 -0
- package/dist/src/graph-server.js +76 -6
- package/dist/src/graph-sync.d.ts +65 -0
- package/dist/src/graph-sync.js +433 -13
- package/dist/src/graph-tool.d.ts +52 -0
- package/dist/src/graph-tool.js +136 -0
- package/dist/src/graph-ui/app.js +272 -50
- package/dist/src/graph-ui/controls.js +6 -0
- package/dist/src/graph-ui/drafts.js +39 -0
- package/dist/src/graph-ui/embed.js +1 -1
- package/dist/src/graph-ui/icons.js +1 -0
- package/dist/src/graph-ui/index.html +2 -2
- package/dist/src/graph-ui/skill-picker.js +242 -0
- package/dist/src/graph-ui/studio.css +7 -5
- package/dist/src/graph-ui/style.css +65 -12
- package/dist/src/graphs.d.ts +60 -5
- package/dist/src/graphs.js +191 -37
- package/dist/src/grok-provider.d.ts +50 -0
- package/dist/src/grok-provider.js +186 -0
- package/dist/src/handoffs.d.ts +13 -0
- package/dist/src/handoffs.js +31 -1
- package/dist/src/hardened-runtime.d.ts +4 -4
- package/dist/src/hardened-runtime.js +109 -9
- package/dist/src/managed-sign-in.d.ts +38 -0
- package/dist/src/managed-sign-in.js +169 -0
- package/dist/src/markdown.d.ts +5 -0
- package/dist/src/markdown.js +5 -2
- package/dist/src/mcp.js +11 -0
- package/dist/src/membership.d.ts +8 -1
- package/dist/src/membership.js +15 -5
- package/dist/src/model-metadata.js +14 -2
- package/dist/src/model-override.d.ts +10 -0
- package/dist/src/model-override.js +20 -0
- package/dist/src/opencode-cli-provider.d.ts +122 -0
- package/dist/src/opencode-cli-provider.js +415 -0
- package/dist/src/opencode-provider.js +23 -8
- package/dist/src/palette.d.ts +2 -0
- package/dist/src/palette.js +2 -0
- package/dist/src/permissions.d.ts +19 -1
- package/dist/src/permissions.js +30 -1
- package/dist/src/powershell-pool.d.ts +11 -2
- package/dist/src/powershell-pool.js +34 -5
- package/dist/src/provider-connection.js +36 -0
- package/dist/src/provider-engine.d.ts +2 -1
- package/dist/src/provider-engine.js +64 -13
- package/dist/src/provider-import.js +6 -1
- package/dist/src/provider-keys.d.ts +48 -0
- package/dist/src/provider-keys.js +121 -0
- package/dist/src/provider-settings.js +22 -3
- package/dist/src/providers.d.ts +12 -1
- package/dist/src/providers.js +27 -8
- package/dist/src/pull-requests.d.ts +123 -20
- package/dist/src/pull-requests.js +334 -84
- package/dist/src/qa/qa-authorize.js +9 -1
- package/dist/src/qa/runtime/ProcessManager.d.ts +6 -0
- package/dist/src/qa/runtime/ProcessManager.js +16 -0
- package/dist/src/react-runtime.js +106 -7
- package/dist/src/read-image.d.ts +30 -0
- package/dist/src/read-image.js +97 -0
- package/dist/src/remote/engine-pool.js +1 -1
- package/dist/src/run-progress.js +6 -1
- package/dist/src/run-records.d.ts +133 -27
- package/dist/src/run-records.js +320 -40
- package/dist/src/runtime.d.ts +38 -1
- package/dist/src/runtime.js +27 -4
- package/dist/src/save-lock.d.ts +11 -0
- package/dist/src/save-lock.js +29 -2
- package/dist/src/secret-redaction.d.ts +13 -0
- package/dist/src/secret-redaction.js +71 -0
- package/dist/src/session-summary.d.ts +10 -4
- package/dist/src/session-summary.js +14 -7
- package/dist/src/sessions.js +8 -2
- package/dist/src/shell.js +4 -1
- package/dist/src/side-panel.d.ts +1 -1
- package/dist/src/side-panel.js +1 -1
- package/dist/src/skill-commands.d.ts +2 -0
- package/dist/src/skill-commands.js +2 -0
- package/dist/src/skills/bundled/create-agent/SKILL.md +81 -0
- package/dist/src/skills/bundled/create-skill/SKILL.md +81 -0
- package/dist/src/skills/bundled/doctor/SKILL.md +43 -0
- package/dist/src/skills/bundled/graph-manager/SKILL.md +100 -0
- package/dist/src/skills/bundled/graph-manager/errors.md +38 -0
- package/dist/src/skills/bundled/graph-manager/patterns.md +78 -0
- package/dist/src/skills/bundled/manage-mcp/SKILL.md +75 -0
- package/dist/src/skills/bundled/manage-mcp/probe.md +165 -0
- package/dist/src/skills/bundled/manage-skills/SKILL.md +67 -0
- package/dist/src/skills/bundled/provenance.json +50 -0
- package/dist/src/skills/bundled/write-instructions/SKILL.md +42 -0
- package/dist/src/skills/invocable-skills.d.ts +41 -0
- package/dist/src/skills/invocable-skills.js +49 -0
- package/dist/src/skills/prompt-skills.d.ts +1 -0
- package/dist/src/skills/prompt-skills.js +33 -0
- package/dist/src/skills/runtime-skills.d.ts +4 -0
- package/dist/src/skills/runtime-skills.js +21 -0
- package/dist/src/structured-step.d.ts +55 -0
- package/dist/src/structured-step.js +85 -0
- package/dist/src/subagent-run.d.ts +1 -1
- package/dist/src/subagent-run.js +29 -33
- package/dist/src/telemetry/schema.d.ts +2 -2
- package/dist/src/telemetry/schema.js +3 -2
- package/dist/src/terminal-ui.d.ts +38 -0
- package/dist/src/terminal-ui.js +126 -28
- package/dist/src/timers.d.ts +21 -2
- package/dist/src/timers.js +12 -4
- package/dist/src/tool-dependencies.js +4 -0
- package/dist/src/tool-names.d.ts +18 -0
- package/dist/src/tool-names.js +26 -0
- package/dist/src/tools.d.ts +9 -0
- package/dist/src/tools.js +159 -20
- package/dist/src/trajectory.js +32 -12
- package/dist/src/transcript.js +5 -0
- package/dist/src/types.d.ts +36 -0
- package/dist/src/web-search.d.ts +59 -0
- package/dist/src/web-search.js +216 -0
- package/docs/agents/README.md +2 -2
- package/docs/agents/mcp-server.md +28 -3
- package/docs/agents/subagent-mode.md +7 -4
- package/docs/concepts/README.md +1 -1
- package/docs/concepts/security.md +4 -2
- package/docs/getting-started/accounts.md +15 -4
- package/docs/getting-started/configure-providers.md +30 -3
- package/docs/guides/README.md +1 -0
- package/docs/guides/browser.md +12 -0
- package/docs/guides/desktop-app.md +11 -4
- package/docs/guides/graph-builder.md +9 -1
- package/docs/guides/web-search.md +47 -0
- package/docs/reference/cli.md +4 -3
- package/docs/reference/config.md +4 -4
- package/docs/reference/slash-commands.md +2 -1
- package/docs/superpowers/plans/2026-11-06-graph-soft-delete.md +125 -0
- package/docs/superpowers/plans/2026-11-09-orchestrator-delegation.md +295 -0
- package/docs/superpowers/specs/2026-11-01-pr-section-design.md +7 -0
- package/docs/superpowers/specs/2026-11-06-bundled-skills-design.md +206 -0
- package/docs/superpowers/specs/2026-11-09-orchestrator-delegation-design.md +291 -0
- package/package.json +1 -1
- package/tests/permissions-test-plan.md +2 -1
package/dist/src/graphs.js
CHANGED
|
@@ -2,10 +2,10 @@ import { mkdir, readFile, readdir, rename, unlink, writeFile } from 'node:fs/pro
|
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { randomUUID } from 'node:crypto';
|
|
4
4
|
import { configDirectory } from './config.js';
|
|
5
|
-
import { acquireSaveLock, archiveUnpublishedSnapshot, SaveLockBusyError } from './save-lock.js';
|
|
5
|
+
import { acquireSaveLock, archiveUnpublishedSnapshot, removeLockedFolder, SaveLockBusyError } from './save-lock.js';
|
|
6
6
|
import { validateMappingConstants, validateMappings, validateSchema, validateValue, schemaAt, nodeOutputSchema } from './handoffs.js';
|
|
7
7
|
import { CANONICAL_CODING_TOOLS, canonicalToolName, canonicalizeToolList, toolNameMatches } from './tool-names.js';
|
|
8
|
-
export const GRAPH_TOOLS = [...CANONICAL_CODING_TOOLS, 'NativeExec', 'AsyncProcess', 'PowerShellFast', 'ShellMetrics', 'read_file', 'list_files', 'search_files', 'write_file', 'edit_file', 'read', 'write', 'edit', 'find', 'grep', 'ls', 'powershell', 'bash', 'shell', 'git_read', 'read_artifact', 'write_artifact', 'repo_explore', 'memory_search', 'set_timer', 'pull_request', 'qa.inspect_project', 'qa.status', 'qa.fast', 'qa.deep', 'qa.test', 'qa.terminal', 'qa.security', 'qa.browser', 'qa.browser_session', 'read_skill_resource', 'browser.panel'];
|
|
8
|
+
export const GRAPH_TOOLS = [...CANONICAL_CODING_TOOLS, 'NativeExec', 'AsyncProcess', 'PowerShellFast', 'ShellMetrics', 'read_file', 'list_files', 'search_files', 'write_file', 'edit_file', 'read', 'write', 'edit', 'find', 'grep', 'ls', 'powershell', 'bash', 'shell', 'git_read', 'read_artifact', 'write_artifact', 'repo_explore', 'memory_search', 'set_timer', 'pull_request', 'graphs', 'qa.inspect_project', 'qa.status', 'qa.fast', 'qa.deep', 'qa.test', 'qa.terminal', 'qa.security', 'qa.browser', 'qa.browser_session', 'browser.solve_captcha', 'web_search', 'read_skill_resource', 'browser.panel', 'browser.incognito'];
|
|
9
9
|
/** QA tool names are an explicit allowlist; gating keys off membership, never a name prefix. */
|
|
10
10
|
export const QA_TOOL_NAMES = ['qa.inspect_project', 'qa.status', 'qa.fast', 'qa.deep', 'qa.test', 'qa.terminal', 'qa.security', 'qa.browser'];
|
|
11
11
|
export const isQaToolName = (name) => QA_TOOL_NAMES.includes(name);
|
|
@@ -26,7 +26,7 @@ export function createOrchestratorNode(id = 'orchestrator') {
|
|
|
26
26
|
id, name: 'Orchestrator', type: 'agent', agentRole: 'orchestrator', executor: 'react-basic',
|
|
27
27
|
instruction: 'Understand the requested work before delegating implementation. Inspect relevant repository files, components, interfaces, architecture and testing patterns with the available read tools. Ground codebase findings in inspected paths and distinguish evidence from unknowns. Ask the user to clarify requirements, acceptance criteria, design preferences and important tradeoffs before handing work onward; do not infer approval from silence. Summarize the confirmed requirements, design considerations and codebase findings, then produce a concrete task instruction for the next Agent. Research subagents are optional and bounded; use only those that help resolve specific questions. Do not implement or modify the workspace during intake.',
|
|
28
28
|
capabilities: { filesystem: 'read', shell: 'disabled', git: 'read', github: 'none', browser: 'playwright', deployment: 'none' },
|
|
29
|
-
tools: ['read_file', 'list_files', 'search_files', 'git_read', 'read_artifact', 'write_artifact', 'repo_explore', 'read_skill_resource', 'qa.browser_session', 'browser.panel'],
|
|
29
|
+
tools: ['read_file', 'list_files', 'search_files', 'git_read', 'read_artifact', 'write_artifact', 'repo_explore', 'read_skill_resource', 'qa.browser_session', 'browser.panel', 'browser.incognito'],
|
|
30
30
|
completion: { mode: 'single', outcome: 'completed' },
|
|
31
31
|
contextPolicy: { history: true },
|
|
32
32
|
inputs: { originalTask: '$run.input.task' },
|
|
@@ -73,8 +73,8 @@ DEFAULT_HARNESS_REVISION_3.nodes.orchestrator.retry = { maxAttempts: 2 };
|
|
|
73
73
|
/** Frozen revision 4 adds skill resources to the published revision-3 snapshot. */
|
|
74
74
|
export const DEFAULT_HARNESS_REVISION_4 = { ...structuredClone(DEFAULT_HARNESS_REVISION_3), revision: 4 };
|
|
75
75
|
DEFAULT_HARNESS_REVISION_4.nodes.orchestrator.tools.push('read_skill_resource');
|
|
76
|
-
/**
|
|
77
|
-
export const
|
|
76
|
+
/** Frozen revision 5 enables the integrated browser for all default agents. */
|
|
77
|
+
export const DEFAULT_HARNESS_REVISION_5 = {
|
|
78
78
|
schemaVersion: 3, id: 'default', name: 'Software Engineer', revision: 5, entry: 'orchestrator',
|
|
79
79
|
nodes: {
|
|
80
80
|
orchestrator: { ...createOrchestratorNode(), retry: { maxAttempts: 2 }, position: { x: 100, y: 120 } },
|
|
@@ -82,6 +82,15 @@ export const DEFAULT_HARNESS = {
|
|
|
82
82
|
done: { id: 'done', name: 'Done', type: 'end', position: { x: 780, y: 120 } },
|
|
83
83
|
}, edges: [{ id: 'orchestrator-engineer', source: 'orchestrator', target: 'engineer', outcome: 'completed', inputMapping: structuredClone(ORCHESTRATOR_HANDOFF) }, { id: 'engineer-done', source: 'engineer', target: 'done', outcome: 'completed' }],
|
|
84
84
|
};
|
|
85
|
+
/**
|
|
86
|
+
* Revision 6 renames the bundled execution agent to Andorra Agent and widens its role to general
|
|
87
|
+
* tasks alongside coding. The agent still receives the confirmed task instruction through the same
|
|
88
|
+
* intake handoff, and topology, capabilities and tooling are exactly revision 5's, so the change is
|
|
89
|
+
* presentation and instruction only.
|
|
90
|
+
*/
|
|
91
|
+
export const DEFAULT_HARNESS = { ...structuredClone(DEFAULT_HARNESS_REVISION_5), name: 'Andorra Agent', revision: 6 };
|
|
92
|
+
DEFAULT_HARNESS.nodes.engineer.name = 'Andorra Agent';
|
|
93
|
+
DEFAULT_HARNESS.nodes.engineer.instruction = 'Carry out the confirmed task instruction completely, whether it is a coding task or a general one: implement code and verify changes with appropriate tools, and answer general research, writing and analysis directly. Use the supplied requirements, acceptance criteria, design considerations and repository findings to guide the work. Verify the result and report remaining issues.';
|
|
85
94
|
/** Upgrade only in-memory copies. Stored snapshots remain unchanged. */
|
|
86
95
|
/**
|
|
87
96
|
* `addOrchestrator: false` upgrades a legacy graph without an Orchestrator to the current schema as it
|
|
@@ -190,13 +199,25 @@ export function intakeCapabilities(node) {
|
|
|
190
199
|
return { filesystem: policy.filesystem === 'none' ? 'none' : 'read', shell: 'disabled',
|
|
191
200
|
git: policy.git === 'none' ? 'none' : 'read', github: 'none', browser: policy.browser, deployment: 'none' };
|
|
192
201
|
}
|
|
193
|
-
|
|
202
|
+
/** The second completion outcome of a delegating Orchestrator: subagents did the work and it landed. */
|
|
203
|
+
export const DELIVERED_OUTCOME = 'delivered';
|
|
204
|
+
export function isWritingRole(role) {
|
|
205
|
+
return role.capabilities?.filesystem === 'read-write' || role.capabilities?.git === 'write';
|
|
206
|
+
}
|
|
207
|
+
/** An Orchestrator delegates implementation when spawning is on and at least one role may write. */
|
|
208
|
+
export function delegatesWriting(node) {
|
|
209
|
+
return node.type === 'agent' && node.agentRole === 'orchestrator' && node.subagents?.enabled === true && node.maxSubagents !== 0
|
|
210
|
+
&& (node.subagents.roles ?? []).some(isWritingRole);
|
|
211
|
+
}
|
|
212
|
+
const canRunCommands = (policy, child) => child !== true && policy.shell === 'allowed' && policy.filesystem === 'read-write' && policy.git === 'write';
|
|
194
213
|
export function permitsBuiltInTool(node, name, child = false) {
|
|
195
214
|
if (node.tools !== undefined && !node.tools.some(configured => toolNameMatches(configured, name)))
|
|
196
215
|
return false;
|
|
197
216
|
const policy = effectiveCapabilities(node);
|
|
198
217
|
const canonical = canonicalToolName(name);
|
|
199
|
-
|
|
218
|
+
// The solve tool only acts on this agent's own qa.browser_session pages, so it follows the same policy;
|
|
219
|
+
// web_search reaches the internet the way the browser does, so the browser policy governs it too.
|
|
220
|
+
if (name === 'qa.browser_session' || name === 'browser.solve_captcha' || name === 'web_search')
|
|
200
221
|
return policy.browser === 'playwright';
|
|
201
222
|
if (['Read', 'Glob', 'Grep', 'repo_explore', 'read_skill_resource'].includes(canonical))
|
|
202
223
|
return policy.filesystem !== 'none';
|
|
@@ -233,7 +254,10 @@ export function nodeOutcomes(node) {
|
|
|
233
254
|
return [node.modifiers.loop.until.outcome];
|
|
234
255
|
if (node.type === 'approval')
|
|
235
256
|
return ['approved', 'rejected'];
|
|
236
|
-
|
|
257
|
+
if (node.completion?.mode === 'outcomes')
|
|
258
|
+
return node.completion.outcomes;
|
|
259
|
+
const outcome = node.completion?.outcome ?? 'completed';
|
|
260
|
+
return delegatesWriting(node) ? [outcome, DELIVERED_OUTCOME] : [outcome];
|
|
237
261
|
}
|
|
238
262
|
function guaranteedGraphInvocations(graph) {
|
|
239
263
|
const nodes = Object.values(graph.nodes);
|
|
@@ -247,7 +271,9 @@ function guaranteedGraphInvocations(graph) {
|
|
|
247
271
|
for (const node of nodes) {
|
|
248
272
|
if (node.id === boundary)
|
|
249
273
|
continue;
|
|
250
|
-
|
|
274
|
+
// An unrouted delivered port is not a path the run can take, so it does not weaken what the
|
|
275
|
+
// completed route guarantees; once routed it is a real alternative like any other outcome.
|
|
276
|
+
const alternatives = nodeOutcomes(node).filter(outcome => outcome !== DELIVERED_OUTCOME || !delegatesWriting(node) || routes(node.id, outcome).length > 0).map(outcome => {
|
|
251
277
|
const reached = new Set();
|
|
252
278
|
for (const edge of routes(node.id, outcome))
|
|
253
279
|
for (const id of guaranteed.get(edge.target))
|
|
@@ -277,7 +303,7 @@ function guaranteedGraphInvocations(graph) {
|
|
|
277
303
|
const required = guarantees().get(graph.entry);
|
|
278
304
|
return { required, loopBodies };
|
|
279
305
|
}
|
|
280
|
-
function minimumGraphToolCalls(graph) {
|
|
306
|
+
export function minimumGraphToolCalls(graph) {
|
|
281
307
|
const { required, loopBodies } = guaranteedGraphInvocations(graph);
|
|
282
308
|
const calls = new Map([...required].map(id => [id, graph.nodes[id].agentRole === 'orchestrator' ? 2 : graph.nodes[id].type === 'action' ? 1 : 0]));
|
|
283
309
|
for (const [loopId, body] of loopBodies) {
|
|
@@ -747,14 +773,26 @@ function validateGraphInternal(value, options = {}) {
|
|
|
747
773
|
fail(`${label}: task-only context cannot supply required inputs for role ${r.id}; select selected context or make the role inputs optional`);
|
|
748
774
|
if (r.capabilities)
|
|
749
775
|
capabilities(r.capabilities, `${label} role ${r.id}`);
|
|
750
|
-
|
|
776
|
+
// A writing role on an Orchestrator is a delegated one: delegatesWriting(node) && isWritingRole(r),
|
|
777
|
+
// spelled out per role so that roles not yet shape-checked by this loop are never inspected.
|
|
778
|
+
const delegated = node.agentRole === 'orchestrator' && spawningEnabled && isWritingRole(r);
|
|
779
|
+
if (delegated && (s.workspace ?? 'shared-read-only') !== 'worktree')
|
|
780
|
+
fail(`${label}: writing roles on an Orchestrator require separate worktrees; select Separate Git worktree`);
|
|
781
|
+
if (delegated && node.completion?.mode === 'outcomes')
|
|
782
|
+
fail(`${label}: Orchestrator delegation needs a single completion outcome; remove declared outcomes or the writing roles`);
|
|
783
|
+
if (delegated && node.completion?.mode === 'single' && node.completion.outcome === DELIVERED_OUTCOME)
|
|
784
|
+
fail(`${label}: the outcome name ${DELIVERED_OUTCOME} is reserved for Orchestrator delegation; rename the completion outcome`);
|
|
785
|
+
// Two ceilings: the Orchestrator itself and its read-only roles stay under the intake ceiling;
|
|
786
|
+
// a delegated writing role is measured against the node's configured capabilities.
|
|
787
|
+
const parent = node.agentRole === 'orchestrator' && spawningEnabled && !delegated ? intakeCapabilities(node) : effectiveCapabilities(node);
|
|
751
788
|
const child = r.capabilities ?? { ...parent, ...((s.workspace ?? 'shared-read-only') === 'shared-read-only' ? { filesystem: parent.filesystem === 'none' ? 'none' : 'read', git: parent.git === 'none' ? 'none' : 'read', shell: 'disabled' } : {}) };
|
|
752
789
|
if (!capabilitySubset(child, parent))
|
|
753
|
-
fail(`${label}: role ${r.id} capability exceeds parent${node.agentRole === 'orchestrator' ? ' intake read-only ceiling; reduce child permissions' : '; reduce child permissions or explicitly grant them to the parent'}`);
|
|
754
|
-
|
|
790
|
+
fail(`${label}: role ${r.id} capability exceeds parent${node.agentRole === 'orchestrator' && !delegated ? ' intake read-only ceiling; reduce child permissions' : '; reduce child permissions or explicitly grant them to the parent'}`);
|
|
791
|
+
// The delegation ceiling is the node's capabilities alone: the Orchestrator's own tool list is its intake kit.
|
|
792
|
+
if (r.tools?.some(t => !permitsBuiltInTool(delegated ? { capabilities: parent } : { ...node, capabilities: parent }, t)))
|
|
755
793
|
fail(`${label}: role ${r.id} tools exceed effective parent capabilities; reduce its tools or explicitly grant parent permissions`);
|
|
756
|
-
if (r.tools?.some(t => !permitsBuiltInTool({ capabilities: child }, t, true)))
|
|
757
|
-
fail(`${label}: role ${r.id} tools exceed its child capabilities; remove unavailable tools (subagents cannot use the host shell)`);
|
|
794
|
+
if (r.tools?.some(t => !permitsBuiltInTool({ capabilities: child }, t, delegated ? 'delegated-worktree' : true)))
|
|
795
|
+
fail(`${label}: role ${r.id} tools exceed its child capabilities; remove unavailable tools${delegated ? '' : ' (subagents cannot use the host shell)'}`);
|
|
758
796
|
const writes = child.filesystem === 'read-write' || child.git === 'write';
|
|
759
797
|
if (spawningEnabled && s.workspace === 'worktree' && writes && parent.git !== 'write')
|
|
760
798
|
fail(`${label}: writing worktree role ${r.id} requires parent Git write access; grant Git write or select a read-only role`);
|
|
@@ -859,8 +897,9 @@ function validateGraphInternal(value, options = {}) {
|
|
|
859
897
|
}
|
|
860
898
|
if (node.type === 'condition' && (node.condition.source === id || canReach(graph.entry, id, node.condition.source)))
|
|
861
899
|
fail(`Condition ${id}: source ${node.condition.source} must execute on every path before this condition; route through the source first`);
|
|
900
|
+
// A delegating Orchestrator's delivered port is optional: unrouted, the graph behaves like intake.
|
|
862
901
|
for (const outcome of nodeOutcomes(node))
|
|
863
|
-
if (!(node.completion?.mode === 'outcomes' && node.completion.requireRoutes === false) && !(outgoing.get(id) ?? []).some(e => e.outcome === outcome))
|
|
902
|
+
if (!(node.completion?.mode === 'outcomes' && node.completion.requireRoutes === false) && !(outcome === DELIVERED_OUTCOME && delegatesWriting(node)) && !(outgoing.get(id) ?? []).some(e => e.outcome === outcome))
|
|
864
903
|
fail(`node ${id}: required outcome ${outcome} has no route; connect its output port`);
|
|
865
904
|
if (node.type === 'join' && node.join?.mode === 'all') {
|
|
866
905
|
const edges = (incoming.get(id) ?? []).filter(edge => !edge.bootstrap);
|
|
@@ -944,8 +983,52 @@ function validateGraphInternal(value, options = {}) {
|
|
|
944
983
|
export class GraphConflictError extends Error {
|
|
945
984
|
constructor(message = 'This graph changed in another editor. Reload it before saving.') { super(message); this.name = 'GraphConflictError'; }
|
|
946
985
|
}
|
|
947
|
-
/**
|
|
948
|
-
|
|
986
|
+
/**
|
|
987
|
+
* A soft-deleted graph: its latest revision carries `metadata.deletedAt`.
|
|
988
|
+
*
|
|
989
|
+
* Deleting publishes that revision rather than removing files, because cloud sync restores every graph
|
|
990
|
+
* an account holds and would bring removed files back. Every earlier revision stays stored.
|
|
991
|
+
*/
|
|
992
|
+
export function isDeletedGraph(graph) {
|
|
993
|
+
return typeof graph.metadata?.deletedAt === 'string' && graph.metadata.deletedAt.length > 0;
|
|
994
|
+
}
|
|
995
|
+
/** What a listing shows. Quota is computed from the full list, so deleted graphs still count there. */
|
|
996
|
+
export function withoutDeletedGraphs(graphs) {
|
|
997
|
+
return graphs.filter(graph => !isDeletedGraph(graph));
|
|
998
|
+
}
|
|
999
|
+
/** A new run named a deleted graph. Resuming a session that already ran it is still allowed. */
|
|
1000
|
+
export class GraphDeletedError extends Error {
|
|
1001
|
+
code = 'GRAPH_DELETED';
|
|
1002
|
+
constructor(name) { super(`Graph ${name} was deleted. Restore it before running it.`); this.name = 'GraphDeletedError'; }
|
|
1003
|
+
}
|
|
1004
|
+
/** Whether the folder holds a published graph: a save's latest pointer or any numbered revision. */
|
|
1005
|
+
async function publishedRevision(folder) {
|
|
1006
|
+
try {
|
|
1007
|
+
await readFile(join(folder, 'latest.json'), 'utf8');
|
|
1008
|
+
return true;
|
|
1009
|
+
}
|
|
1010
|
+
catch (error) {
|
|
1011
|
+
if (error.code !== 'ENOENT')
|
|
1012
|
+
return true;
|
|
1013
|
+
}
|
|
1014
|
+
try {
|
|
1015
|
+
for (const entry of await readdir(folder))
|
|
1016
|
+
if (/^\d+\.json$/.test(entry))
|
|
1017
|
+
return true;
|
|
1018
|
+
return false;
|
|
1019
|
+
}
|
|
1020
|
+
catch (error) {
|
|
1021
|
+
return error.code !== 'ENOENT';
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
/**
|
|
1025
|
+
* Publish an immutable cloud revision only when the local revision is absent or identical.
|
|
1026
|
+
*
|
|
1027
|
+
* `skip` and `floorOf` are consulted under the folder's save lock immediately before any write:
|
|
1028
|
+
* a graph deleted on this machine must not be written back, and asking while holding the lock
|
|
1029
|
+
* makes those verdicts final against a delete or revival that is still running.
|
|
1030
|
+
*/
|
|
1031
|
+
export async function restoreGraphRevision(input, directory, skip, floorOf) {
|
|
949
1032
|
const graph = validateGraphInternal(input);
|
|
950
1033
|
if (graph.id === 'default' || graph.revision < 1)
|
|
951
1034
|
throw new Error('Invalid cloud revision');
|
|
@@ -954,6 +1037,64 @@ export async function restoreGraphRevision(input, directory) {
|
|
|
954
1037
|
const release = await acquireSaveLock(folder);
|
|
955
1038
|
const temp = join(folder, `latest-${randomUUID()}.tmp`);
|
|
956
1039
|
try {
|
|
1040
|
+
if (skip && await skip(graph)) {
|
|
1041
|
+
// The tombstone is the authority: what this restore finds here is either residue from a
|
|
1042
|
+
// restore that raced the delete — removed under the lock — or a graph a save re-created
|
|
1043
|
+
// after the delete and before the tombstone revival cleared it. Erasing that re-creation
|
|
1044
|
+
// would lose a save that already succeeded, so only an unpublished folder is removed.
|
|
1045
|
+
if (!await publishedRevision(folder))
|
|
1046
|
+
await removeLockedFolder(folder);
|
|
1047
|
+
return { graph, restored: false };
|
|
1048
|
+
}
|
|
1049
|
+
// The latest pointer is read before any write: the floor verdict below needs it, and a
|
|
1050
|
+
// damaged pointer must refuse the restore before the folder receives new content.
|
|
1051
|
+
let current = 0;
|
|
1052
|
+
try {
|
|
1053
|
+
const raw = await readFile(join(folder, 'latest.json'), 'utf8');
|
|
1054
|
+
try {
|
|
1055
|
+
current = JSON.parse(raw);
|
|
1056
|
+
}
|
|
1057
|
+
catch {
|
|
1058
|
+
throw new GraphConflictError('The local latest pointer is damaged; preserve it as a conflict.');
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
catch (error) {
|
|
1062
|
+
if (error.code !== 'ENOENT')
|
|
1063
|
+
throw error;
|
|
1064
|
+
}
|
|
1065
|
+
if (!Number.isSafeInteger(current) || current < 0)
|
|
1066
|
+
throw new GraphConflictError('Invalid latest revision');
|
|
1067
|
+
// A re-created id starts a new lineage. While a deletion floor is recorded for the id, cloud
|
|
1068
|
+
// revisions above the replacement's head never advance its latest pointer: the floor the
|
|
1069
|
+
// deleting machine recorded can sit behind the cloud (another device synced newer revisions
|
|
1070
|
+
// it never pulled), so a revision above the floor is not proof of new-lineage history.
|
|
1071
|
+
// New-lineage snapshots are unaffected — they were restored locally before their upload, so
|
|
1072
|
+
// their revisions never exceed the head. A device with no local graph at all still adopts
|
|
1073
|
+
// revisions above the floor: only what the deleting machine had already seen is known to
|
|
1074
|
+
// belong to the deleted lineage. Everything else stays in the immutable snapshot cache,
|
|
1075
|
+
// which would otherwise make the replacement open as the old graph again.
|
|
1076
|
+
const floor = floorOf ? await floorOf(graph) : undefined;
|
|
1077
|
+
if (floor !== undefined && current < graph.revision && (current >= 1 || graph.revision <= floor)) {
|
|
1078
|
+
// A live replacement can still take a later revision of its own lineage: storage pins
|
|
1079
|
+
// metadata.createdAt per lineage (a save takes it from the stored head, never from the
|
|
1080
|
+
// submitted graph), every save of the lineage preserves it, and a foreign lineage cannot
|
|
1081
|
+
// produce it. A snapshot above the head that carries the replacement's creation time is a
|
|
1082
|
+
// later edit of the replacement — another device that adopted it and saved — so it advances
|
|
1083
|
+
// the pointer like any save. Anything else belongs to the deleted lineage the floor keeps
|
|
1084
|
+
// out: the replacement is young, or the revision predates it, or no replacement lives here.
|
|
1085
|
+
let replacementCreatedAt;
|
|
1086
|
+
if (current >= 1) {
|
|
1087
|
+
// An unreadable head cannot vouch for any lineage, so the verdict stays refusal.
|
|
1088
|
+
try {
|
|
1089
|
+
replacementCreatedAt = JSON.parse(await readFile(join(folder, `${current}.json`), 'utf8'))?.metadata?.createdAt;
|
|
1090
|
+
}
|
|
1091
|
+
catch {
|
|
1092
|
+
replacementCreatedAt = undefined;
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
if (replacementCreatedAt === undefined || graph.metadata?.createdAt !== replacementCreatedAt)
|
|
1096
|
+
return { graph, restored: false };
|
|
1097
|
+
}
|
|
957
1098
|
const snapshot = join(folder, `${graph.revision}.json`);
|
|
958
1099
|
let exists = false;
|
|
959
1100
|
try {
|
|
@@ -975,27 +1116,11 @@ export async function restoreGraphRevision(input, directory) {
|
|
|
975
1116
|
}
|
|
976
1117
|
if (!exists)
|
|
977
1118
|
await writeFile(snapshot, JSON.stringify(graph, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
|
|
978
|
-
let current = 0;
|
|
979
|
-
try {
|
|
980
|
-
const raw = await readFile(join(folder, 'latest.json'), 'utf8');
|
|
981
|
-
try {
|
|
982
|
-
current = JSON.parse(raw);
|
|
983
|
-
}
|
|
984
|
-
catch {
|
|
985
|
-
throw new GraphConflictError('The local latest pointer is damaged; preserve it as a conflict.');
|
|
986
|
-
}
|
|
987
|
-
}
|
|
988
|
-
catch (error) {
|
|
989
|
-
if (error.code !== 'ENOENT')
|
|
990
|
-
throw error;
|
|
991
|
-
}
|
|
992
|
-
if (!Number.isSafeInteger(current) || current < 0)
|
|
993
|
-
throw new GraphConflictError('Invalid latest revision');
|
|
994
1119
|
if (graph.revision > current) {
|
|
995
1120
|
await writeFile(temp, JSON.stringify(graph.revision), { flag: 'wx', mode: 0o600 });
|
|
996
1121
|
await rename(temp, join(folder, 'latest.json'));
|
|
997
1122
|
}
|
|
998
|
-
return graph;
|
|
1123
|
+
return { graph, restored: true };
|
|
999
1124
|
}
|
|
1000
1125
|
finally {
|
|
1001
1126
|
await unlink(temp).catch(() => { });
|
|
@@ -1008,9 +1133,9 @@ export async function loadGraph(id, revision, directory = configDirectory()) {
|
|
|
1008
1133
|
if (revision !== undefined && (!Number.isSafeInteger(revision) || revision < 1))
|
|
1009
1134
|
throw new Error('Invalid graph revision');
|
|
1010
1135
|
if (id === 'default') {
|
|
1011
|
-
if (revision !== undefined && ![1, 2, 3, 4, 5].includes(revision))
|
|
1136
|
+
if (revision !== undefined && ![1, 2, 3, 4, 5, 6].includes(revision))
|
|
1012
1137
|
throw new Error('Default graph revision does not exist');
|
|
1013
|
-
return structuredClone(revision === 1 ? LEGACY_DEFAULT_HARNESS : revision === 2 ? DEFAULT_HARNESS_REVISION_2 : revision === 3 ? DEFAULT_HARNESS_REVISION_3 : revision === 4 ? DEFAULT_HARNESS_REVISION_4 : DEFAULT_HARNESS);
|
|
1138
|
+
return structuredClone(revision === 1 ? LEGACY_DEFAULT_HARNESS : revision === 2 ? DEFAULT_HARNESS_REVISION_2 : revision === 3 ? DEFAULT_HARNESS_REVISION_3 : revision === 4 ? DEFAULT_HARNESS_REVISION_4 : revision === 5 ? DEFAULT_HARNESS_REVISION_5 : DEFAULT_HARNESS);
|
|
1014
1139
|
}
|
|
1015
1140
|
const folder = join(directory, 'graphs', id);
|
|
1016
1141
|
const selected = revision ?? JSON.parse(await readFile(join(folder, 'latest.json'), 'utf8'));
|
|
@@ -1100,3 +1225,32 @@ export async function saveGraph(input, expectedRevision, directory = configDirec
|
|
|
1100
1225
|
await releaseLock();
|
|
1101
1226
|
}
|
|
1102
1227
|
}
|
|
1228
|
+
/**
|
|
1229
|
+
* Remove a saved graph and its whole revision history.
|
|
1230
|
+
*
|
|
1231
|
+
* The save lock serializes against a save or cloud restore of the same graph, so a delete cannot
|
|
1232
|
+
* race one into leaving a half-written folder behind. The folder leaves the live path in one
|
|
1233
|
+
* rename while the lock is held, so a save that lands during the removal writes into a fresh
|
|
1234
|
+
* folder and survives it. Deleting the bundled `default` is refused: it has no storage to remove,
|
|
1235
|
+
* and a hidden preset would only return on the next launch.
|
|
1236
|
+
*/
|
|
1237
|
+
export async function deleteGraph(id, directory = configDirectory(), options = {}) {
|
|
1238
|
+
if (!validId(id) || id === 'default')
|
|
1239
|
+
throw new Error('Invalid graph id');
|
|
1240
|
+
const folder = join(directory, 'graphs', id);
|
|
1241
|
+
let releaseLock;
|
|
1242
|
+
try {
|
|
1243
|
+
releaseLock = await acquireSaveLock(folder);
|
|
1244
|
+
}
|
|
1245
|
+
catch (error) {
|
|
1246
|
+
if (error instanceof SaveLockBusyError)
|
|
1247
|
+
throw new GraphConflictError('Wait for the current save before deleting this graph.');
|
|
1248
|
+
throw error;
|
|
1249
|
+
}
|
|
1250
|
+
try {
|
|
1251
|
+
await removeLockedFolder(folder, options.onDetached);
|
|
1252
|
+
}
|
|
1253
|
+
finally {
|
|
1254
|
+
await releaseLock();
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { type CliExecutableSpec } from './cli-executable.js';
|
|
2
|
+
import type { ModelAdapter, ModelResponse, ToolSchema } from './types.js';
|
|
3
|
+
/** A marker, not an endpoint: requests go through the signed-in Grok CLI on this machine. */
|
|
4
|
+
export declare const GROK_BASE_URL = "https://api.x.ai";
|
|
5
|
+
export declare const GROK_EXECUTABLE: CliExecutableSpec;
|
|
6
|
+
/**
|
|
7
|
+
* The child environment: the parent's, minus every xAI key the CLI would fall back to.
|
|
8
|
+
*
|
|
9
|
+
* A subscription provider must be billed to the signed-in account or fail; a stray `XAI_API_KEY`
|
|
10
|
+
* in the parent environment would otherwise turn a signed-out run into metered API usage.
|
|
11
|
+
*/
|
|
12
|
+
export declare function grokEnvironment(source?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
|
|
13
|
+
export interface GrokRunOptions {
|
|
14
|
+
files?: Record<string, string>;
|
|
15
|
+
captureStderr?: boolean;
|
|
16
|
+
acceptedExitCodes?: number[];
|
|
17
|
+
}
|
|
18
|
+
export type GrokRun = (args: (cwd: string) => string[], signal: AbortSignal, options?: GrokRunOptions) => Promise<{
|
|
19
|
+
stdout: string;
|
|
20
|
+
stderr: string;
|
|
21
|
+
}>;
|
|
22
|
+
export interface GrokDependencies {
|
|
23
|
+
run?: GrokRun;
|
|
24
|
+
}
|
|
25
|
+
export declare const runGrokProcess: GrokRun;
|
|
26
|
+
/** What `grok models` says about the sign-in and the catalog it serves. */
|
|
27
|
+
export declare function parseGrokModels(output: string): {
|
|
28
|
+
signedIn: boolean;
|
|
29
|
+
models: string[];
|
|
30
|
+
email?: string;
|
|
31
|
+
};
|
|
32
|
+
/** Read the CLI's sign-in state and model catalog without inference. */
|
|
33
|
+
export declare function readGrokCatalog(signal: AbortSignal, dependencies?: GrokDependencies): Promise<{
|
|
34
|
+
signedIn: boolean;
|
|
35
|
+
models: string[];
|
|
36
|
+
email?: string;
|
|
37
|
+
}>;
|
|
38
|
+
/**
|
|
39
|
+
* Accept one model step only, from the Messages-shaped stream the CLI prints.
|
|
40
|
+
*
|
|
41
|
+
* Any native tool the CLI exposed or the model called is refused: the step must come back as the
|
|
42
|
+
* structured object, and Andorra alone executes what it names.
|
|
43
|
+
*/
|
|
44
|
+
export declare function parseGrokResponse(output: string, tools?: readonly Pick<ToolSchema, 'name'>[]): ModelResponse;
|
|
45
|
+
/** A text-only step: every assistant text block, in order, and nothing else. */
|
|
46
|
+
export declare function parseGrokText(output: string): ModelResponse;
|
|
47
|
+
/** Grok produces one model response; Andorra owns tool execution, graph state, and permissions. */
|
|
48
|
+
export declare function createGrokAdapter(_config: {
|
|
49
|
+
model: string;
|
|
50
|
+
}, dependencies?: GrokDependencies): ModelAdapter;
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { resolveCliExecutable } from './cli-executable.js';
|
|
3
|
+
import { runBoundedCli } from './cli-process.js';
|
|
4
|
+
import { allowanceInstruction, boundTextStep, parseStructuredStep, STRUCTURED_STEP_PROMPT, STRUCTURED_STEP_SCHEMA, structuredStepPrompt, TEXT_STEP_PROMPT } from './structured-step.js';
|
|
5
|
+
/** A marker, not an endpoint: requests go through the signed-in Grok CLI on this machine. */
|
|
6
|
+
export const GROK_BASE_URL = 'https://api.x.ai';
|
|
7
|
+
export const GROK_EXECUTABLE = {
|
|
8
|
+
names: ['grok'], overrideEnv: 'ANDORRA_GROK_PATH', homeDirectories: [join('.grok', 'bin')],
|
|
9
|
+
installMessage: 'Install the Grok CLI from x.ai, sign in, then retry the Grok provider.',
|
|
10
|
+
};
|
|
11
|
+
const SIGN_IN_MESSAGE = 'Sign in to Grok (grok login) on this machine, then retry the Grok provider.';
|
|
12
|
+
const REQUEST_TIMEOUT_MS = 10 * 60_000;
|
|
13
|
+
const CATALOG_TIMEOUT_MS = 30_000;
|
|
14
|
+
/**
|
|
15
|
+
* The child environment: the parent's, minus every xAI key the CLI would fall back to.
|
|
16
|
+
*
|
|
17
|
+
* A subscription provider must be billed to the signed-in account or fail; a stray `XAI_API_KEY`
|
|
18
|
+
* in the parent environment would otherwise turn a signed-out run into metered API usage.
|
|
19
|
+
*/
|
|
20
|
+
export function grokEnvironment(source = process.env) {
|
|
21
|
+
const env = Object.fromEntries(Object.entries(source).filter(([key]) => !/^(?:XAI_|GROK_API_KEY$|NODE_OPTIONS$)/i.test(key)));
|
|
22
|
+
return { ...env, GROK_DISABLE_AUTOUPDATER: '1', NO_COLOR: '1' };
|
|
23
|
+
}
|
|
24
|
+
export const runGrokProcess = async (args, signal, options = {}) => {
|
|
25
|
+
const executable = await resolveCliExecutable(GROK_EXECUTABLE);
|
|
26
|
+
return runBoundedCli(executable, args, signal, { env: grokEnvironment(), label: 'Grok CLI', ...options });
|
|
27
|
+
};
|
|
28
|
+
/** What `grok models` says about the sign-in and the catalog it serves. */
|
|
29
|
+
export function parseGrokModels(output) {
|
|
30
|
+
const plain = output.replace(/\u001b\[[0-9;]*m/g, '');
|
|
31
|
+
const models = [];
|
|
32
|
+
for (const line of plain.split(/\r?\n/)) {
|
|
33
|
+
const bullet = line.match(/^\s*[*-]\s+(\S+)/);
|
|
34
|
+
if (bullet?.[1] && !models.includes(bullet[1]) && models.length < 1000)
|
|
35
|
+
models.push(bullet[1]);
|
|
36
|
+
}
|
|
37
|
+
const signedOut = /\bnot (?:authenticated|signed in|logged in)\b/i.test(plain);
|
|
38
|
+
const email = plain.match(/\b(?:logged|signed) in as\s+([^\s@]+@[^\s@]+\.[^\s.,;)]+)/i)?.[1];
|
|
39
|
+
return { signedIn: !signedOut && models.length > 0, models: signedOut ? [] : models, ...(email && !signedOut ? { email } : {}) };
|
|
40
|
+
}
|
|
41
|
+
/** Read the CLI's sign-in state and model catalog without inference. */
|
|
42
|
+
export async function readGrokCatalog(signal, dependencies = {}) {
|
|
43
|
+
const run = dependencies.run ?? runGrokProcess;
|
|
44
|
+
const bounded = AbortSignal.any([signal, AbortSignal.timeout(CATALOG_TIMEOUT_MS)]);
|
|
45
|
+
// `models` takes no update flag; the environment already turns the updater off.
|
|
46
|
+
const { stdout, stderr } = await run(() => ['models'], bounded, { captureStderr: true, acceptedExitCodes: [0, 1] });
|
|
47
|
+
return parseGrokModels(`${stdout}\n${stderr}`);
|
|
48
|
+
}
|
|
49
|
+
function parseJson(text) {
|
|
50
|
+
try {
|
|
51
|
+
return JSON.parse(text);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
throw new Error('Grok CLI returned malformed JSON');
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function frames(text) { return text.split(/\r?\n/).filter(line => line.trim().startsWith('{')).map(parseJson); }
|
|
58
|
+
/** Messages API usage; `input_tokens` is uncached only, so both cache buckets join it. */
|
|
59
|
+
function grokUsage(usage) {
|
|
60
|
+
if (!usage || typeof usage !== 'object')
|
|
61
|
+
return undefined;
|
|
62
|
+
const token = (name) => Number.isSafeInteger(usage[name]) && usage[name] >= 0 ? usage[name] : undefined;
|
|
63
|
+
const input = token('input_tokens');
|
|
64
|
+
const output = token('output_tokens');
|
|
65
|
+
const read = token('cache_read_input_tokens');
|
|
66
|
+
const created = token('cache_creation_input_tokens');
|
|
67
|
+
// An all-zero ledger means the CLI could not account for the turn, not that it was free.
|
|
68
|
+
if (!input && !output && !read && !created)
|
|
69
|
+
return { requests: 1 };
|
|
70
|
+
return { requests: 1,
|
|
71
|
+
...(input === undefined ? {} : { inputTokens: input + (read ?? 0) + (created ?? 0) }),
|
|
72
|
+
...(output === undefined ? {} : { outputTokens: output }),
|
|
73
|
+
...(read === undefined ? {} : { cacheRead: read }), ...(created === undefined ? {} : { cacheWrite: created }) };
|
|
74
|
+
}
|
|
75
|
+
function failure(message) {
|
|
76
|
+
if (typeof message === 'string' && /not (?:signed in|authenticated|logged in)/i.test(message))
|
|
77
|
+
return new Error(SIGN_IN_MESSAGE);
|
|
78
|
+
return new Error('Grok inference failed. Check its sign-in, model access, and subscription limits.');
|
|
79
|
+
}
|
|
80
|
+
const STRUCTURED_TOOL = /^structured_?output$/i;
|
|
81
|
+
/**
|
|
82
|
+
* Accept one model step only, from the Messages-shaped stream the CLI prints.
|
|
83
|
+
*
|
|
84
|
+
* Any native tool the CLI exposed or the model called is refused: the step must come back as the
|
|
85
|
+
* structured object, and Andorra alone executes what it names.
|
|
86
|
+
*/
|
|
87
|
+
export function parseGrokResponse(output, tools = []) {
|
|
88
|
+
const events = frames(output);
|
|
89
|
+
const error = events.find(frame => frame?.type === 'error');
|
|
90
|
+
if (error)
|
|
91
|
+
throw failure(error.message);
|
|
92
|
+
for (const event of events.filter(frame => frame?.type === 'system' && frame.subtype === 'init')) {
|
|
93
|
+
if (event.tools !== undefined && (!Array.isArray(event.tools) || event.tools.some((name) => typeof name !== 'string' || !STRUCTURED_TOOL.test(name)))) {
|
|
94
|
+
throw new Error('Grok exposed unexpected native tools');
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
for (const event of events.filter(frame => frame?.type === 'assistant')) {
|
|
98
|
+
if (event.parent_tool_use_id || !Array.isArray(event.message?.content))
|
|
99
|
+
throw new Error('Grok returned an invalid assistant step');
|
|
100
|
+
if (event.message.content.some((block) => (block?.type === 'tool_use' || block?.type === 'server_tool_use') && !STRUCTURED_TOOL.test(String(block.name)))) {
|
|
101
|
+
throw new Error('Grok attempted a native tool');
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const results = events.filter(frame => frame?.type === 'result');
|
|
105
|
+
if (results.length !== 1)
|
|
106
|
+
throw new Error('Grok did not return exactly one model result');
|
|
107
|
+
const result = results[0];
|
|
108
|
+
if (result.is_error !== false || result.subtype !== 'success')
|
|
109
|
+
throw failure(Array.isArray(result.errors) ? result.errors.join(' ') : result.result);
|
|
110
|
+
let structured = result.structured_output;
|
|
111
|
+
if (structured === undefined && typeof result.result === 'string') {
|
|
112
|
+
try {
|
|
113
|
+
structured = JSON.parse(result.result);
|
|
114
|
+
}
|
|
115
|
+
catch { /* reported below */ }
|
|
116
|
+
}
|
|
117
|
+
if (structured === undefined)
|
|
118
|
+
throw new Error('Grok did not return a complete Andorra model step');
|
|
119
|
+
const response = parseStructuredStep(structured, tools, 'Grok');
|
|
120
|
+
const usage = grokUsage(result.usage);
|
|
121
|
+
if (usage)
|
|
122
|
+
response.usage = usage;
|
|
123
|
+
return response;
|
|
124
|
+
}
|
|
125
|
+
/** A text-only step: every assistant text block, in order, and nothing else. */
|
|
126
|
+
export function parseGrokText(output) {
|
|
127
|
+
const events = frames(output);
|
|
128
|
+
const error = events.find(frame => frame?.type === 'error');
|
|
129
|
+
if (error)
|
|
130
|
+
throw failure(error.message);
|
|
131
|
+
const results = events.filter(frame => frame?.type === 'result');
|
|
132
|
+
if (results.length !== 1 || results[0].is_error !== false || results[0].subtype !== 'success')
|
|
133
|
+
throw failure(results[0]?.result);
|
|
134
|
+
const texts = [];
|
|
135
|
+
for (const event of events.filter(frame => frame?.type === 'assistant')) {
|
|
136
|
+
for (const block of Array.isArray(event.message?.content) ? event.message.content : []) {
|
|
137
|
+
if (block?.type === 'text' && typeof block.text === 'string')
|
|
138
|
+
texts.push(block.text);
|
|
139
|
+
else if (block?.type === 'tool_use' || block?.type === 'server_tool_use')
|
|
140
|
+
throw new Error('Grok attempted a tool during text generation');
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
const text = texts.length ? texts.join('') : typeof results[0].result === 'string' ? results[0].result : '';
|
|
144
|
+
const usage = grokUsage(results[0].usage);
|
|
145
|
+
return { text, toolCalls: [], ...(usage ? { usage } : {}) };
|
|
146
|
+
}
|
|
147
|
+
/** Flags that leave the CLI a bare model: no built-in tools, subagents, memory, plans, search or updates. */
|
|
148
|
+
const ISOLATION_ARGS = ['--tools', '', '--disallowed-tools', 'Agent', '--no-subagents', '--no-memory', '--no-plan',
|
|
149
|
+
'--disable-web-search', '--no-auto-update', '--permission-mode', 'dontAsk', '--max-turns', '1', '--verbatim'];
|
|
150
|
+
/** Grok produces one model response; Andorra owns tool execution, graph state, and permissions. */
|
|
151
|
+
export function createGrokAdapter(_config, dependencies = {}) {
|
|
152
|
+
const run = dependencies.run ?? runGrokProcess;
|
|
153
|
+
return {
|
|
154
|
+
async listModels(signal) {
|
|
155
|
+
const catalog = await readGrokCatalog(signal, dependencies);
|
|
156
|
+
if (!catalog.signedIn)
|
|
157
|
+
throw new Error(SIGN_IN_MESSAGE);
|
|
158
|
+
return catalog.models;
|
|
159
|
+
},
|
|
160
|
+
async generate(request) {
|
|
161
|
+
request.signal.throwIfAborted();
|
|
162
|
+
const auxiliary = request.maxTokens !== undefined;
|
|
163
|
+
if (auxiliary && (!Number.isSafeInteger(request.maxTokens) || request.maxTokens < 1))
|
|
164
|
+
throw new Error('Invalid auxiliary output allowance.');
|
|
165
|
+
if (auxiliary && request.tools.length)
|
|
166
|
+
throw new Error('Grok cannot apply an auxiliary output allowance to tool-bearing requests.');
|
|
167
|
+
const signal = AbortSignal.any([request.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)]);
|
|
168
|
+
const imageCount = request.messages.reduce((total, message) => total + (message.images?.length ?? 0), 0);
|
|
169
|
+
// The prompt travels in a file: a conversation outgrows the Windows command-line limit, and the
|
|
170
|
+
// CLI does not read stdin in headless mode. Images cannot be forwarded through it yet, so the
|
|
171
|
+
// model is told how many were left out rather than reasoning as if it had seen them.
|
|
172
|
+
const prompt = JSON.stringify({ ...JSON.parse(structuredStepPrompt(request)),
|
|
173
|
+
...(imageCount ? { omittedImages: `This provider cannot forward images; ${imageCount} image${imageCount === 1 ? ' was' : 's were'} omitted from the conversation.` } : {}) });
|
|
174
|
+
request.onRequest?.();
|
|
175
|
+
const { stdout } = await run(cwd => ['--prompt-file', join(cwd, 'prompt.json'), '--output-format', 'streaming-messages-json',
|
|
176
|
+
'-m', request.model, ...ISOLATION_ARGS,
|
|
177
|
+
...(auxiliary ? ['--system-prompt-override', `${TEXT_STEP_PROMPT} ${allowanceInstruction(request.maxTokens)}`] : ['--json-schema', JSON.stringify(STRUCTURED_STEP_SCHEMA), '--system-prompt-override', STRUCTURED_STEP_PROMPT])], signal, { files: { 'prompt.json': prompt }, acceptedExitCodes: [0, 1] });
|
|
178
|
+
signal.throwIfAborted();
|
|
179
|
+
if (!auxiliary)
|
|
180
|
+
return parseGrokResponse(stdout, request.tools);
|
|
181
|
+
// The CLI has no output cap, so the allowance is stated above and enforced on the answer.
|
|
182
|
+
const text = parseGrokText(stdout);
|
|
183
|
+
return boundTextStep(text, request.maxTokens, text.usage?.outputTokens);
|
|
184
|
+
},
|
|
185
|
+
};
|
|
186
|
+
}
|
package/dist/src/handoffs.d.ts
CHANGED
|
@@ -29,6 +29,19 @@ export interface ValueScope {
|
|
|
29
29
|
export declare function validateMappingConstants(graph: unknown): void;
|
|
30
30
|
export declare function validateSchema(schema: unknown, path?: string, depth?: number): asserts schema is JsonSchema;
|
|
31
31
|
export declare function validateValue(schema: JsonSchema, value: unknown, path?: string): void;
|
|
32
|
+
/** A mapping read a value its scope does not hold (an omitted optional field, unset state). */
|
|
33
|
+
export declare class MissingReferenceError extends Error {
|
|
34
|
+
}
|
|
32
35
|
export declare function resolveValue(expression: ValueExpression, scope: ValueScope): unknown;
|
|
36
|
+
/**
|
|
37
|
+
* Whether a mapping failure only means the input is absent. validateMappings refuses to map a field
|
|
38
|
+
* the source schema marks optional into a required destination input, and accepts it into an
|
|
39
|
+
* optional one, so the runtime honours the same contract: a missing value for an optional input
|
|
40
|
+
* leaves the input out and the target runs, while one for a required input (reachable only through
|
|
41
|
+
* an open source schema) still stops the run.
|
|
42
|
+
*/
|
|
43
|
+
export declare function isAbsentOptionalInput(error: unknown, key: string, inputSchema: JsonSchema | undefined): boolean;
|
|
44
|
+
/** Resolve a node's or edge's input mapping into the target's inputs, leaving absent optional inputs out. */
|
|
45
|
+
export declare function resolveMapping(mapping: Record<string, ValueExpression> | undefined, scope: ValueScope, inputSchema: JsonSchema | undefined): Record<string, unknown>;
|
|
33
46
|
export declare function schemaAt(schema: JsonSchema | undefined, keys: string[], label: string, requirePresent?: boolean): JsonSchema | undefined;
|
|
34
47
|
export declare function validateMappings(graph: Graph): void;
|