@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
|
@@ -6,6 +6,7 @@ import { andorraConvertMessages, andorraConvertTools } from '../vendor/engine/ru
|
|
|
6
6
|
import { andorraNormalizeContext } from '../vendor/engine/runtime/ai/utils/transcript.js';
|
|
7
7
|
import { andorraClampMaxTokensToContext } from '../vendor/engine/runtime/ai/api/simple-options.js';
|
|
8
8
|
import { isEngineContextOverflow, toEngineMessages } from './provider-engine.js';
|
|
9
|
+
import { encodeProviderToolNames } from './tool-names.js';
|
|
9
10
|
import { assertRequestTimeout, assertStreamIdleTimeout, configuredContextWindow, resolveProviderApiKey, DEFAULT_REQUEST_TIMEOUT_MS, ProviderRequestError } from './providers.js';
|
|
10
11
|
import { OPENCODE_GO_BASE_URL, OPENCODE_GO_MODEL_SNAPSHOT, readOpenCodeModels } from './opencode-catalog.js';
|
|
11
12
|
const OUTPUT_LIMIT = 4 * 1024 * 1024;
|
|
@@ -200,6 +201,10 @@ export function createOpenCodeAdapter(config, dependencies = {}) {
|
|
|
200
201
|
throw new Error('The selected OpenCode Go model does not support this reasoning effort.');
|
|
201
202
|
const session = createHash('sha256').update(`${request.context?.runId ?? fallbackSession}/${request.context?.subagentId ?? ''}`).digest('hex');
|
|
202
203
|
const protocol = metadata.protocol;
|
|
204
|
+
// Strict provider name rules apply on every Go protocol; the dotted canonical names travel
|
|
205
|
+
// encoded and are decoded back before the result reaches the executor.
|
|
206
|
+
const { tools: providerTools, codec } = encodeProviderToolNames(request.tools);
|
|
207
|
+
const decodeCalls = (calls) => calls.map(call => ({ ...call, name: codec.decode(call.name) }));
|
|
203
208
|
const model = { id: request.model, name: request.model, api: protocol, provider: config.id,
|
|
204
209
|
baseUrl: `${OPENCODE_GO_BASE_URL}/${protocol === 'anthropic-messages' ? 'anthropic/v1' : 'openai/v1'}`,
|
|
205
210
|
contextWindow: configuredContextWindow(config, request.model) ?? (request.model === config.model ? config.contextWindow : undefined)
|
|
@@ -339,14 +344,14 @@ export function createOpenCodeAdapter(config, dependencies = {}) {
|
|
|
339
344
|
try {
|
|
340
345
|
let result;
|
|
341
346
|
if (protocol === 'google-generative-ai')
|
|
342
|
-
result = await googleResponse(request, model, send, effort);
|
|
347
|
+
result = await googleResponse(request, model, send, effort, providerTools, codec);
|
|
343
348
|
else {
|
|
344
349
|
const nativeRequest = { ...request, messages: request.messages.map(message => {
|
|
345
350
|
const saved = message.providerContinuation;
|
|
346
351
|
return saved && (saved.api !== model.api || saved.provider !== model.provider || saved.model !== model.id)
|
|
347
352
|
? { ...message, reasoningContent: undefined } : message;
|
|
348
353
|
}) };
|
|
349
|
-
const context = andorraNormalizeContext({ messages: toEngineMessages(nativeRequest, model), tools:
|
|
354
|
+
const context = andorraNormalizeContext({ messages: toEngineMessages(nativeRequest, model, codec), tools: providerTools });
|
|
350
355
|
const nativeFetch = async (_url, init) => send(JSON.parse(String(init?.body)));
|
|
351
356
|
const options = {
|
|
352
357
|
apiKey: 'andorra-transport-owned', fetch: nativeFetch, signal, maxRetries: 0,
|
|
@@ -371,6 +376,8 @@ export function createOpenCodeAdapter(config, dependencies = {}) {
|
|
|
371
376
|
}
|
|
372
377
|
if (transportError)
|
|
373
378
|
throw transportError;
|
|
379
|
+
if (result.toolCalls.length)
|
|
380
|
+
result = { ...result, toolCalls: decodeCalls(result.toolCalls) };
|
|
374
381
|
if (signal.aborted)
|
|
375
382
|
throw new Error('OpenCode Go request ended.');
|
|
376
383
|
const ids = new Set();
|
|
@@ -415,8 +422,8 @@ function engineResponse(output, provider, model) {
|
|
|
415
422
|
outputTokens: counter(output.usage.output), cacheRead: counter(output.usage.cacheRead), cacheWrite: counter(output.usage.cacheWrite), requests: 1 } };
|
|
416
423
|
}
|
|
417
424
|
/** Gemini signatures can attach to text AND tool calls; retain the exact parts as opaque replay. */
|
|
418
|
-
async function googleResponse(request, model, send, effort) {
|
|
419
|
-
const engineMessages = toEngineMessages(request, model);
|
|
425
|
+
async function googleResponse(request, model, send, effort, providerTools, codec) {
|
|
426
|
+
const engineMessages = toEngineMessages(request, model, codec);
|
|
420
427
|
// The generic engine boundary stores only thinking blocks. Gemini's entire signed model
|
|
421
428
|
// turn is kept in that opaque slot and restored after the shared transcript conversion.
|
|
422
429
|
for (const [index, message] of engineMessages.entries())
|
|
@@ -437,13 +444,21 @@ async function googleResponse(request, model, send, effort) {
|
|
|
437
444
|
}
|
|
438
445
|
if (!Array.isArray(savedParts))
|
|
439
446
|
malformed();
|
|
447
|
+
// Continuations stored before the transport encoding existed keep the original dotted name in
|
|
448
|
+
// the replayed parts while the matching tool result already travels under the encoded name.
|
|
449
|
+
// Anchor each call to the same encode(canonical) map the serializer gives its functionResponse,
|
|
450
|
+
// falling back to a decode/encode round-trip (identity on post-change parts) when history lost it.
|
|
451
|
+
const historyNames = new Map((request.messages[index].toolCalls ?? []).map(call => [call.id, codec.encode(call.name)]));
|
|
440
452
|
// Restore this exact assistant message before normalization can skip empty turns.
|
|
441
453
|
// Signatures on text and function calls survive the shared Gemini serializer too.
|
|
442
454
|
message.content = savedParts.flatMap((part) => {
|
|
443
455
|
object(part);
|
|
444
|
-
if (part.functionCall)
|
|
445
|
-
|
|
446
|
-
|
|
456
|
+
if (part.functionCall) {
|
|
457
|
+
const call = object(part.functionCall);
|
|
458
|
+
const name = typeof call.name === 'string' ? codec.encode(codec.decode(call.name)) : call.name;
|
|
459
|
+
return [{ type: 'toolCall', id: call.id, name: historyNames.get(call.id) ?? name,
|
|
460
|
+
arguments: object(call.args ?? {}), ...(part.thoughtSignature ? { thoughtSignature: part.thoughtSignature } : {}) }];
|
|
461
|
+
}
|
|
447
462
|
if (typeof part.text === 'string')
|
|
448
463
|
return part.thought ? [{ type: 'thinking', thinking: part.text, thinkingSignature: part.thoughtSignature }]
|
|
449
464
|
: [{ type: 'text', text: part.text, textSignature: part.thoughtSignature }];
|
|
@@ -454,7 +469,7 @@ async function googleResponse(request, model, send, effort) {
|
|
|
454
469
|
const contents = andorraConvertMessages(model, context);
|
|
455
470
|
const system = request.messages.filter(message => message.role === 'system').map(message => message.content).join('\n\n');
|
|
456
471
|
const response = await send({ contents, ...(system ? { systemInstruction: { parts: [{ text: system }] } } : {}),
|
|
457
|
-
tools: andorraConvertTools(
|
|
472
|
+
tools: andorraConvertTools(providerTools), generationConfig: { maxOutputTokens: andorraClampMaxTokensToContext(model, context, Math.min(request.maxTokens ?? model.maxTokens, model.maxTokens)),
|
|
458
473
|
...(effort ? { thinkingConfig: effort === 'none' ? { thinkingBudget: 0 } : { thinkingLevel: effort.toUpperCase() } } : {}) } });
|
|
459
474
|
const text = [], thoughts = [], parts = [];
|
|
460
475
|
const calls = [];
|
package/dist/src/palette.d.ts
CHANGED
|
@@ -15,6 +15,8 @@ export declare const SUBTLE = 250;
|
|
|
15
15
|
export declare const WHITE = 231;
|
|
16
16
|
/** The accent: the brightest neutral, so emphasis reads as strength rather than color. */
|
|
17
17
|
export declare const ACCENT_INDEX = 231;
|
|
18
|
+
/** A picked skill in the composer: bold indigo, so a recognised command reads apart from typed text and amber attachments. */
|
|
19
|
+
export declare const SKILL_CHIP = 147;
|
|
18
20
|
/**
|
|
19
21
|
* Semantic status colors, the only hues in the palette.
|
|
20
22
|
*
|
package/dist/src/palette.js
CHANGED
|
@@ -15,6 +15,8 @@ export const SUBTLE = 250;
|
|
|
15
15
|
export const WHITE = 231;
|
|
16
16
|
/** The accent: the brightest neutral, so emphasis reads as strength rather than color. */
|
|
17
17
|
export const ACCENT_INDEX = WHITE;
|
|
18
|
+
/** A picked skill in the composer: bold indigo, so a recognised command reads apart from typed text and amber attachments. */
|
|
19
|
+
export const SKILL_CHIP = 147;
|
|
18
20
|
/**
|
|
19
21
|
* Semantic status colors, the only hues in the palette.
|
|
20
22
|
*
|
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
import type { ToolContext } from './types.js';
|
|
2
|
-
export declare const PERMISSION_MODES: readonly ["read-only", "ask-for-approval", "approve-for-me", "full-access"];
|
|
2
|
+
export declare const PERMISSION_MODES: readonly ["read-only", "plan", "ask-for-approval", "approve-for-me", "full-access"];
|
|
3
3
|
export type PermissionMode = typeof PERMISSION_MODES[number];
|
|
4
4
|
export declare const PERMISSION_OPTIONS: readonly [{
|
|
5
5
|
readonly id: "read-only";
|
|
6
6
|
readonly label: "Read Only";
|
|
7
7
|
readonly description: "Read workspace files; approval required for edits or internet access.";
|
|
8
|
+
}, {
|
|
9
|
+
readonly id: "plan";
|
|
10
|
+
readonly label: "Plan";
|
|
11
|
+
readonly description: "Research read-only and present a plan; edits run after the plan is approved.";
|
|
8
12
|
}, {
|
|
9
13
|
readonly id: "ask-for-approval";
|
|
10
14
|
readonly label: "Ask for approval";
|
|
@@ -22,7 +26,21 @@ export declare function isPermissionMode(value: unknown): value is PermissionMod
|
|
|
22
26
|
/** Callers canonicalize through realpath first, so symlink aliases share a setting. */
|
|
23
27
|
export declare function workspacePermissionKey(workspace: string): string;
|
|
24
28
|
export declare function permissionMode(context: Pick<ToolContext, 'permissions' | 'yolo' | 'runControl' | 'pinFilePaths'>): PermissionMode | undefined;
|
|
29
|
+
/**
|
|
30
|
+
* Ask approvals one at a time, deciding again any that waited across a live mode change.
|
|
31
|
+
*
|
|
32
|
+
* Concurrent nodes and subagents share one prompt surface, so their approvals queue behind each other.
|
|
33
|
+
* A tool decides to ask under the mode in force when it asks; a live change while its prompt waited
|
|
34
|
+
* leaves that decision stale. The waiting prompt is then handed back as `policy-changed` instead of
|
|
35
|
+
* shown, and its tool decides again: under Full Access it no longer asks, and under a mode that still
|
|
36
|
+
* requires an answer it asks again. Every `approve` caller already loops on that answer.
|
|
37
|
+
*/
|
|
38
|
+
export declare function serializeApprovals(approve: ToolContext['approve'], mode: () => PermissionMode | undefined): ToolContext['approve'];
|
|
25
39
|
export declare function permissionLabel(mode: PermissionMode): string;
|
|
40
|
+
/** The refusal a mutation meets while a plan is presented but not yet approved. */
|
|
41
|
+
export declare const PLAN_MODE_MUTATION_ERROR = "Plan mode: edits are disabled until a plan is approved. Present the plan with present_plan.";
|
|
42
|
+
/** A per-tool approval is not a plan approval. Use at dispatch boundaries after any await. */
|
|
43
|
+
export declare function assertPlanMutationAllowed(context: Pick<ToolContext, 'permissions' | 'yolo' | 'runControl' | 'pinFilePaths'>): void;
|
|
26
44
|
/** Reject remote/device namespaces before any filesystem resolution can contact them. */
|
|
27
45
|
export declare function assertLocalFilePath(name: string): void;
|
|
28
46
|
export declare function protectedPermissionRoots(workspace: string): string[];
|
package/dist/src/permissions.js
CHANGED
|
@@ -2,9 +2,10 @@ import { createHash } from 'node:crypto';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { lstat, readlink } from 'node:fs/promises';
|
|
4
4
|
import { homedir } from 'node:os';
|
|
5
|
-
export const PERMISSION_MODES = ['read-only', 'ask-for-approval', 'approve-for-me', 'full-access'];
|
|
5
|
+
export const PERMISSION_MODES = ['read-only', 'plan', 'ask-for-approval', 'approve-for-me', 'full-access'];
|
|
6
6
|
export const PERMISSION_OPTIONS = [
|
|
7
7
|
{ id: 'read-only', label: 'Read Only', description: 'Read workspace files; approval required for edits or internet access.' },
|
|
8
|
+
{ id: 'plan', label: 'Plan', description: 'Research read-only and present a plan; edits run after the plan is approved.' },
|
|
8
9
|
{ id: 'ask-for-approval', label: 'Ask for approval', description: 'Read, edit and run commands in the workspace; approval required outside the sandbox or for internet access.' },
|
|
9
10
|
{ id: 'approve-for-me', label: 'Approve for me', description: 'Automatically allow sandboxed actions; ask for potentially unsafe actions outside the sandbox.' },
|
|
10
11
|
{ id: 'full-access', label: 'Full Access', description: 'Use with caution: access the host filesystem and internet without approval.' },
|
|
@@ -20,9 +21,37 @@ export function workspacePermissionKey(workspace) {
|
|
|
20
21
|
export function permissionMode(context) {
|
|
21
22
|
return context.pinFilePaths ? 'full-access' : context.runControl?.permissions ?? context.permissions ?? ((context.runControl?.yolo ?? context.yolo) ? 'full-access' : undefined);
|
|
22
23
|
}
|
|
24
|
+
/**
|
|
25
|
+
* Ask approvals one at a time, deciding again any that waited across a live mode change.
|
|
26
|
+
*
|
|
27
|
+
* Concurrent nodes and subagents share one prompt surface, so their approvals queue behind each other.
|
|
28
|
+
* A tool decides to ask under the mode in force when it asks; a live change while its prompt waited
|
|
29
|
+
* leaves that decision stale. The waiting prompt is then handed back as `policy-changed` instead of
|
|
30
|
+
* shown, and its tool decides again: under Full Access it no longer asks, and under a mode that still
|
|
31
|
+
* requires an answer it asks again. Every `approve` caller already loops on that answer.
|
|
32
|
+
*/
|
|
33
|
+
export function serializeApprovals(approve, mode) {
|
|
34
|
+
let tail = Promise.resolve();
|
|
35
|
+
return (name, args, signal) => {
|
|
36
|
+
const decidedUnder = mode();
|
|
37
|
+
const pending = tail.then(() => {
|
|
38
|
+
signal.throwIfAborted();
|
|
39
|
+
return mode() === decidedUnder ? approve(name, args, signal) : 'policy-changed';
|
|
40
|
+
});
|
|
41
|
+
tail = pending.catch(() => { });
|
|
42
|
+
return pending;
|
|
43
|
+
};
|
|
44
|
+
}
|
|
23
45
|
export function permissionLabel(mode) {
|
|
24
46
|
return PERMISSION_OPTIONS.find(option => option.id === mode).label;
|
|
25
47
|
}
|
|
48
|
+
/** The refusal a mutation meets while a plan is presented but not yet approved. */
|
|
49
|
+
export const PLAN_MODE_MUTATION_ERROR = 'Plan mode: edits are disabled until a plan is approved. Present the plan with present_plan.';
|
|
50
|
+
/** A per-tool approval is not a plan approval. Use at dispatch boundaries after any await. */
|
|
51
|
+
export function assertPlanMutationAllowed(context) {
|
|
52
|
+
if (permissionMode(context) === 'plan')
|
|
53
|
+
throw new Error(PLAN_MODE_MUTATION_ERROR);
|
|
54
|
+
}
|
|
26
55
|
/** Reject remote/device namespaces before any filesystem resolution can contact them. */
|
|
27
56
|
export function assertLocalFilePath(name) {
|
|
28
57
|
if (/^[\\/]{2}/.test(name) || /^\\(?:\?\?|Device|GLOBAL\?\?)\\/i.test(name)) {
|
|
@@ -19,8 +19,17 @@ export declare class PowerShellWorker {
|
|
|
19
19
|
constructor(workspace: string, onClose: () => void, terminate?: typeof stopProcessTree);
|
|
20
20
|
private append;
|
|
21
21
|
private onStdout;
|
|
22
|
-
execute(command: string, timeout: number, signal: AbortSignal, launchPolicy: () => ShellSandbox | undefined): Promise<string>;
|
|
22
|
+
execute(command: string, timeout: number, signal: AbortSignal, launchPolicy: () => ShellSandbox | undefined, onOutput?: (text: string) => void): Promise<string>;
|
|
23
23
|
dispose(error?: Error): Promise<void>;
|
|
24
24
|
}
|
|
25
|
-
export declare function runPooledPowerShell(command: string, workspace: string, timeout: number, signal: AbortSignal, launchPolicy: () => ShellSandbox | undefined): Promise<string>;
|
|
25
|
+
export declare function runPooledPowerShell(command: string, workspace: string, timeout: number, signal: AbortSignal, launchPolicy: () => ShellSandbox | undefined, onOutput?: (text: string) => void): Promise<string>;
|
|
26
|
+
/** The workspaces that currently hold a pooled interpreter. */
|
|
27
|
+
export declare function pooledPowerShellWorkspaces(): string[];
|
|
28
|
+
/**
|
|
29
|
+
* Ends the pooled interpreter of `root` and of every folder under it, and waits until each process
|
|
30
|
+
* tree is gone. For a workspace that is about to be deleted: an idle interpreter stays alive for
|
|
31
|
+
* `IDLE_MS` with the workspace as its current directory, which keeps Windows from removing the
|
|
32
|
+
* folder. A command still running there fails as disposed. Never throws.
|
|
33
|
+
*/
|
|
34
|
+
export declare function disposePooledPowerShellUnder(root: string): Promise<void>;
|
|
26
35
|
export declare function disposePooledPowerShell(): Promise<void>;
|
|
@@ -78,6 +78,7 @@ export class PowerShellWorker {
|
|
|
78
78
|
this.active.output = this.active.output.slice(-MAX_OUTPUT);
|
|
79
79
|
this.active.truncated = true;
|
|
80
80
|
}
|
|
81
|
+
this.active.onOutput?.(text);
|
|
81
82
|
}
|
|
82
83
|
onStdout(text) {
|
|
83
84
|
if (!this.active) {
|
|
@@ -88,7 +89,19 @@ export class PowerShellWorker {
|
|
|
88
89
|
const prefix = '\u001eANDORRA_DONE:' + this.active.id + ':';
|
|
89
90
|
const start = this.stdoutPending.indexOf(prefix);
|
|
90
91
|
if (start < 0) {
|
|
91
|
-
|
|
92
|
+
// The completion marker always begins with the record separator, so only text from its last
|
|
93
|
+
// occurrence can still grow into the marker; everything before that is finished output and
|
|
94
|
+
// leaves at once. Holding back the marker's whole width instead would delay a live tail by
|
|
95
|
+
// as many characters as the marker is long, which is several lines of a command's output.
|
|
96
|
+
let safeLength = this.stdoutPending.length;
|
|
97
|
+
const candidate = this.stdoutPending.lastIndexOf('\u001e');
|
|
98
|
+
if (candidate >= 0) {
|
|
99
|
+
const tail = this.stdoutPending.slice(candidate);
|
|
100
|
+
// Text that already diverged from the marker is output: no earlier position can start the
|
|
101
|
+
// marker either, so nothing is held.
|
|
102
|
+
if (tail.length <= prefix.length && prefix.startsWith(tail))
|
|
103
|
+
safeLength = candidate;
|
|
104
|
+
}
|
|
92
105
|
this.append(this.stdoutPending.slice(0, safeLength));
|
|
93
106
|
this.stdoutPending = this.stdoutPending.slice(safeLength);
|
|
94
107
|
return;
|
|
@@ -101,7 +114,7 @@ export class PowerShellWorker {
|
|
|
101
114
|
this.stdoutPending = '';
|
|
102
115
|
this.active.finish(Number.isInteger(code) ? code : 1);
|
|
103
116
|
}
|
|
104
|
-
execute(command, timeout, signal, launchPolicy) {
|
|
117
|
+
execute(command, timeout, signal, launchPolicy, onOutput) {
|
|
105
118
|
const doExecute = () => new Promise((resolve, reject) => {
|
|
106
119
|
if (this.closed) {
|
|
107
120
|
reject(new Error('PowerShell worker is unavailable'));
|
|
@@ -134,7 +147,7 @@ export class PowerShellWorker {
|
|
|
134
147
|
void this.dispose().then(() => reject(error), cleanupError => reject(new AggregateError([error, cleanupError], 'PowerShell failed and process cleanup failed')));
|
|
135
148
|
};
|
|
136
149
|
this.active = {
|
|
137
|
-
id, output: '', truncated: false,
|
|
150
|
+
id, output: '', truncated: false, onOutput,
|
|
138
151
|
fail,
|
|
139
152
|
finish: (code) => {
|
|
140
153
|
if (settled)
|
|
@@ -191,7 +204,7 @@ export class PowerShellWorker {
|
|
|
191
204
|
}
|
|
192
205
|
}
|
|
193
206
|
const workers = new Map();
|
|
194
|
-
export async function runPooledPowerShell(command, workspace, timeout, signal, launchPolicy) {
|
|
207
|
+
export async function runPooledPowerShell(command, workspace, timeout, signal, launchPolicy, onOutput) {
|
|
195
208
|
if (process.platform !== 'win32')
|
|
196
209
|
throw new Error('Persistent PowerShell is Windows-only');
|
|
197
210
|
if (!command.trim() || command.includes('\0') || command.length > 32_000)
|
|
@@ -220,7 +233,7 @@ export async function runPooledPowerShell(command, workspace, timeout, signal, l
|
|
|
220
233
|
spawnToCloseMs: Date.now() - started, cleanupMs: 0, timedOut, aborted, exitCode,
|
|
221
234
|
});
|
|
222
235
|
try {
|
|
223
|
-
const output = await worker.execute(command, timeout, signal, launchPolicy);
|
|
236
|
+
const output = await worker.execute(command, timeout, signal, launchPolicy, onOutput);
|
|
224
237
|
collect(0, false, false);
|
|
225
238
|
return output;
|
|
226
239
|
}
|
|
@@ -229,6 +242,22 @@ export async function runPooledPowerShell(command, workspace, timeout, signal, l
|
|
|
229
242
|
throw error;
|
|
230
243
|
}
|
|
231
244
|
}
|
|
245
|
+
/** The workspaces that currently hold a pooled interpreter. */
|
|
246
|
+
export function pooledPowerShellWorkspaces() { return [...workers.keys()]; }
|
|
247
|
+
/**
|
|
248
|
+
* Ends the pooled interpreter of `root` and of every folder under it, and waits until each process
|
|
249
|
+
* tree is gone. For a workspace that is about to be deleted: an idle interpreter stays alive for
|
|
250
|
+
* `IDLE_MS` with the workspace as its current directory, which keeps Windows from removing the
|
|
251
|
+
* folder. A command still running there fails as disposed. Never throws.
|
|
252
|
+
*/
|
|
253
|
+
export async function disposePooledPowerShellUnder(root) {
|
|
254
|
+
const base = path.resolve(root).toLowerCase();
|
|
255
|
+
const owned = [...workers.values()].filter(worker => {
|
|
256
|
+
const inside = path.relative(base, path.resolve(worker.workspace).toLowerCase());
|
|
257
|
+
return inside === '' || (!inside.startsWith('..') && !path.isAbsolute(inside));
|
|
258
|
+
});
|
|
259
|
+
await Promise.all(owned.map(worker => worker.dispose().catch(() => { })));
|
|
260
|
+
}
|
|
232
261
|
export async function disposePooledPowerShell() {
|
|
233
262
|
await Promise.all([...workers.values()].map(worker => worker.dispose()));
|
|
234
263
|
workers.clear();
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { readCodexCatalog } from './codex-provider.js';
|
|
2
2
|
import { codexConnectFor } from './codex-rpc.js';
|
|
3
3
|
import { readClaudeCatalog } from './claude-provider.js';
|
|
4
|
+
import { readGrokCatalog } from './grok-provider.js';
|
|
5
|
+
import { readOpenCodeCatalog } from './opencode-cli-provider.js';
|
|
6
|
+
import { CliUnavailableError } from './cli-executable.js';
|
|
4
7
|
import { deadlinePhrase } from './providers.js';
|
|
5
8
|
import { providerAuthHeaders } from './anthropic-credentials.js';
|
|
6
9
|
/** The wall-clock ceiling for one test: long enough for a cold local server, short enough for a button. */
|
|
@@ -60,6 +63,39 @@ export async function testProviderConnection(provider, signal, deps = {}) {
|
|
|
60
63
|
return failed(bounded.aborted ? 'The Claude Code sign-in check timed out.' : 'Claude Code sign-in or model discovery is unavailable.');
|
|
61
64
|
}
|
|
62
65
|
}
|
|
66
|
+
if (provider.type === 'grok') {
|
|
67
|
+
try {
|
|
68
|
+
const catalog = await readGrokCatalog(bounded);
|
|
69
|
+
signal.throwIfAborted();
|
|
70
|
+
if (!catalog.signedIn)
|
|
71
|
+
return failed('Sign in to Grok on this machine before using this provider.');
|
|
72
|
+
return { ok: true, latencyMs: Date.now() - startedAt, modelCount: catalog.models.length,
|
|
73
|
+
...(provider.model.trim() ? { modelAvailable: catalog.models.includes(provider.model) } : {}) };
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
signal.throwIfAborted();
|
|
77
|
+
if (error instanceof CliUnavailableError)
|
|
78
|
+
return failed(error.message);
|
|
79
|
+
return failed(bounded.aborted ? 'The Grok sign-in check timed out.' : 'Grok sign-in or model discovery is unavailable.');
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (provider.type === 'opencode') {
|
|
83
|
+
try {
|
|
84
|
+
const catalog = await readOpenCodeCatalog(bounded);
|
|
85
|
+
signal.throwIfAborted();
|
|
86
|
+
if (!catalog.models.length)
|
|
87
|
+
return failed('OpenCode has no connected provider. Sign in to one from the provider settings.');
|
|
88
|
+
const ids = catalog.models.map(model => model.id);
|
|
89
|
+
return { ok: true, latencyMs: Date.now() - startedAt, modelCount: ids.length,
|
|
90
|
+
...(provider.model.trim() ? { modelAvailable: ids.includes(provider.model) } : {}) };
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
signal.throwIfAborted();
|
|
94
|
+
if (error instanceof CliUnavailableError)
|
|
95
|
+
return failed(error.message);
|
|
96
|
+
return failed(bounded.aborted ? 'The OpenCode check timed out.' : 'OpenCode is unavailable. Check the OpenCode CLI and try again.');
|
|
97
|
+
}
|
|
98
|
+
}
|
|
63
99
|
if (provider.type === 'codex') {
|
|
64
100
|
try {
|
|
65
101
|
const catalog = await (deps.codexCatalog ?? ((codexSignal) => readCodexCatalog(codexSignal, codexConnectFor(provider))))(bounded);
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { Message as EngineMessage, Model } from '../vendor/engine/runtime/ai/types.js';
|
|
2
2
|
import type { GenerateRequest, ModelResponse } from './types.js';
|
|
3
|
+
import { type ProviderToolNameCodec } from './tool-names.js';
|
|
3
4
|
/** Host transport policy stays outside the copied serializers and stream parsers. */
|
|
4
5
|
export interface EngineTransport {
|
|
5
6
|
providerId: string;
|
|
@@ -32,6 +33,6 @@ export declare function isEngineContextOverflow(errorMessage: string): boolean;
|
|
|
32
33
|
*/
|
|
33
34
|
export declare function relocateConversationBreakpoint(body: Record<string, unknown>, mutableTail: number): void;
|
|
34
35
|
/** Convert at the provider boundary; reasoning is continuation state, never visible text. */
|
|
35
|
-
export declare function toEngineMessages(request: GenerateRequest, model: Model<any
|
|
36
|
+
export declare function toEngineMessages(request: GenerateRequest, model: Model<any>, names?: ProviderToolNameCodec): EngineMessage[];
|
|
36
37
|
/** Run the copied provider implementation, with compatibility for whole-JSON servers. */
|
|
37
38
|
export declare function generateEngineResponse(request: GenerateRequest, host: EngineTransport): Promise<ModelResponse>;
|
|
@@ -4,6 +4,7 @@ import { andorraNormalizeContext } from '../vendor/engine/runtime/ai/utils/trans
|
|
|
4
4
|
import { andorraIsContextOverflow } from '../vendor/engine/runtime/ai/utils/overflow.js';
|
|
5
5
|
import { ANTHROPIC_MODELS } from '../vendor/engine/runtime/ai/providers/anthropic.models.js';
|
|
6
6
|
import { andorraClampMaxTokensToContext } from '../vendor/engine/runtime/ai/api/simple-options.js';
|
|
7
|
+
import { encodeProviderToolNames } from './tool-names.js';
|
|
7
8
|
const emptyUsage = () => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0,
|
|
8
9
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } });
|
|
9
10
|
export function isEngineContextOverflow(errorMessage) {
|
|
@@ -40,8 +41,9 @@ export function relocateConversationBreakpoint(body, mutableTail) {
|
|
|
40
41
|
anchor.cache_control = control;
|
|
41
42
|
}
|
|
42
43
|
/** Convert at the provider boundary; reasoning is continuation state, never visible text. */
|
|
43
|
-
export function toEngineMessages(request, model) {
|
|
44
|
-
const
|
|
44
|
+
export function toEngineMessages(request, model, names) {
|
|
45
|
+
const encode = names?.encode ?? ((name) => name);
|
|
46
|
+
const historyNames = new Map(request.messages.flatMap(m => (m.toolCalls ?? []).map(c => [c.id, encode(c.name)])));
|
|
45
47
|
return request.messages.map((message) => {
|
|
46
48
|
// User-turn attachments ride the same image blocks tool observations use; the vendored
|
|
47
49
|
// serializers emit them for image-capable models and replace them with a placeholder for
|
|
@@ -53,7 +55,7 @@ export function toEngineMessages(request, model) {
|
|
|
53
55
|
if (message.role === 'system')
|
|
54
56
|
return { role: 'system', content: message.content, timestamp: 0 };
|
|
55
57
|
if (message.role === 'tool')
|
|
56
|
-
return { role: 'toolResult', toolCallId: message.toolCallId, toolName:
|
|
58
|
+
return { role: 'toolResult', toolCallId: message.toolCallId, toolName: historyNames.get(message.toolCallId) ?? 'unknown',
|
|
57
59
|
content: [{ type: 'text', text: message.content }, ...(message.images ?? []).map(image => ({ type: 'image', ...image }))], isError: message.content.startsWith('Tool error:'), timestamp: 0 };
|
|
58
60
|
const content = [];
|
|
59
61
|
const continuation = message.providerContinuation;
|
|
@@ -73,14 +75,14 @@ export function toEngineMessages(request, model) {
|
|
|
73
75
|
catch {
|
|
74
76
|
args = {};
|
|
75
77
|
}
|
|
76
|
-
content.push({ type: 'toolCall', id: call.id, name: call.name, arguments: args });
|
|
78
|
+
content.push({ type: 'toolCall', id: call.id, name: encode(call.name), arguments: args });
|
|
77
79
|
}
|
|
78
80
|
return { role: 'assistant', content, api: model.api, provider: model.provider, model: model.id,
|
|
79
81
|
usage: emptyUsage(), stopReason: message.toolCalls?.length ? 'toolUse' : 'stop', timestamp: 0 };
|
|
80
82
|
});
|
|
81
83
|
}
|
|
82
84
|
const STREAM_LIMIT = 4 * 1024 * 1024;
|
|
83
|
-
/** Bound retained model output, not repeated SSE IDs, usage, or heartbeat metadata. */
|
|
85
|
+
/** Bound retained model output, not repeated SSE IDs, usage, or heartbeat metadata. Returns the parsed event for the caller's own accounting. */
|
|
84
86
|
function streamPayloadBudget(anthropic) {
|
|
85
87
|
let bytes = 0, detailBlocks = 0;
|
|
86
88
|
let lastDetailType;
|
|
@@ -145,6 +147,7 @@ function streamPayloadBudget(anthropic) {
|
|
|
145
147
|
}
|
|
146
148
|
}
|
|
147
149
|
}
|
|
150
|
+
return event;
|
|
148
151
|
};
|
|
149
152
|
}
|
|
150
153
|
/** Run the copied provider implementation, with compatibility for whole-JSON servers. */
|
|
@@ -166,6 +169,47 @@ export async function generateEngineResponse(request, host) {
|
|
|
166
169
|
let transportError;
|
|
167
170
|
let wholeResult;
|
|
168
171
|
let validated;
|
|
172
|
+
// Whether any frame mentioned the cache split. The vendored parser collapses an unmentioned
|
|
173
|
+
// counter into zero, and the host contract keys on presence, not value: a provider answering
|
|
174
|
+
// cached_tokens: 0 measured a cold cache, while a provider that never mentions cache measured
|
|
175
|
+
// nothing, and only the first belongs in the local cache-hit denominator. The whole-body
|
|
176
|
+
// mapping in providers.ts already keeps explicit zeros; the stream path now matches it. The
|
|
177
|
+
// frames are parsed once for the payload budget, so the watcher rides that same parse.
|
|
178
|
+
let streamReportsCacheRead = false, streamReportsCacheWrite = false;
|
|
179
|
+
const watchCacheReport = (parsed) => {
|
|
180
|
+
if (streamReportsCacheRead && streamReportsCacheWrite)
|
|
181
|
+
return;
|
|
182
|
+
if (typeof parsed !== 'object' || parsed === null)
|
|
183
|
+
return;
|
|
184
|
+
const event = parsed;
|
|
185
|
+
const ledger = (value) => {
|
|
186
|
+
if (typeof value !== 'object' || value === null)
|
|
187
|
+
return;
|
|
188
|
+
const usage = value;
|
|
189
|
+
if (host.anthropic) {
|
|
190
|
+
if (usage.cache_read_input_tokens !== undefined)
|
|
191
|
+
streamReportsCacheRead = true;
|
|
192
|
+
if (usage.cache_creation_input_tokens !== undefined)
|
|
193
|
+
streamReportsCacheWrite = true;
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
if (usage.prompt_cache_hit_tokens !== undefined || usage.cached_tokens !== undefined)
|
|
197
|
+
streamReportsCacheRead = true;
|
|
198
|
+
const details = usage.prompt_tokens_details;
|
|
199
|
+
if (typeof details === 'object' && details !== null) {
|
|
200
|
+
if (details.cached_tokens !== undefined)
|
|
201
|
+
streamReportsCacheRead = true;
|
|
202
|
+
if (details.cache_write_tokens !== undefined)
|
|
203
|
+
streamReportsCacheWrite = true;
|
|
204
|
+
}
|
|
205
|
+
};
|
|
206
|
+
// OpenAI-compatible usage rides the final chunk; Anthropic's arrives in message_start
|
|
207
|
+
// (prompt-side counters) and message_delta (the completion counter), each under its own key.
|
|
208
|
+
ledger(event.usage);
|
|
209
|
+
const message = event.message;
|
|
210
|
+
if (typeof message === 'object' && message !== null)
|
|
211
|
+
ledger(message.usage);
|
|
212
|
+
};
|
|
169
213
|
// No provider SDK authentication/environment discovery: Andorra's send() owns credentials.
|
|
170
214
|
const nativeFetch = async (_url, init) => {
|
|
171
215
|
try {
|
|
@@ -205,7 +249,7 @@ export async function generateEngineResponse(request, host) {
|
|
|
205
249
|
if (data === '[DONE]')
|
|
206
250
|
return true;
|
|
207
251
|
if (data) {
|
|
208
|
-
accountPayload(data);
|
|
252
|
+
watchCacheReport(accountPayload(data));
|
|
209
253
|
validator?.event(data);
|
|
210
254
|
}
|
|
211
255
|
return host.anthropic && /^event:\s*message_stop$/m.test(raw);
|
|
@@ -296,7 +340,12 @@ export async function generateEngineResponse(request, host) {
|
|
|
296
340
|
throw error;
|
|
297
341
|
}
|
|
298
342
|
};
|
|
299
|
-
|
|
343
|
+
// Strict providers validate tool names against ^[a-zA-Z0-9_-]+$ and reject the request over
|
|
344
|
+
// Andorra's dotted canonical names, so the request travels under encoded names and the
|
|
345
|
+
// response is decoded back before anything downstream (executor, journal, desktop) sees it.
|
|
346
|
+
const { tools: providerTools, codec } = encodeProviderToolNames(request.tools);
|
|
347
|
+
const decodeCalls = (calls) => calls.map(call => ({ ...call, name: codec.decode(call.name) }));
|
|
348
|
+
const nativeContext = andorraNormalizeContext({ messages: toEngineMessages(request, model, codec), tools: providerTools });
|
|
300
349
|
const stream = (host.anthropic ? streamMessages : streamCompletions)(model, nativeContext, {
|
|
301
350
|
apiKey: 'andorra-host-managed', fetch: nativeFetch, signal: request.signal, maxRetries: 0, env: {},
|
|
302
351
|
// Anthropic caches a prefix only up to an explicit breakpoint, so the serializer must mark
|
|
@@ -342,9 +391,8 @@ export async function generateEngineResponse(request, host) {
|
|
|
342
391
|
if (transportError)
|
|
343
392
|
throw transportError;
|
|
344
393
|
if (wholeResult)
|
|
345
|
-
return
|
|
346
|
-
providerContinuation: { ...wholeResult.providerContinuation, api: model.api, provider: model.provider, model: model.id }
|
|
347
|
-
} : wholeResult;
|
|
394
|
+
return { ...wholeResult, toolCalls: decodeCalls(wholeResult.toolCalls),
|
|
395
|
+
...(wholeResult.providerContinuation ? { providerContinuation: { ...wholeResult.providerContinuation, api: model.api, provider: model.provider, model: model.id } } : {}) };
|
|
348
396
|
const result = await stream.result();
|
|
349
397
|
if (result.stopReason === 'error') {
|
|
350
398
|
// Upstream error strings can contain provider response bodies. Never expose them.
|
|
@@ -391,11 +439,14 @@ export async function generateEngineResponse(request, host) {
|
|
|
391
439
|
// vendored parser only knows request totals. Copy the measurement onto the authoritative usage
|
|
392
440
|
// so throughput can be reported over decode time alone, excluding prefill and tool gaps.
|
|
393
441
|
const validatedDecodeMs = validated?.usage?.decodeMs;
|
|
394
|
-
return { text: validated?.text ?? text, toolCalls: validated?.toolCalls ?? host.checkCalls(calls), stopReason: validated?.stopReason ?? result.rawStopReason ?? (result.stopReason === 'toolUse' ? 'tool_calls' : result.stopReason),
|
|
442
|
+
return { text: validated?.text ?? text, toolCalls: decodeCalls(validated?.toolCalls ?? host.checkCalls(calls)), stopReason: validated?.stopReason ?? result.rawStopReason ?? (result.stopReason === 'toolUse' ? 'tool_calls' : result.stopReason),
|
|
395
443
|
...(!host.anthropic && thoughts.length ? { reasoningContent: thoughts.join('') } : {}),
|
|
396
444
|
...(host.anthropic && thinking.length ? { providerContinuation: { api: model.api, provider: model.provider, model: model.id, thinking } } : {}),
|
|
397
445
|
usage: { inputTokens: result.usage.input + cacheRead + cacheWrite, outputTokens: result.usage.output, requests: 1,
|
|
398
|
-
|
|
399
|
-
|
|
446
|
+
// Presence, not positivity: a frame-reported zero is a measurement, and the flags say
|
|
447
|
+
// whether any frame reported the counter at all. A reported-but-malformed counter stays
|
|
448
|
+
// out of the split like an unreported one.
|
|
449
|
+
...(streamReportsCacheRead && validatedCounter(result.usage.cacheRead) ? { cacheRead: result.usage.cacheRead } : {}),
|
|
450
|
+
...(streamReportsCacheWrite && validatedCounter(result.usage.cacheWrite) ? { cacheWrite: result.usage.cacheWrite } : {}),
|
|
400
451
|
...(typeof validatedDecodeMs === 'number' && Number.isFinite(validatedDecodeMs) && validatedDecodeMs > 0 ? { decodeMs: validatedDecodeMs } : {}) } };
|
|
401
452
|
}
|
|
@@ -18,7 +18,8 @@ export const PEER_PROVIDER_EXPORT_CAPABILITY = 'remote.providers.export';
|
|
|
18
18
|
const PEER_IMPORT_DEADLINE_MS = 60_000;
|
|
19
19
|
/** Limit staged providers per export; every excess entry is reported as rejected, never silently omitted. */
|
|
20
20
|
const MAX_EXPORTED_PROVIDERS = 100;
|
|
21
|
-
|
|
21
|
+
// A literal, not PROVIDER_TYPES: this module is evaluated inside the providers module's import cycle.
|
|
22
|
+
const IMPORT_PROVIDER_TYPES = new Set(['openai-compatible', 'anthropic', 'codex', 'claude', 'opencode-go', 'grok', 'opencode']);
|
|
22
23
|
function message(error) { return error instanceof Error ? error.message : String(error); }
|
|
23
24
|
/**
|
|
24
25
|
* Rebuild one exported provider from known fields only, or reject it.
|
|
@@ -215,6 +216,10 @@ function credentialNote(provider) {
|
|
|
215
216
|
return 'ChatGPT sign-in does not transfer; sign in again after importing';
|
|
216
217
|
if (provider.type === 'claude')
|
|
217
218
|
return 'Claude Code sign-in does not transfer; sign in on this machine after importing';
|
|
219
|
+
if (provider.type === 'grok')
|
|
220
|
+
return 'Grok sign-in does not transfer; sign in on this machine after importing';
|
|
221
|
+
if (provider.type === 'opencode')
|
|
222
|
+
return 'OpenCode sign-ins do not transfer; connect its providers on this machine after importing';
|
|
218
223
|
if (provider.apiKey)
|
|
219
224
|
return 'API key transfers';
|
|
220
225
|
if (provider.apiKeyEnv)
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Saved provider API keys, kept in the OS credential store rather than in `config.json`.
|
|
3
|
+
*
|
|
4
|
+
* Each provider's key lives in its own vault entry, scoped by the configuration directory and the
|
|
5
|
+
* provider id, under its own service so `andorra logout --all` (which clears sign-ins) never touches
|
|
6
|
+
* them. One entry per key keeps each within the store's per-entry bound however many providers are
|
|
7
|
+
* configured, and lets a save write only the keys that changed. The configuration file keeps a
|
|
8
|
+
* `providerKeys: "keyring"` marker in their place; the keys are read back into memory when the
|
|
9
|
+
* configuration loads, so everything downstream of `loadConfig` sees exactly the provider objects it
|
|
10
|
+
* always did.
|
|
11
|
+
*
|
|
12
|
+
* Where the machine has no OS store (Linux without Secret Service), or the user chose
|
|
13
|
+
* `ANDORRA_CREDENTIAL_STORE=file`, keys stay in the owner-only `config.json` as before: that is
|
|
14
|
+
* the same fallback a sign-in takes. On Windows and macOS a failing store is reported instead.
|
|
15
|
+
*/
|
|
16
|
+
export declare const PROVIDER_KEY_SERVICE = "Andorra Code provider keys";
|
|
17
|
+
/** The value `config.json` holds in `providerKeys` while its keys are in the OS store. */
|
|
18
|
+
export declare const PROVIDER_KEYS_IN_KEYRING = "keyring";
|
|
19
|
+
export interface ProviderKeyVault {
|
|
20
|
+
read(): Promise<string | undefined>;
|
|
21
|
+
write(value: string): Promise<void>;
|
|
22
|
+
remove(): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
type VaultFactory = (directory: string, provider: string) => ProviderKeyVault;
|
|
25
|
+
/** Tests replace the OS store (and the platform's fallback rule); the returned function restores both. */
|
|
26
|
+
export declare function setProviderKeyVaultForTesting(factory: VaultFactory | undefined, options?: {
|
|
27
|
+
fallback?: boolean;
|
|
28
|
+
}): () => void;
|
|
29
|
+
/** The keys a configuration directory saved for these providers, by provider id. */
|
|
30
|
+
export declare function readProviderKeys(directory: string, providers: readonly string[]): Promise<Map<string, string>>;
|
|
31
|
+
/**
|
|
32
|
+
* Save the keys in the OS store: each key that differs from `current` (what the vault already
|
|
33
|
+
* holds, when known) is written, so an unchanged key is not rewritten on every save. Keys that
|
|
34
|
+
* are no longer configured are left for the caller to remove once the configuration that drops
|
|
35
|
+
* them is published. Returns false, having saved nothing, when the keys belong in `config.json`
|
|
36
|
+
* instead: `ANDORRA_CREDENTIAL_STORE=file`, or no OS store on a platform where that falls back.
|
|
37
|
+
*/
|
|
38
|
+
export declare function storeProviderKeys(directory: string, keys: Map<string, string>, current?: Map<string, string>, environment?: NodeJS.ProcessEnv): Promise<boolean>;
|
|
39
|
+
/**
|
|
40
|
+
* Put the vault back the way `current` describes it for these providers, after a save that wrote
|
|
41
|
+
* them could not publish its configuration. Best-effort: the save's own failure is what is reported.
|
|
42
|
+
*/
|
|
43
|
+
export declare function restoreProviderKeys(directory: string, providers: Iterable<string>, current: Map<string, string>): Promise<void>;
|
|
44
|
+
/** Delete the keys a configuration directory saved for these providers. A machine without an OS store holds none. */
|
|
45
|
+
export declare function removeProviderKeys(directory: string, providers: Iterable<string>): Promise<void>;
|
|
46
|
+
/** Whether saving should move plaintext keys out of `config.json` on this machine. */
|
|
47
|
+
export declare function providerKeysBelongInKeyring(environment?: NodeJS.ProcessEnv): boolean;
|
|
48
|
+
export {};
|