@andorra-labs/code 0.1.17 → 0.1.19
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-jev-savings.d.ts +4 -0
- package/dist/src/account-jev-savings.js +92 -0
- package/dist/src/acp-agent.js +2 -2
- package/dist/src/agent-execution.js +441 -53
- package/dist/src/agent-mcp.js +7 -1
- package/dist/src/agent-modifiers.js +5 -7
- package/dist/src/analytics.d.ts +19 -1
- package/dist/src/analytics.js +9 -1
- package/dist/src/andorra/entry.js +15 -6
- package/dist/src/andorra/errors.js +3 -0
- package/dist/src/andorra/hosted.d.ts +8 -0
- package/dist/src/andorra/hosted.js +22 -3
- package/dist/src/andorra/streams.d.ts +49 -0
- package/dist/src/andorra/streams.js +98 -0
- package/dist/src/antigravity-acp.d.ts +28 -0
- package/dist/src/antigravity-acp.js +150 -0
- package/dist/src/antigravity-terminal.d.ts +2 -0
- package/dist/src/antigravity-terminal.js +214 -0
- package/dist/src/app-server/adaptive-routing-settings.d.ts +37 -0
- package/dist/src/app-server/adaptive-routing-settings.js +69 -0
- package/dist/src/app-server/artifact.d.ts +14 -0
- package/dist/src/app-server/artifact.js +46 -0
- package/dist/src/app-server/legal-protocol.d.ts +33 -0
- package/dist/src/app-server/legal-protocol.js +16 -0
- package/dist/src/app-server/protocol.d.ts +34 -3
- package/dist/src/app-server/protocol.js +3 -1
- package/dist/src/app-server/telemetry-protocol.d.ts +53 -0
- package/dist/src/app-server/telemetry-protocol.js +2 -0
- package/dist/src/app-server/telemetry.d.ts +38 -0
- package/dist/src/app-server/telemetry.js +163 -0
- package/dist/src/app-server/workspace.d.ts +21 -0
- package/dist/src/app-server/workspace.js +192 -10
- package/dist/src/app-server.d.ts +82 -26
- package/dist/src/app-server.js +1573 -417
- package/dist/src/attachments.d.ts +10 -0
- package/dist/src/attachments.js +102 -7
- package/dist/src/auth/AuthManager.d.ts +11 -2
- package/dist/src/auth/AuthManager.js +56 -13
- package/dist/src/auth/index.d.ts +5 -1
- package/dist/src/auth/index.js +8 -1
- package/dist/src/auth/lifecycle.d.ts +13 -0
- package/dist/src/auth/lifecycle.js +109 -0
- package/dist/src/auth/store.d.ts +1 -0
- package/dist/src/auth/store.js +12 -0
- package/dist/src/auth/types.d.ts +12 -0
- package/dist/src/automation-runner.js +2 -0
- package/dist/src/automation-service.js +7 -2
- package/dist/src/automation-tool.js +2 -1
- package/dist/src/benchmark-scores.d.ts +88 -0
- package/dist/src/benchmark-scores.js +302 -0
- package/dist/src/bridge/command.js +16 -1
- package/dist/src/bridge/control.d.ts +3 -1
- package/dist/src/bridge/control.js +9 -3
- package/dist/src/bridge/engines.d.ts +2 -0
- package/dist/src/bridge/engines.js +9 -0
- package/dist/src/bridge/github.d.ts +108 -0
- package/dist/src/bridge/github.js +378 -0
- package/dist/src/bridge/host-ops.d.ts +3 -3
- package/dist/src/bridge/host-ops.js +14 -2
- package/dist/src/bridge/host.d.ts +2 -0
- package/dist/src/bridge/host.js +70 -16
- package/dist/src/bridge/protocol.d.ts +1 -0
- package/dist/src/bridge/protocol.js +1 -0
- package/dist/src/browser-panel-tool.d.ts +12 -0
- package/dist/src/browser-panel-tool.js +30 -3
- package/dist/src/browser-runner.js +53 -62
- package/dist/src/browser-server.js +10 -4
- package/dist/src/browser-session.d.ts +14 -0
- package/dist/src/browser-session.js +57 -12
- package/dist/src/browser-view.d.ts +40 -1
- package/dist/src/browser-view.js +163 -9
- package/dist/src/browser-window-style.d.ts +27 -0
- package/dist/src/browser-window-style.js +244 -0
- package/dist/src/bug-report-attachments.d.ts +48 -0
- package/dist/src/bug-report-attachments.js +327 -0
- package/dist/src/bug-report.d.ts +23 -3
- package/dist/src/bug-report.js +72 -9
- package/dist/src/claude-provider.d.ts +1 -0
- package/dist/src/claude-provider.js +77 -36
- package/dist/src/cli.d.ts +1 -3
- package/dist/src/cli.js +245 -62
- package/dist/src/codex-provider.d.ts +1 -0
- package/dist/src/codex-provider.js +44 -8
- package/dist/src/coding-tools.d.ts +1 -0
- package/dist/src/coding-tools.js +28 -7
- package/dist/src/command-screens.d.ts +1 -1
- package/dist/src/command-screens.js +2 -2
- package/dist/src/commands.d.ts +9 -2
- package/dist/src/commands.js +69 -64
- package/dist/src/completion.js +13 -7
- package/dist/src/config.d.ts +14 -3
- package/dist/src/config.js +57 -17
- package/dist/src/context-budget.d.ts +11 -2
- package/dist/src/context-budget.js +38 -4
- package/dist/src/context-compaction.d.ts +10 -8
- package/dist/src/context-compaction.js +23 -24
- package/dist/src/deadline.js +1 -1
- package/dist/src/decision/DecisionEngine.d.ts +2 -0
- package/dist/src/decision/DecisionManager.d.ts +16 -0
- package/dist/src/decision/DecisionManager.js +75 -2
- package/dist/src/decision/applyTaskKind.d.ts +8 -0
- package/dist/src/decision/applyTaskKind.js +53 -0
- package/dist/src/decision/applyToolMenu.js +6 -2
- package/dist/src/decision/hostedPolicy.js +6 -3
- package/dist/src/decision/optimizationPolicy.d.ts +10 -0
- package/dist/src/decision/optimizationPolicy.js +23 -3
- package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +4 -1
- package/dist/src/decision/providers/AndorraDecisionProvider.js +29 -7
- package/dist/src/decision/providers/index.js +1 -1
- package/dist/src/decision/taskKind.d.ts +52 -0
- package/dist/src/decision/taskKind.js +76 -0
- package/dist/src/decision/toolFamilies.js +1 -1
- package/dist/src/decision/types.d.ts +3 -1
- package/dist/src/default-graph.js +1 -1
- package/dist/src/efficiency.d.ts +80 -1
- package/dist/src/efficiency.js +119 -4
- package/dist/src/effort-routing.d.ts +27 -0
- package/dist/src/effort-routing.js +34 -0
- package/dist/src/evidence.d.ts +110 -0
- package/dist/src/evidence.js +195 -0
- package/dist/src/extensions.d.ts +2 -0
- package/dist/src/extensions.js +30 -20
- package/dist/src/github-app/agent-writes.d.ts +1 -1
- package/dist/src/github-app/agent-writes.js +1 -1
- package/dist/src/github-app/client.d.ts +19 -0
- package/dist/src/github-app/client.js +21 -1
- package/dist/src/github-app/event-source.d.ts +0 -5
- package/dist/src/github-app/event-source.js +1 -31
- package/dist/src/github-app/metrics.d.ts +2 -5
- package/dist/src/github-app/metrics.js +2 -14
- package/dist/src/github-app/review-loop.d.ts +5 -5
- package/dist/src/github-app/review-loop.js +1 -1
- package/dist/src/github-app/review-node.d.ts +2 -2
- package/dist/src/github-app/triggers.d.ts +3 -3
- package/dist/src/github-names.d.ts +7 -0
- package/dist/src/github-names.js +7 -0
- package/dist/src/glob-search.d.ts +1 -0
- package/dist/src/glob-search.js +3 -0
- package/dist/src/google-provider.d.ts +5 -28
- package/dist/src/google-provider.js +6 -141
- package/dist/src/graph-editor-session.d.ts +1 -0
- package/dist/src/graph-editor-session.js +2 -0
- package/dist/src/graph-health.js +3 -1
- package/dist/src/graph-preview.d.ts +2 -0
- package/dist/src/graph-preview.js +1 -0
- package/dist/src/graph-runner.js +20 -14
- package/dist/src/graph-selection.d.ts +3 -1
- package/dist/src/graph-selection.js +2 -2
- package/dist/src/graph-server.d.ts +8 -1
- package/dist/src/graph-server.js +49 -12
- package/dist/src/graph-sync.d.ts +2 -1
- package/dist/src/graph-sync.js +13 -0
- package/dist/src/graph-ui/app.js +49 -8
- package/dist/src/graph-ui/index.html +1 -1
- package/dist/src/graphs.d.ts +23 -1
- package/dist/src/graphs.js +58 -7
- package/dist/src/grok-provider.js +17 -14
- package/dist/src/hardened-runtime.js +39 -25
- package/dist/src/jev-savings.d.ts +4 -0
- package/dist/src/jev-savings.js +13 -0
- package/dist/src/legal/client.d.ts +25 -0
- package/dist/src/legal/client.js +47 -0
- package/dist/src/legal/command.d.ts +13 -0
- package/dist/src/legal/command.js +98 -0
- package/dist/src/legal/documents.d.ts +2 -0
- package/dist/src/legal/documents.js +14 -0
- package/dist/src/legal/gate.d.ts +13 -0
- package/dist/src/legal/gate.js +96 -0
- package/dist/src/legal/manifest.d.ts +21 -0
- package/dist/src/legal/manifest.js +23 -0
- package/dist/src/legal/receipt.d.ts +13 -0
- package/dist/src/legal/receipt.js +137 -0
- package/dist/src/legal/release.d.ts +27 -0
- package/dist/src/legal/release.js +28 -0
- package/dist/src/managed-sign-in.d.ts +0 -1
- package/dist/src/managed-sign-in.js +0 -13
- package/dist/src/membership.d.ts +27 -1
- package/dist/src/membership.js +139 -7
- package/dist/src/model-health-cache.js +1 -1
- package/dist/src/model-metadata.js +3 -7
- package/dist/src/model-override.d.ts +2 -1
- package/dist/src/model-override.js +9 -0
- package/dist/src/model-pool.d.ts +99 -0
- package/dist/src/model-pool.js +136 -0
- package/dist/src/model-relay/local.js +5 -0
- package/dist/src/model-relay/remote.d.ts +2 -0
- package/dist/src/model-relay/remote.js +4 -0
- package/dist/src/model-tiers.d.ts +16 -1
- package/dist/src/model-tiers.js +31 -7
- package/dist/src/opencode-cli-provider.js +59 -56
- package/dist/src/opencode-provider.js +16 -13
- package/dist/src/permissions.d.ts +5 -0
- package/dist/src/permissions.js +7 -0
- package/dist/src/plan-pass.js +2 -1
- package/dist/src/pool-scores.d.ts +45 -0
- package/dist/src/pool-scores.js +40 -0
- package/dist/src/provider-connection.js +3 -17
- package/dist/src/provider-engine.d.ts +13 -1
- package/dist/src/provider-engine.js +116 -12
- package/dist/src/provider-request-error.d.ts +8 -0
- package/dist/src/provider-request-error.js +12 -0
- package/dist/src/provider-settings.d.ts +1 -1
- package/dist/src/provider-settings.js +36 -18
- package/dist/src/provider-turn-deadline.d.ts +39 -0
- package/dist/src/provider-turn-deadline.js +139 -0
- package/dist/src/providers.d.ts +8 -9
- package/dist/src/providers.js +211 -150
- package/dist/src/pull-request-merge.d.ts +1 -8
- package/dist/src/pull-request-merge.js +0 -4
- package/dist/src/pull-requests.d.ts +83 -57
- package/dist/src/pull-requests.js +266 -225
- package/dist/src/qa/runtime/ProcessManager.d.ts +5 -1
- package/dist/src/qa/runtime/ProcessManager.js +9 -3
- package/dist/src/react-runtime.js +245 -71
- package/dist/src/reasoning-probe-cloud.d.ts +10 -0
- package/dist/src/reasoning-probe-cloud.js +209 -0
- package/dist/src/remote/engine-pool.d.ts +3 -0
- package/dist/src/remote/engine-pool.js +88 -21
- package/dist/src/remote/recovery.d.ts +6 -0
- package/dist/src/remote/recovery.js +37 -0
- package/dist/src/run-records.d.ts +13 -3
- package/dist/src/run-records.js +59 -34
- package/dist/src/runtime.d.ts +47 -2
- package/dist/src/runtime.js +33 -7
- package/dist/src/session-summary.d.ts +8 -0
- package/dist/src/session-summary.js +34 -0
- package/dist/src/sessions.d.ts +32 -0
- package/dist/src/sessions.js +65 -3
- package/dist/src/shell.js +6 -0
- package/dist/src/side-panel.js +36 -2
- package/dist/src/sign-in-detection.d.ts +1 -1
- package/dist/src/sign-in-detection.js +4 -10
- package/dist/src/sign-in-offer.js +1 -1
- package/dist/src/skill-commands.js +1 -1
- package/dist/src/skills/bundled/bug-report/SKILL.md +51 -7
- package/dist/src/skills/bundled/graph-manager/SKILL.md +2 -2
- package/dist/src/skills/bundled/graph-manager/patterns.md +13 -19
- package/dist/src/skills/bundled/provenance.json +3 -3
- package/dist/src/subagent-run.js +50 -50
- package/dist/src/subscription-usage.d.ts +50 -0
- package/dist/src/subscription-usage.js +92 -0
- package/dist/src/task-checkout.d.ts +157 -0
- package/dist/src/task-checkout.js +628 -0
- package/dist/src/telemetry/access.d.ts +18 -0
- package/dist/src/telemetry/access.js +43 -0
- package/dist/src/telemetry/aggregate.d.ts +18 -2
- package/dist/src/telemetry/aggregate.js +22 -9
- package/dist/src/telemetry/capture-core.d.ts +33 -14
- package/dist/src/telemetry/capture-core.js +124 -25
- package/dist/src/telemetry/capture.d.ts +3 -2
- package/dist/src/telemetry/capture.js +21 -1
- package/dist/src/telemetry/decision-capture.js +4 -0
- package/dist/src/telemetry/emitter.d.ts +6 -7
- package/dist/src/telemetry/emitter.js +124 -29
- package/dist/src/telemetry/gate.d.ts +41 -2
- package/dist/src/telemetry/gate.js +89 -4
- package/dist/src/telemetry/home.d.ts +1 -0
- package/dist/src/telemetry/home.js +20 -0
- package/dist/src/telemetry/identity.d.ts +6 -3
- package/dist/src/telemetry/identity.js +19 -6
- package/dist/src/telemetry/lifecycle.d.ts +8 -0
- package/dist/src/telemetry/lifecycle.js +76 -0
- package/dist/src/telemetry/outbox.d.ts +13 -8
- package/dist/src/telemetry/outbox.js +68 -12
- package/dist/src/telemetry/permission-command.d.ts +38 -0
- package/dist/src/telemetry/permission-command.js +208 -0
- package/dist/src/telemetry/permission.d.ts +168 -0
- package/dist/src/telemetry/permission.js +662 -0
- package/dist/src/telemetry/record-installation.d.ts +1 -0
- package/dist/src/telemetry/record-installation.js +9 -0
- package/dist/src/telemetry/region-data.d.ts +12 -0
- package/dist/src/telemetry/region-data.js +1314 -0
- package/dist/src/telemetry/region.d.ts +34 -0
- package/dist/src/telemetry/region.js +87 -0
- package/dist/src/telemetry/run-privacy.d.ts +11 -0
- package/dist/src/telemetry/run-privacy.js +165 -0
- package/dist/src/telemetry/schema.d.ts +27 -6
- package/dist/src/telemetry/schema.js +109 -14
- package/dist/src/telemetry/state.d.ts +11 -7
- package/dist/src/telemetry/state.js +39 -6
- package/dist/src/telemetry/surface.d.ts +20 -3
- package/dist/src/telemetry/surface.js +71 -15
- package/dist/src/telemetry/uploader.d.ts +6 -11
- package/dist/src/telemetry/uploader.js +72 -46
- package/dist/src/telemetry/uploads.d.ts +5 -1
- package/dist/src/telemetry/uploads.js +25 -6
- package/dist/src/telemetry/version.d.ts +5 -0
- package/dist/src/telemetry/version.js +34 -0
- package/dist/src/telemetry/workspace.d.ts +4 -1
- package/dist/src/telemetry/workspace.js +18 -3
- package/dist/src/terminal-ui.d.ts +3 -0
- package/dist/src/terminal-ui.js +48 -6
- package/dist/src/test-edit-guard.d.ts +30 -0
- package/dist/src/test-edit-guard.js +167 -2
- package/dist/src/thinking-level-detect.d.ts +13 -0
- package/dist/src/thinking-level-detect.js +52 -0
- package/dist/src/thinking-levels.d.ts +30 -0
- package/dist/src/thinking-levels.js +131 -0
- package/dist/src/timers.d.ts +3 -0
- package/dist/src/todos.d.ts +2 -1
- package/dist/src/todos.js +24 -4
- package/dist/src/tool-argument-coercion.d.ts +7 -0
- package/dist/src/tool-argument-coercion.js +49 -0
- package/dist/src/tool-catalog.d.ts +2 -2
- package/dist/src/tool-catalog.js +1 -1
- package/dist/src/tools.js +67 -22
- package/dist/src/transcript.js +3 -2
- package/dist/src/types.d.ts +48 -1
- package/dist/src/update.js +4 -0
- package/dist/src/usage-analytics.d.ts +7 -0
- package/dist/src/usage-analytics.js +85 -13
- package/dist/telemetry-consent-v1 +1 -0
- package/package.json +97 -96
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { DecisionBatch } from './decision/types.js';
|
|
2
|
+
import { type AdaptiveRoutingConfig, type EfficiencyReason, type PoolClass, type PoolEntry } from './efficiency.js';
|
|
3
|
+
/**
|
|
4
|
+
* Pool routing: the second adaptive-routing strategy (`strategy: 'pool'`).
|
|
5
|
+
*
|
|
6
|
+
* The configuration lists pairs (provider, model, thinking level), each with a quality score and an optional cost the
|
|
7
|
+
* user supplies. A task is given a class, the class sets the score a pair must reach, and among the pairs that reach
|
|
8
|
+
* it the router picks the lowest effective cost: the pair's cost divided by its subscription's standing, so a unit
|
|
9
|
+
* spent on a subscription behind its pace counts for more and one on a subscription with allowance to spare for less.
|
|
10
|
+
* Subscription usage never lowers the score a task must reach: it only changes which pair serves it. Nothing here
|
|
11
|
+
* reads a file or the network; usage readings are passed in, and a provider with no reading is never held back.
|
|
12
|
+
*/
|
|
13
|
+
/** One usage window of a subscription, as its provider reports it. */
|
|
14
|
+
export interface QuotaWindow {
|
|
15
|
+
/** Share of the window's allowance already used, 0 to 100. */
|
|
16
|
+
usedPercent: number;
|
|
17
|
+
/** When the window resets, in milliseconds since the epoch. */
|
|
18
|
+
resetsAt?: number;
|
|
19
|
+
/** The whole length of the window in seconds, from the provider; never guessed from a label. */
|
|
20
|
+
windowSeconds?: number;
|
|
21
|
+
}
|
|
22
|
+
/** Usage windows by provider id. A provider with no entry has no known limit. */
|
|
23
|
+
export type QuotaReadings = Readonly<Record<string, readonly QuotaWindow[] | undefined>>;
|
|
24
|
+
export interface PoolTarget {
|
|
25
|
+
provider: string;
|
|
26
|
+
model: string;
|
|
27
|
+
effort?: PoolEntry['effort'];
|
|
28
|
+
}
|
|
29
|
+
export interface PoolDecisionInput {
|
|
30
|
+
task: string;
|
|
31
|
+
routing: AdaptiveRoutingConfig & {
|
|
32
|
+
enabled: boolean;
|
|
33
|
+
maxEscalations: number;
|
|
34
|
+
};
|
|
35
|
+
baseline: {
|
|
36
|
+
provider: string;
|
|
37
|
+
model: string;
|
|
38
|
+
effort?: string;
|
|
39
|
+
};
|
|
40
|
+
node: {
|
|
41
|
+
provider?: string;
|
|
42
|
+
model?: string;
|
|
43
|
+
};
|
|
44
|
+
modelPinned?: boolean;
|
|
45
|
+
hints?: DecisionBatch;
|
|
46
|
+
configured: {
|
|
47
|
+
id: string;
|
|
48
|
+
model?: string;
|
|
49
|
+
models?: readonly string[];
|
|
50
|
+
}[];
|
|
51
|
+
quota?: QuotaReadings;
|
|
52
|
+
/** With `candidates: all`: the thinking levels a provider's model takes. Without it every scored level is a pair. */
|
|
53
|
+
levels?: (provider: string, model: string) => readonly string[] | undefined;
|
|
54
|
+
/** Milliseconds since the epoch; defaults to the current time. */
|
|
55
|
+
now?: number;
|
|
56
|
+
/** A class named by the caller (a parent agent naming one for its subagent) instead of classifying the task. */
|
|
57
|
+
declaredClass?: PoolClass;
|
|
58
|
+
previous?: {
|
|
59
|
+
poolClass: PoolClass;
|
|
60
|
+
reason?: string;
|
|
61
|
+
escalations: number;
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
export interface PoolDecision {
|
|
65
|
+
poolClass?: PoolClass;
|
|
66
|
+
target?: PoolTarget;
|
|
67
|
+
/** The target differs from the pair the node would have run. */
|
|
68
|
+
applied: boolean;
|
|
69
|
+
reason: EfficiencyReason;
|
|
70
|
+
evidence: 'policy' | 'pinned' | 'hint' | 'lexical' | 'declared' | 'escalation' | 'none';
|
|
71
|
+
/** Pairs that reach the class score, and how many of those the usage reserve held back. */
|
|
72
|
+
candidates: number;
|
|
73
|
+
blocked: number;
|
|
74
|
+
/** The chosen pair's subscription standing, when its usage was known. */
|
|
75
|
+
standing?: number;
|
|
76
|
+
/** With `candidates: all`: the configured models left out because they have no score yet. */
|
|
77
|
+
unscored?: number;
|
|
78
|
+
}
|
|
79
|
+
export declare const DEFAULT_POOL_RESERVE_PERCENT = 5;
|
|
80
|
+
export declare const DEFAULT_POOL_NEAR_TIE_PERCENT = 10;
|
|
81
|
+
export declare function isPoolClass(value: unknown): value is PoolClass;
|
|
82
|
+
export declare function poolClassScore(routing: Pick<AdaptiveRoutingConfig, 'classScores'>, poolClass: PoolClass): number;
|
|
83
|
+
/**
|
|
84
|
+
* Where a subscription stands: `blocked` when any live window has no more than the reserve left, and `standing` as
|
|
85
|
+
* the share of allowance left divided by the share of the window left (1 is on pace, above 1 is ahead). The pace
|
|
86
|
+
* comes from windows of a day or longer whose length and reset time are both known; the tightest one counts.
|
|
87
|
+
*/
|
|
88
|
+
export declare function quotaStanding(windows: readonly QuotaWindow[] | undefined, now: number, reservePercent: number): {
|
|
89
|
+
blocked: boolean;
|
|
90
|
+
standing?: number;
|
|
91
|
+
};
|
|
92
|
+
/** The class of a task from the evidence at hand, or undefined when nothing is decisive. */
|
|
93
|
+
export declare function classifyPoolClass(task: string, hints: DecisionBatch | undefined): {
|
|
94
|
+
poolClass: PoolClass;
|
|
95
|
+
evidence: 'hint' | 'lexical';
|
|
96
|
+
reason: EfficiencyReason;
|
|
97
|
+
} | undefined;
|
|
98
|
+
/** Decide the pair for one attempt. A target is named only when a configured pair reaches the class score. */
|
|
99
|
+
export declare function decidePoolModel(input: PoolDecisionInput): PoolDecision;
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { DecisionPolicy } from './decision/DecisionPolicy.js';
|
|
2
|
+
import { DEFAULT_POOL_CLASS_SCORES, POOL_CLASSES, poolEntries } from './efficiency.js';
|
|
3
|
+
import { MECHANICAL_MAX_CHARS, MECHANICAL_WORDS, RISK_WORDS } from './model-tiers.js';
|
|
4
|
+
export const DEFAULT_POOL_RESERVE_PERCENT = 5;
|
|
5
|
+
export const DEFAULT_POOL_NEAR_TIE_PERCENT = 10;
|
|
6
|
+
/** A window shorter than this (a session window) can hold a pair back when nearly empty but does not set the pace. */
|
|
7
|
+
const SHORT_WINDOW_SECONDS = 86_400;
|
|
8
|
+
/** The lowest standing a cost is divided by: a subscription far behind its pace makes a pair at most ten times dearer. */
|
|
9
|
+
const MIN_STANDING = 0.1;
|
|
10
|
+
const MAX_STANDING = 10;
|
|
11
|
+
const ESCALATION_REASONS = new Set(['repeatedToolFailure', 'maxIterations', 'maxCompletionRepairs', 'Prepared-step metadata allowance exhausted']);
|
|
12
|
+
export function isPoolClass(value) {
|
|
13
|
+
return typeof value === 'string' && POOL_CLASSES.includes(value);
|
|
14
|
+
}
|
|
15
|
+
export function poolClassScore(routing, poolClass) {
|
|
16
|
+
return routing.classScores?.[poolClass] ?? DEFAULT_POOL_CLASS_SCORES[poolClass];
|
|
17
|
+
}
|
|
18
|
+
function nextPoolClass(poolClass) {
|
|
19
|
+
const index = POOL_CLASSES.indexOf(poolClass);
|
|
20
|
+
return index >= 0 && index < POOL_CLASSES.length - 1 ? POOL_CLASSES[index + 1] : undefined;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Where a subscription stands: `blocked` when any live window has no more than the reserve left, and `standing` as
|
|
24
|
+
* the share of allowance left divided by the share of the window left (1 is on pace, above 1 is ahead). The pace
|
|
25
|
+
* comes from windows of a day or longer whose length and reset time are both known; the tightest one counts.
|
|
26
|
+
*/
|
|
27
|
+
export function quotaStanding(windows, now, reservePercent) {
|
|
28
|
+
let blocked = false;
|
|
29
|
+
let standing;
|
|
30
|
+
for (const window of windows ?? []) {
|
|
31
|
+
if (!Number.isFinite(window.usedPercent))
|
|
32
|
+
continue;
|
|
33
|
+
// A window whose reset time has passed describes an allowance that no longer exists.
|
|
34
|
+
if (window.resetsAt !== undefined && window.resetsAt <= now)
|
|
35
|
+
continue;
|
|
36
|
+
const remaining = Math.min(100, Math.max(0, 100 - window.usedPercent));
|
|
37
|
+
if (remaining <= reservePercent)
|
|
38
|
+
blocked = true;
|
|
39
|
+
if (window.resetsAt === undefined || window.windowSeconds === undefined || window.windowSeconds < SHORT_WINDOW_SECONDS)
|
|
40
|
+
continue;
|
|
41
|
+
const timeLeft = Math.min(1, Math.max(0.01, (window.resetsAt - now) / (window.windowSeconds * 1000)));
|
|
42
|
+
const pace = Math.min(MAX_STANDING, remaining / 100 / timeLeft);
|
|
43
|
+
standing = standing === undefined ? pace : Math.min(standing, pace);
|
|
44
|
+
}
|
|
45
|
+
return { blocked, ...(standing === undefined ? {} : { standing }) };
|
|
46
|
+
}
|
|
47
|
+
/** The class of a task from the evidence at hand, or undefined when nothing is decisive. */
|
|
48
|
+
export function classifyPoolClass(task, hints) {
|
|
49
|
+
const risk = hints !== undefined && (DecisionPolicy.boolean(hints, 'security_sensitive') === true || DecisionPolicy.boolean(hints, 'architecture_affecting') === true);
|
|
50
|
+
const complexity = hints ? DecisionPolicy.score(hints, 'task_complexity') : undefined;
|
|
51
|
+
if (risk)
|
|
52
|
+
return { poolClass: 'deep', evidence: 'hint', reason: 'risk' };
|
|
53
|
+
if (RISK_WORDS.test(task))
|
|
54
|
+
return { poolClass: 'deep', evidence: 'lexical', reason: 'risk' };
|
|
55
|
+
if (complexity !== undefined && complexity >= 0.8)
|
|
56
|
+
return { poolClass: 'deep', evidence: 'hint', reason: 'deep' };
|
|
57
|
+
const short = task.length <= MECHANICAL_MAX_CHARS;
|
|
58
|
+
if (short && MECHANICAL_WORDS.test(task) && (complexity === undefined || complexity <= 0.4))
|
|
59
|
+
return { poolClass: 'routine', evidence: 'lexical', reason: 'routine' };
|
|
60
|
+
if (complexity !== undefined && complexity <= 0.25 && short)
|
|
61
|
+
return { poolClass: 'quick', evidence: 'hint', reason: 'quick' };
|
|
62
|
+
if (complexity !== undefined)
|
|
63
|
+
return { poolClass: 'standard', evidence: 'hint', reason: 'standard' };
|
|
64
|
+
return undefined;
|
|
65
|
+
}
|
|
66
|
+
function configuredTarget(entry, configured) {
|
|
67
|
+
const provider = configured.find(item => item.id === entry.provider);
|
|
68
|
+
if (!provider)
|
|
69
|
+
return undefined;
|
|
70
|
+
const model = entry.model ?? provider.model;
|
|
71
|
+
if (!model)
|
|
72
|
+
return undefined;
|
|
73
|
+
if (entry.model !== undefined && provider.models?.length && !provider.models.includes(entry.model) && provider.model !== entry.model)
|
|
74
|
+
return undefined;
|
|
75
|
+
return { provider: provider.id, model, ...(entry.effort === undefined ? {} : { effort: entry.effort }) };
|
|
76
|
+
}
|
|
77
|
+
/** Decide the pair for one attempt. A target is named only when a configured pair reaches the class score. */
|
|
78
|
+
export function decidePoolModel(input) {
|
|
79
|
+
const kept = { applied: false, reason: 'baseline', evidence: 'none', candidates: 0, blocked: 0 };
|
|
80
|
+
const routing = input.routing;
|
|
81
|
+
if (!routing.enabled || routing.strategy !== 'pool')
|
|
82
|
+
return { ...kept, reason: 'unconfigured', evidence: 'policy' };
|
|
83
|
+
const { entries, unscored } = poolEntries(routing, input.configured, input.levels);
|
|
84
|
+
const counted = unscored > 0 ? { unscored } : {};
|
|
85
|
+
if (!entries.length)
|
|
86
|
+
return { ...kept, ...counted, reason: 'unconfigured', evidence: 'policy' };
|
|
87
|
+
if (input.node.provider !== undefined || input.node.model !== undefined || input.modelPinned)
|
|
88
|
+
return { ...kept, reason: 'pinned', evidence: 'pinned' };
|
|
89
|
+
let poolClass;
|
|
90
|
+
let reason;
|
|
91
|
+
let evidence;
|
|
92
|
+
if (input.previous) {
|
|
93
|
+
const { poolClass: ran, reason: why, escalations } = input.previous;
|
|
94
|
+
const failed = why !== undefined && ESCALATION_REASONS.has(why);
|
|
95
|
+
const higher = failed && escalations < routing.maxEscalations ? nextPoolClass(ran) : undefined;
|
|
96
|
+
poolClass = higher ?? ran;
|
|
97
|
+
reason = higher ? 'escalated' : failed ? 'escalation_limit' : 'baseline';
|
|
98
|
+
evidence = 'escalation';
|
|
99
|
+
}
|
|
100
|
+
else if (input.declaredClass) {
|
|
101
|
+
poolClass = input.declaredClass;
|
|
102
|
+
reason = input.declaredClass;
|
|
103
|
+
evidence = 'declared';
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
const classified = classifyPoolClass(input.task, input.hints);
|
|
107
|
+
if (!classified)
|
|
108
|
+
return { ...kept, reason: 'low_confidence' };
|
|
109
|
+
({ poolClass, reason, evidence } = classified);
|
|
110
|
+
}
|
|
111
|
+
const needed = poolClassScore(routing, poolClass);
|
|
112
|
+
const sufficient = entries.flatMap(entry => {
|
|
113
|
+
const target = entry.quality >= needed ? configuredTarget(entry, input.configured) : undefined;
|
|
114
|
+
return target ? [{ entry, target }] : [];
|
|
115
|
+
});
|
|
116
|
+
if (!sufficient.length)
|
|
117
|
+
return { ...kept, ...counted, poolClass, reason: 'no_candidate', evidence };
|
|
118
|
+
const now = input.now ?? Date.now();
|
|
119
|
+
const reserve = routing.quota?.reservePercent ?? DEFAULT_POOL_RESERVE_PERCENT;
|
|
120
|
+
const open = sufficient.map(item => ({ ...item, ...quotaStanding(input.quota?.[item.target.provider], now, reserve) })).filter(item => !item.blocked);
|
|
121
|
+
const blocked = sufficient.length - open.length;
|
|
122
|
+
if (!open.length)
|
|
123
|
+
return { ...kept, ...counted, poolClass, reason: 'quota_reserve', evidence, candidates: sufficient.length, blocked };
|
|
124
|
+
// A pair's cost stands for the allowance one task uses on its subscription, and the standing says what that
|
|
125
|
+
// allowance is worth now: the cost is divided by it. Unknown usage is on pace (1), neither preferred nor avoided.
|
|
126
|
+
// With no cost given, a higher score is taken to cost more, so the lowest sufficient pair wins.
|
|
127
|
+
const cost = (item) => (item.entry.cost ?? item.entry.quality) / Math.max(MIN_STANDING, item.standing ?? 1);
|
|
128
|
+
const cheapest = Math.min(...open.map(cost));
|
|
129
|
+
const nearTie = 1 + (routing.quota?.nearTiePercent ?? DEFAULT_POOL_NEAR_TIE_PERCENT) / 100;
|
|
130
|
+
const chosen = open.filter(item => cost(item) <= cheapest * nearTie)
|
|
131
|
+
.reduce((first, next) => (next.standing ?? 1) > (first.standing ?? 1) ? next : first);
|
|
132
|
+
const { target } = chosen;
|
|
133
|
+
const applied = target.provider !== input.baseline.provider || target.model !== input.baseline.model
|
|
134
|
+
|| (target.effort !== undefined && target.effort !== input.baseline.effort);
|
|
135
|
+
return { poolClass, target, applied, reason, evidence, candidates: sufficient.length, blocked, ...counted, ...(chosen.standing === undefined ? {} : { standing: chosen.standing }) };
|
|
136
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { configuredModelSnapshot } from '../model-metadata.js';
|
|
2
2
|
import { ANDORRA_SESSION_ID, findProviderById, ProviderRequestError, REASONING_EFFORTS, RetryableProviderError, supportsReasoningEffort } from '../providers.js';
|
|
3
|
+
import { ProviderTurnTimeoutError } from '../provider-turn-deadline.js';
|
|
3
4
|
import { redactSecrets } from '../memory/redaction.js';
|
|
4
5
|
import { RELAY_DELTA_LIMIT_BYTES, RELAY_FAILURE_CODE, RELAY_PAYLOAD_LIMIT_BYTES } from './remote.js';
|
|
5
6
|
/** At most this many relayed requests of one machine are in hand at once, generating or waiting to be delivered; another is left for a later announce. */
|
|
@@ -77,6 +78,10 @@ function failureOf(error) {
|
|
|
77
78
|
const message = shownMessage(error);
|
|
78
79
|
if (!(error instanceof ProviderRequestError))
|
|
79
80
|
return { message, kind: 'other' };
|
|
81
|
+
if (error instanceof ProviderTurnTimeoutError) {
|
|
82
|
+
const { phase, limitMs, elapsedMs, lastProgressAgeMs } = error;
|
|
83
|
+
return { message, kind: 'provider-request', code: 'provider_timeout', timeout: { phase, limitMs, elapsedMs, lastProgressAgeMs } };
|
|
84
|
+
}
|
|
80
85
|
const code = typeof error.telemetryCode === 'string' && RELAY_FAILURE_CODE.test(error.telemetryCode) ? error.telemetryCode : undefined;
|
|
81
86
|
return {
|
|
82
87
|
message, kind: error instanceof RetryableProviderError ? 'retryable' : 'provider-request',
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type ProviderConfig } from '../providers.js';
|
|
2
|
+
import { type ProviderTurnTiming } from '../provider-turn-deadline.js';
|
|
2
3
|
import type { Message, ModelAdapter, ModelRequestContext, ModelResponse, ModelRetry, ToolSchema } from '../types.js';
|
|
3
4
|
/** One model request's JSON payload may be this large; with its envelope it stays under the relay's 16 MiB frame. */
|
|
4
5
|
export declare const RELAY_PAYLOAD_LIMIT_BYTES: number;
|
|
@@ -39,6 +40,7 @@ export interface RelayFailure {
|
|
|
39
40
|
kind: RelayErrorKind;
|
|
40
41
|
contextOverflow?: true;
|
|
41
42
|
code?: string;
|
|
43
|
+
timeout?: ProviderTurnTiming;
|
|
42
44
|
}
|
|
43
45
|
/** The form a relayed failure's telemetry code must have. */
|
|
44
46
|
export declare const RELAY_FAILURE_CODE: RegExp;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { ProviderRequestError, RetryableProviderError } from '../providers.js';
|
|
3
|
+
import { ProviderTurnTimeoutError, readProviderTurnTiming } from '../provider-turn-deadline.js';
|
|
3
4
|
/** One model request's JSON payload may be this large; with its envelope it stays under the relay's 16 MiB frame. */
|
|
4
5
|
export const RELAY_PAYLOAD_LIMIT_BYTES = 12 * 1024 * 1024;
|
|
5
6
|
/** An unclaimed request is announced again this often, so a desktop that attaches later still sees it. */
|
|
@@ -46,6 +47,9 @@ function boundedDelta(delta) {
|
|
|
46
47
|
function failure(error) {
|
|
47
48
|
const message = typeof error?.message === 'string' && error.message.trim() ? error.message : 'The model request failed on your computer.';
|
|
48
49
|
const code = typeof error?.code === 'string' && RELAY_FAILURE_CODE.test(error.code) ? error.code : undefined;
|
|
50
|
+
const timing = error?.kind === 'provider-request' && code === 'provider_timeout' ? readProviderTurnTiming(error.timeout) : undefined;
|
|
51
|
+
if (timing)
|
|
52
|
+
return new ProviderTurnTimeoutError(timing.phase, timing.limitMs, timing.elapsedMs, timing.lastProgressAgeMs);
|
|
49
53
|
let failed;
|
|
50
54
|
if (error?.kind === 'retryable')
|
|
51
55
|
failed = new RetryableProviderError(message);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { DecisionBatch } from './decision/types.js';
|
|
2
|
-
import { type AdaptiveRoutingConfig, type EfficiencyReason, type ModelPricing, type ModelTier } from './efficiency.js';
|
|
2
|
+
import { type AdaptiveRoutingConfig, type EfficiencyReason, type ModelPricing, type ModelTier, type PoolEffort } from './efficiency.js';
|
|
3
3
|
import type { Usage } from './types.js';
|
|
4
4
|
export interface TierDecisionInput {
|
|
5
5
|
task: string;
|
|
@@ -27,17 +27,32 @@ export interface TierDecisionInput {
|
|
|
27
27
|
reason?: string;
|
|
28
28
|
escalations: number;
|
|
29
29
|
};
|
|
30
|
+
/** The thinking levels a provider's model takes. Without it every scored level can be chosen. */
|
|
31
|
+
levels?: (provider: string, model: string) => readonly string[] | undefined;
|
|
30
32
|
}
|
|
31
33
|
export interface TierDecision {
|
|
32
34
|
tier?: ModelTier;
|
|
35
|
+
/** `effort` is the tier's thinking level: the one the tier names, or the one chosen from the model's scores. */
|
|
33
36
|
target?: {
|
|
34
37
|
provider: string;
|
|
35
38
|
model: string;
|
|
39
|
+
effort?: PoolEffort;
|
|
36
40
|
};
|
|
37
41
|
applied: boolean;
|
|
38
42
|
reason: EfficiencyReason;
|
|
39
43
|
evidence: 'policy' | 'pinned' | 'hint' | 'lexical' | 'escalation' | 'none';
|
|
40
44
|
}
|
|
45
|
+
export declare const RISK_WORDS: RegExp;
|
|
46
|
+
export declare const MECHANICAL_WORDS: RegExp;
|
|
47
|
+
export declare const MECHANICAL_MAX_CHARS = 400;
|
|
48
|
+
/**
|
|
49
|
+
* The thinking level a tier's model runs at, from its scores: the cheapest scored level that reaches the tier's
|
|
50
|
+
* score, or the best-scored level when none reaches it. Undefined when no level the model takes is scored.
|
|
51
|
+
*/
|
|
52
|
+
export declare function tierEffort(routing: Pick<AdaptiveRoutingConfig, 'scores' | 'classScores'>, tier: ModelTier, target: {
|
|
53
|
+
provider: string;
|
|
54
|
+
model: string;
|
|
55
|
+
}, levels?: (provider: string, model: string) => readonly string[] | undefined): PoolEffort | undefined;
|
|
41
56
|
export declare function classifyTier(task: string, hints: DecisionBatch | undefined): {
|
|
42
57
|
tier: ModelTier;
|
|
43
58
|
evidence: 'hint' | 'lexical';
|
package/dist/src/model-tiers.js
CHANGED
|
@@ -1,9 +1,31 @@
|
|
|
1
1
|
import { DecisionPolicy } from './decision/DecisionPolicy.js';
|
|
2
|
-
import { MODEL_TIERS } from './efficiency.js';
|
|
3
|
-
const RISK_WORDS = /\b(security|auth(?:entication|orization|n)?|credential|secret|token|crypt|permission|sandbox|race condition|deadlock|memory leak|crash|segfault|corrupt|data loss|architecture|architectural|redesign|migration|migrate|concurrency|thread|lock|regression|flaky|intermittent|nondeterministic|root cause)\b/i;
|
|
4
|
-
const MECHANICAL_WORDS = /\b(rename|typo|comment|docstring|jsdoc|format(?:ting)?|reformat|prettier|lint(?: fix)?|bump (?:the )?version|changelog|readme|whitespace|trailing|reorder imports|sort imports|unused import|remove unused|add (?:a )?log|console\.log|copyright|license header|spelling|wording)\b/i;
|
|
5
|
-
const MECHANICAL_MAX_CHARS = 400;
|
|
2
|
+
import { DEFAULT_POOL_CLASS_SCORES, MODEL_TIERS, POOL_EFFORTS, poolScoreKey } from './efficiency.js';
|
|
3
|
+
export const RISK_WORDS = /\b(security|auth(?:entication|orization|n)?|credential|secret|token|crypt|permission|sandbox|race condition|deadlock|memory leak|crash|segfault|corrupt|data loss|architecture|architectural|redesign|migration|migrate|concurrency|thread|lock|regression|flaky|intermittent|nondeterministic|root cause)\b/i;
|
|
4
|
+
export const MECHANICAL_WORDS = /\b(rename|typo|comment|docstring|jsdoc|format(?:ting)?|reformat|prettier|lint(?: fix)?|bump (?:the )?version|changelog|readme|whitespace|trailing|reorder imports|sort imports|unused import|remove unused|add (?:a )?log|console\.log|copyright|license header|spelling|wording)\b/i;
|
|
5
|
+
export const MECHANICAL_MAX_CHARS = 400;
|
|
6
6
|
const ESCALATION_REASONS = new Set(['repeatedToolFailure', 'maxIterations', 'maxCompletionRepairs', 'Prepared-step metadata allowance exhausted']);
|
|
7
|
+
/** The class whose score a tier's thinking level must reach. */
|
|
8
|
+
const TIER_CLASS = { economy: 'quick', balanced: 'standard', premium: 'deep' };
|
|
9
|
+
/**
|
|
10
|
+
* The thinking level a tier's model runs at, from its scores: the cheapest scored level that reaches the tier's
|
|
11
|
+
* score, or the best-scored level when none reaches it. Undefined when no level the model takes is scored.
|
|
12
|
+
*/
|
|
13
|
+
export function tierEffort(routing, tier, target, levels) {
|
|
14
|
+
const key = poolScoreKey(target.provider, target.model);
|
|
15
|
+
const score = routing.scores && Object.hasOwn(routing.scores, key) ? routing.scores[key] : undefined;
|
|
16
|
+
const taken = levels?.(target.provider, target.model);
|
|
17
|
+
const scored = POOL_EFFORTS.flatMap(effort => {
|
|
18
|
+
const pair = score?.efforts?.[effort];
|
|
19
|
+
return pair && (taken === undefined || taken.includes(effort)) ? [{ effort, quality: pair.quality, cost: pair.cost ?? pair.quality }] : [];
|
|
20
|
+
});
|
|
21
|
+
if (!scored.length)
|
|
22
|
+
return undefined;
|
|
23
|
+
const needed = routing.classScores?.[TIER_CLASS[tier]] ?? DEFAULT_POOL_CLASS_SCORES[TIER_CLASS[tier]];
|
|
24
|
+
const reaching = scored.filter(item => item.quality >= needed);
|
|
25
|
+
if (!reaching.length)
|
|
26
|
+
return scored.reduce((best, next) => next.quality > best.quality ? next : best).effort;
|
|
27
|
+
return reaching.reduce((best, next) => next.cost < best.cost ? next : best).effort;
|
|
28
|
+
}
|
|
7
29
|
function configuredTarget(target, configured) {
|
|
8
30
|
if (!target)
|
|
9
31
|
return undefined;
|
|
@@ -15,7 +37,7 @@ function configuredTarget(target, configured) {
|
|
|
15
37
|
return undefined;
|
|
16
38
|
if (target.model !== undefined && provider.models?.length && !provider.models.includes(target.model) && provider.model !== target.model)
|
|
17
39
|
return undefined;
|
|
18
|
-
return { provider: provider.id, model };
|
|
40
|
+
return { provider: provider.id, model, ...(target.effort === undefined ? {} : { effort: target.effort }) };
|
|
19
41
|
}
|
|
20
42
|
function nextTier(tier) {
|
|
21
43
|
const index = MODEL_TIERS.indexOf(tier);
|
|
@@ -46,9 +68,11 @@ export function decideModelTier(input) {
|
|
|
46
68
|
if (input.node.provider !== undefined || input.node.model !== undefined || input.modelPinned)
|
|
47
69
|
return { ...baseline, reason: 'pinned', evidence: 'pinned' };
|
|
48
70
|
const resolve = (tier, reason, evidence) => {
|
|
49
|
-
const
|
|
50
|
-
if (!
|
|
71
|
+
const found = configuredTarget(input.routing.tiers?.[tier], input.configured);
|
|
72
|
+
if (!found)
|
|
51
73
|
return { ...baseline, tier, reason: 'unconfigured', evidence };
|
|
74
|
+
const effort = found.effort ?? tierEffort(input.routing, tier, found, input.levels);
|
|
75
|
+
const target = effort === undefined ? found : { ...found, effort };
|
|
52
76
|
const differs = target.provider !== input.baseline.provider || target.model !== input.baseline.model;
|
|
53
77
|
return { tier, target, applied: differs, reason, evidence };
|
|
54
78
|
};
|
|
@@ -7,6 +7,7 @@ import { resolveCliExecutable } from './cli-executable.js';
|
|
|
7
7
|
import { stopProcessTree } from './cli-process.js';
|
|
8
8
|
import { resolveTrustedTaskkill } from './shell.js';
|
|
9
9
|
import { allowanceInstruction, boundTextStep, parseStructuredStep, STRUCTURED_STEP_PROMPT, STRUCTURED_STEP_SCHEMA, structuredStepPrompt, TEXT_STEP_PROMPT } from './structured-step.js';
|
|
10
|
+
import { DEFAULT_WHOLE_RESPONSE_MS, withProviderTurnDeadline } from './provider-turn-deadline.js';
|
|
10
11
|
export const OPENCODE_BASE_URL = 'https://opencode.ai';
|
|
11
12
|
export const OPENCODE_EXECUTABLE = {
|
|
12
13
|
names: ['opencode'], overrideEnv: 'ANDORRA_OPENCODE_PATH', homeDirectories: [join('.opencode', 'bin')],
|
|
@@ -15,7 +16,6 @@ export const OPENCODE_EXECUTABLE = {
|
|
|
15
16
|
};
|
|
16
17
|
const START_TIMEOUT_MS = 60_000;
|
|
17
18
|
const IDLE_STOP_MS = 5 * 60_000;
|
|
18
|
-
const REQUEST_TIMEOUT_MS = 10 * 60_000;
|
|
19
19
|
const CATALOG_TIMEOUT_MS = 30_000;
|
|
20
20
|
const RETRY_POLL_MS = 2_000;
|
|
21
21
|
const STRUCTURED_AGENT = 'andorra';
|
|
@@ -245,66 +245,69 @@ export function createOpenCodeCliAdapter(_config, dependencies = {}) {
|
|
|
245
245
|
if (auxiliary && request.tools.length)
|
|
246
246
|
throw new Error('OpenCode cannot apply an auxiliary output allowance to tool-bearing requests.');
|
|
247
247
|
const { providerID, modelID } = splitModel(request.model);
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
248
|
+
return withProviderTurnDeadline(request.signal, async (deadline) => {
|
|
249
|
+
const { signal } = deadline;
|
|
250
|
+
const created = await server().request('/session', { method: 'POST', body: { title: 'Andorra model step' }, signal });
|
|
251
|
+
const sessionId = object(created.body)?.id;
|
|
252
|
+
if (created.status !== 200 || typeof sessionId !== 'string' || !/^[\w-]{1,200}$/.test(sessionId))
|
|
253
|
+
throw new Error('OpenCode could not open a session.');
|
|
254
|
+
const parts = [{ type: 'text', text: structuredStepPrompt(request) }];
|
|
255
|
+
request.messages.forEach((message, index) => message.images?.forEach((image, imageIndex) => {
|
|
256
|
+
parts.push({ type: 'text', text: `Image ${imageIndex + 1} from conversation message ${index + 1}:` }, { type: 'file', mime: image.mimeType, url: `data:${image.mimeType};base64,${image.data}`, filename: `image-${index + 1}-${imageIndex + 1}` });
|
|
257
|
+
}));
|
|
258
|
+
const watch = new AbortController();
|
|
259
|
+
let retried;
|
|
260
|
+
const poll = (async () => {
|
|
261
|
+
while (!watch.signal.aborted) {
|
|
262
|
+
await new Promise(resolve => setTimeout(resolve, dependencies.retryPollMs ?? RETRY_POLL_MS));
|
|
263
|
+
if (watch.signal.aborted)
|
|
264
|
+
return;
|
|
265
|
+
const status = await server().request('/session/status', { signal: AbortSignal.any([signal, watch.signal]) }).catch(() => undefined);
|
|
266
|
+
const state = object(object(status?.body)?.[sessionId]);
|
|
267
|
+
if (state?.type === 'retry') {
|
|
268
|
+
retried = note(state.message) ?? 'the provider asked to retry later';
|
|
269
|
+
watch.abort();
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
270
272
|
}
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
const stopped = AbortSignal.any([signal, watch.signal]);
|
|
274
|
-
try {
|
|
275
|
-
request.onRequest?.();
|
|
276
|
-
let reply;
|
|
273
|
+
})();
|
|
274
|
+
const stopped = AbortSignal.any([signal, watch.signal]);
|
|
277
275
|
try {
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
|
|
276
|
+
deadline.waitForResponse();
|
|
277
|
+
request.onRequest?.();
|
|
278
|
+
let reply;
|
|
279
|
+
try {
|
|
280
|
+
reply = await server().request(`/session/${sessionId}/message`, { method: 'POST', signal: stopped, body: {
|
|
281
|
+
model: { providerID, modelID }, agent: auxiliary ? TEXT_AGENT : STRUCTURED_AGENT, parts,
|
|
282
|
+
...(auxiliary ? { system: allowanceInstruction(request.maxTokens) } : {}),
|
|
283
|
+
...(auxiliary ? {} : { format: { type: 'json_schema', schema: STRUCTURED_STEP_SCHEMA, retryCount: 1 } }),
|
|
284
|
+
} });
|
|
285
|
+
}
|
|
286
|
+
catch (error) {
|
|
287
|
+
if (retried)
|
|
288
|
+
throw new Error(`OpenCode request failed: ${retried}`);
|
|
289
|
+
throw error;
|
|
290
|
+
}
|
|
285
291
|
if (retried)
|
|
286
292
|
throw new Error(`OpenCode request failed: ${retried}`);
|
|
287
|
-
|
|
293
|
+
if (reply.status !== 200)
|
|
294
|
+
throw upstreamFailure(object(reply.body), providerID);
|
|
295
|
+
const response = parseOpenCodeReply(reply.body, request.tools, providerID, !auxiliary);
|
|
296
|
+
if (!auxiliary)
|
|
297
|
+
return response;
|
|
298
|
+
const visible = reply.body.info?.tokens?.output;
|
|
299
|
+
return boundTextStep(response, request.maxTokens, Number.isSafeInteger(visible) ? visible : undefined);
|
|
288
300
|
}
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
}
|
|
299
|
-
finally {
|
|
300
|
-
const interrupted = stopped.aborted;
|
|
301
|
-
watch.abort();
|
|
302
|
-
await poll;
|
|
303
|
-
const cleanup = AbortSignal.timeout(10_000);
|
|
304
|
-
if (interrupted)
|
|
305
|
-
await server().request(`/session/${sessionId}/abort`, { method: 'POST', signal: cleanup }).catch(() => { });
|
|
306
|
-
await server().request(`/session/${sessionId}`, { method: 'DELETE', signal: cleanup }).catch(() => { });
|
|
307
|
-
}
|
|
301
|
+
finally {
|
|
302
|
+
const interrupted = stopped.aborted;
|
|
303
|
+
watch.abort();
|
|
304
|
+
await poll;
|
|
305
|
+
const cleanup = AbortSignal.timeout(10_000);
|
|
306
|
+
if (interrupted)
|
|
307
|
+
await server().request(`/session/${sessionId}/abort`, { method: 'POST', signal: cleanup }).catch(() => { });
|
|
308
|
+
await server().request(`/session/${sessionId}`, { method: 'DELETE', signal: cleanup }).catch(() => { });
|
|
309
|
+
}
|
|
310
|
+
}, { responseMs: DEFAULT_WHOLE_RESPONSE_MS });
|
|
308
311
|
},
|
|
309
312
|
};
|
|
310
313
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createProviderTurnDeadline, ProviderTurnTimeoutError } from './provider-turn-deadline.js';
|
|
1
2
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
3
|
import { loadEngineStreams } from './engine-streams.js';
|
|
3
4
|
import { andorraNormalizeContext } from '../vendor/engine/runtime/ai/utils/transcript.js';
|
|
@@ -208,15 +209,13 @@ export function createOpenCodeAdapter(config, dependencies = {}) {
|
|
|
208
209
|
...(protocol === 'openai-completions' ? { compat: { supportsDeveloperRole: false, supportsStore: false,
|
|
209
210
|
supportsMidConvoSystemMessages: true, requiresReasoningContentOnAssistantMessages: true } } : {}) };
|
|
210
211
|
const timeoutMs = config.streamIdleTimeoutMs ?? config.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
211
|
-
const deadline =
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
const refresh = () => { clearTimeout(timer); if (timeoutMs > 0)
|
|
215
|
-
timer = setTimeout(() => deadline.abort(), timeoutMs); };
|
|
212
|
+
const deadline = createProviderTurnDeadline(request.signal, { startupMs: timeoutMs, idleMs: timeoutMs,
|
|
213
|
+
...(timeoutMs === 0 ? { totalMs: 0 } : {}) });
|
|
214
|
+
const { signal } = deadline;
|
|
216
215
|
let wire = '', transportError;
|
|
217
216
|
let cancelBody = async () => { };
|
|
218
217
|
const send = async (body) => {
|
|
219
|
-
|
|
218
|
+
deadline.waitForResponse();
|
|
220
219
|
request.onRequest?.();
|
|
221
220
|
const headers = { 'content-type': 'application/json', 'user-agent': 'andorra-code/0.1', 'x-opencode-session': session };
|
|
222
221
|
if (protocol === 'anthropic-messages') {
|
|
@@ -285,7 +284,7 @@ export function createOpenCodeAdapter(config, dependencies = {}) {
|
|
|
285
284
|
let size = 0, ended = false;
|
|
286
285
|
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
287
286
|
let controller;
|
|
288
|
-
const finish = () => { ended = true;
|
|
287
|
+
const finish = () => { ended = true; signal.removeEventListener('abort', abort); };
|
|
289
288
|
cancelBody = async () => { if (!ended) {
|
|
290
289
|
finish();
|
|
291
290
|
await reader.cancel().catch(() => { });
|
|
@@ -313,7 +312,6 @@ export function createOpenCodeAdapter(config, dependencies = {}) {
|
|
|
313
312
|
if ((size += chunk.value.byteLength) > OUTPUT_LIMIT)
|
|
314
313
|
throw new Error('OpenCode Go response exceeds the 4 MiB limit.');
|
|
315
314
|
wire += decoder.decode(chunk.value, { stream: true });
|
|
316
|
-
refresh();
|
|
317
315
|
value.enqueue(chunk.value);
|
|
318
316
|
}
|
|
319
317
|
catch (error) {
|
|
@@ -335,7 +333,7 @@ export function createOpenCodeAdapter(config, dependencies = {}) {
|
|
|
335
333
|
try {
|
|
336
334
|
let result;
|
|
337
335
|
if (protocol === 'google-generative-ai')
|
|
338
|
-
result = await googleResponse(request, model, send, effort, providerTools, codec);
|
|
336
|
+
result = await googleResponse(request, model, send, effort, providerTools, codec, deadline.progress);
|
|
339
337
|
else {
|
|
340
338
|
const nativeRequest = { ...request, messages: request.messages.map(message => {
|
|
341
339
|
const saved = message.providerContinuation;
|
|
@@ -353,6 +351,8 @@ export function createOpenCodeAdapter(config, dependencies = {}) {
|
|
|
353
351
|
const stream = protocol === 'openai-completions' ? chatStream(model, context, options)
|
|
354
352
|
: protocol === 'openai-responses' ? responsesStream(model, context, options) : messagesStream(model, context, options);
|
|
355
353
|
for await (const event of stream) {
|
|
354
|
+
if ((event.type === 'text_delta' || event.type === 'thinking_delta' || event.type === 'toolcall_delta') && event.delta)
|
|
355
|
+
deadline.progress();
|
|
356
356
|
if (event.type === 'text_delta')
|
|
357
357
|
request.onText?.(event.delta);
|
|
358
358
|
if (event.type === 'thinking_delta')
|
|
@@ -386,8 +386,8 @@ export function createOpenCodeAdapter(config, dependencies = {}) {
|
|
|
386
386
|
catch (error) {
|
|
387
387
|
if (request.signal.aborted)
|
|
388
388
|
throw new Error('OpenCode Go request cancelled.');
|
|
389
|
-
if (
|
|
390
|
-
throw
|
|
389
|
+
if (signal.reason instanceof ProviderTurnTimeoutError)
|
|
390
|
+
throw signal.reason;
|
|
391
391
|
if (error instanceof ProviderRequestError)
|
|
392
392
|
throw error;
|
|
393
393
|
if (error instanceof Error && /^OpenCode Go (?:response exceeds|returned)/.test(error.message))
|
|
@@ -395,7 +395,7 @@ export function createOpenCodeAdapter(config, dependencies = {}) {
|
|
|
395
395
|
throw new Error('OpenCode Go request failed. Check the Go connection and model availability.');
|
|
396
396
|
}
|
|
397
397
|
finally {
|
|
398
|
-
|
|
398
|
+
deadline.dispose();
|
|
399
399
|
await cancelBody();
|
|
400
400
|
}
|
|
401
401
|
},
|
|
@@ -413,7 +413,7 @@ function engineResponse(output, provider, model) {
|
|
|
413
413
|
usage: { inputTokens: counter(output.usage.input) + counter(output.usage.cacheRead) + counter(output.usage.cacheWrite),
|
|
414
414
|
outputTokens: counter(output.usage.output), cacheRead: counter(output.usage.cacheRead), cacheWrite: counter(output.usage.cacheWrite), requests: 1 } };
|
|
415
415
|
}
|
|
416
|
-
async function googleResponse(request, model, send, effort, providerTools, codec) {
|
|
416
|
+
async function googleResponse(request, model, send, effort, providerTools, codec, progress) {
|
|
417
417
|
const engineMessages = toEngineMessages(request, model, codec);
|
|
418
418
|
for (const [index, message] of engineMessages.entries())
|
|
419
419
|
if (message.role === 'assistant') {
|
|
@@ -475,6 +475,8 @@ async function googleResponse(request, model, send, effort, providerTools, codec
|
|
|
475
475
|
object(part);
|
|
476
476
|
parts.push(part);
|
|
477
477
|
if (typeof part.text === 'string') {
|
|
478
|
+
if (part.text)
|
|
479
|
+
progress();
|
|
478
480
|
if (part.thought) {
|
|
479
481
|
thoughts.push(part.text);
|
|
480
482
|
request.onReasoning?.(part.text);
|
|
@@ -491,6 +493,7 @@ async function googleResponse(request, model, send, effort, providerTools, codec
|
|
|
491
493
|
if (typeof call.name !== 'string' || !call.name)
|
|
492
494
|
malformed();
|
|
493
495
|
calls.push({ id, name: call.name, arguments: JSON.stringify(object(call.args ?? {})) });
|
|
496
|
+
progress();
|
|
494
497
|
}
|
|
495
498
|
}
|
|
496
499
|
};
|