@andorra-labs/code 0.1.18 → 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 +347 -45
- 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/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 +23 -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 +3 -1
- package/dist/src/app-server/workspace.js +39 -8
- package/dist/src/app-server.d.ts +50 -25
- package/dist/src/app-server.js +1008 -400
- 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/benchmark-scores.d.ts +88 -0
- package/dist/src/benchmark-scores.js +302 -0
- package/dist/src/bridge/command.js +4 -1
- package/dist/src/bridge/control.js +2 -1
- package/dist/src/bridge/engines.d.ts +2 -0
- package/dist/src/bridge/engines.js +9 -0
- package/dist/src/bridge/host-ops.d.ts +2 -2
- package/dist/src/bridge/host-ops.js +4 -2
- package/dist/src/bridge/host.d.ts +2 -0
- package/dist/src/bridge/host.js +63 -12
- 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/claude-provider.d.ts +1 -0
- package/dist/src/claude-provider.js +77 -36
- package/dist/src/cli.js +235 -58
- package/dist/src/codex-provider.d.ts +1 -0
- package/dist/src/codex-provider.js +43 -7
- package/dist/src/coding-tools.d.ts +1 -0
- package/dist/src/coding-tools.js +19 -5
- package/dist/src/command-screens.d.ts +1 -1
- package/dist/src/command-screens.js +2 -2
- package/dist/src/commands.d.ts +8 -1
- package/dist/src/commands.js +67 -63
- package/dist/src/completion.js +5 -3
- package/dist/src/config.d.ts +14 -3
- package/dist/src/config.js +54 -16
- package/dist/src/context-budget.d.ts +11 -2
- package/dist/src/context-budget.js +23 -2
- 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/DecisionManager.d.ts +5 -0
- package/dist/src/decision/DecisionManager.js +39 -2
- package/dist/src/decision/applyToolMenu.js +6 -2
- package/dist/src/decision/hostedPolicy.js +6 -4
- 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 +2 -1
- package/dist/src/decision/providers/AndorraDecisionProvider.js +17 -7
- package/dist/src/decision/providers/index.js +1 -1
- package/dist/src/decision/toolFamilies.js +1 -1
- package/dist/src/decision/types.d.ts +2 -0
- package/dist/src/efficiency.d.ts +75 -1
- package/dist/src/efficiency.js +114 -3
- 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/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/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-runner.js +19 -13
- 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 +45 -10
- package/dist/src/graph-sync.d.ts +2 -1
- package/dist/src/graph-sync.js +13 -0
- package/dist/src/graph-ui/app.js +19 -8
- package/dist/src/graph-ui/index.html +1 -1
- package/dist/src/graphs.d.ts +17 -1
- package/dist/src/graphs.js +51 -5
- package/dist/src/grok-provider.js +17 -14
- package/dist/src/hardened-runtime.js +7 -4
- 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-metadata.js +3 -7
- 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 +13 -1
- package/dist/src/model-tiers.js +28 -4
- 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.js +42 -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 +3 -9
- package/dist/src/providers.js +181 -146
- 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 +82 -66
- package/dist/src/pull-requests.js +266 -276
- 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 +147 -56
- 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 +85 -18
- 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 +18 -1
- package/dist/src/runtime.js +25 -7
- package/dist/src/session-summary.d.ts +8 -0
- package/dist/src/session-summary.js +34 -0
- package/dist/src/sessions.d.ts +8 -0
- package/dist/src/sessions.js +12 -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/graph-manager/SKILL.md +2 -2
- package/dist/src/skills/bundled/graph-manager/patterns.md +13 -19
- package/dist/src/skills/bundled/provenance.json +2 -2
- 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 +20 -4
- package/dist/src/task-checkout.js +78 -8
- 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/thinking-level-detect.d.ts +3 -1
- package/dist/src/thinking-level-detect.js +8 -3
- package/dist/src/thinking-levels.d.ts +1 -1
- package/dist/src/thinking-levels.js +11 -4
- package/dist/src/timers.d.ts +2 -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/tools.js +67 -22
- package/dist/src/transcript.js +2 -1
- package/dist/src/types.d.ts +14 -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
package/dist/src/membership.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
1
4
|
import { DEFAULT_AGENT_GRAPH } from './default-graph.js';
|
|
2
5
|
import { DEFAULT_HARNESS, builtInGraph, GraphDeletedError, isDeletedGraph, loadGraph, validateGraph } from './graphs.js';
|
|
3
6
|
import { AUTH_REFRESH_BUDGET_MS, AuthError, getAccessToken, getAuthConfiguration, getAuthStatus } from './auth/index.js';
|
|
@@ -7,6 +10,7 @@ import { configDirectory, loadConfig } from './config.js';
|
|
|
7
10
|
import { analyticsPlanFromMembership, resolveAnalyticsConfig } from './analytics.js';
|
|
8
11
|
import { recordConfirmedPlan } from './telemetry/state.js';
|
|
9
12
|
import { telemetryDirectory } from './telemetry/identity.js';
|
|
13
|
+
import { telemetryLease, withTelemetryAdmission } from './telemetry/permission.js';
|
|
10
14
|
import { bindPortableGraphProviders } from './graph-provider-portability.js';
|
|
11
15
|
import { loadFreeTierGraph, notePremiumGraphAccount } from './graph-quota.js';
|
|
12
16
|
export const SOFTWARE_ENGINEER_HARNESS = {
|
|
@@ -28,7 +32,7 @@ function retiredAndorraHarness() {
|
|
|
28
32
|
export function currentGraphSelection(id) {
|
|
29
33
|
return id === RETIRED_ANDORRA_SELECTION ? 'default' : id;
|
|
30
34
|
}
|
|
31
|
-
export const MEMBERSHIP_TIERS = ['free', 'legacy', 'paid'];
|
|
35
|
+
export const MEMBERSHIP_TIERS = ['free', 'legacy', 'paid', 'plus', 'ultra', 'max'];
|
|
32
36
|
export function windowFields(result) {
|
|
33
37
|
const positive = (value) => Number.isSafeInteger(value) && value > 0;
|
|
34
38
|
const fields = {};
|
|
@@ -46,13 +50,17 @@ export function windowFields(result) {
|
|
|
46
50
|
return fields;
|
|
47
51
|
}
|
|
48
52
|
export function membershipPlanLabel(tier, paid) {
|
|
49
|
-
if (tier === 'paid')
|
|
50
|
-
return '
|
|
53
|
+
if (tier === 'paid' || tier === 'plus')
|
|
54
|
+
return 'Plus';
|
|
55
|
+
if (tier === 'ultra')
|
|
56
|
+
return 'Ultra';
|
|
57
|
+
if (tier === 'max')
|
|
58
|
+
return 'Max';
|
|
51
59
|
if (tier === 'legacy')
|
|
52
60
|
return 'Legacy';
|
|
53
61
|
if (tier === 'free')
|
|
54
62
|
return paid ? 'Legacy' : 'Free';
|
|
55
|
-
return paid ? '
|
|
63
|
+
return paid ? 'Plus' : 'Free';
|
|
56
64
|
}
|
|
57
65
|
function transportFailureReason(error) {
|
|
58
66
|
let current = error;
|
|
@@ -97,15 +105,18 @@ export function safeAccountEmail(value) {
|
|
|
97
105
|
export { PaidMembershipRequiredError } from './membership-errors.js';
|
|
98
106
|
import { PaidMembershipRequiredError } from './membership-errors.js';
|
|
99
107
|
const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']);
|
|
100
|
-
async function recordPlanConfirmation(answer, home) {
|
|
108
|
+
async function recordPlanConfirmation(answer, home, regional = false) {
|
|
101
109
|
const directory = home ?? configDirectory();
|
|
102
110
|
const observedAt = new Date().toISOString();
|
|
103
|
-
const preference = resolveAnalyticsConfig(await loadConfig(directory)).enabled ? 'on' : 'off';
|
|
111
|
+
const preference = regional || resolveAnalyticsConfig(await loadConfig(directory)).enabled ? 'on' : 'off';
|
|
104
112
|
await recordConfirmedPlan({ directory: telemetryDirectory(directory), subject: answer.subject, tier: answer.tier, preference, observedAt });
|
|
105
113
|
}
|
|
106
114
|
export function createMembershipClient(deps) {
|
|
107
115
|
return async (signal, home) => {
|
|
108
116
|
signal?.throwIfAborted();
|
|
117
|
+
const privacy = { home: home ?? configDirectory(), signals: deps.telemetrySignals };
|
|
118
|
+
// Permission must exist at request START as well as completion: a delayed pre-Yes /me is not backfilled.
|
|
119
|
+
const lease = await telemetryLease(privacy);
|
|
109
120
|
const tokenBudget = signal ? AbortSignal.any([signal, AbortSignal.timeout(AUTH_REFRESH_BUDGET_MS)]) : AbortSignal.timeout(AUTH_REFRESH_BUDGET_MS);
|
|
110
121
|
let bounded;
|
|
111
122
|
try {
|
|
@@ -160,7 +171,14 @@ export function createMembershipClient(deps) {
|
|
|
160
171
|
const tier = typeof result.tier === 'string' && MEMBERSHIP_TIERS.includes(result.tier)
|
|
161
172
|
? result.tier : undefined;
|
|
162
173
|
const observedAt = new Date().toISOString();
|
|
163
|
-
|
|
174
|
+
if (lease)
|
|
175
|
+
await withTelemetryAdmission(privacy, async (admission) => {
|
|
176
|
+
const confirmation = { subject: result.subject, tier: analyticsPlanFromMembership(tier, result.paid), observedAt };
|
|
177
|
+
if (deps.recordPlan)
|
|
178
|
+
await deps.recordPlan(confirmation, home);
|
|
179
|
+
else
|
|
180
|
+
await recordPlanConfirmation(confirmation, home, admission.status.permissionRequired);
|
|
181
|
+
}, lease).catch(() => { });
|
|
164
182
|
const served = Date.parse(response.headers?.get?.('date') ?? '');
|
|
165
183
|
await (deps.storePass ?? ((pass, subject, directory, serverTime, plan) => storePlanPass(pass, subject, directory, { serverTime, plan })))(result.pass, result.subject, home ?? configDirectory(), Number.isFinite(served) ? served : undefined, { paid: result.paid, ...(tier ? { tier } : {}) }).catch(() => { });
|
|
166
184
|
const windowed = windowFields(result);
|
|
@@ -172,6 +190,8 @@ export function createMembershipClient(deps) {
|
|
|
172
190
|
return { paid: result.paid, subject: result.subject, ...(email ? { email } : {}), ...(tier ? { tier } : {}), ...(result.dailyDecisionLimit === undefined ? {} : { dailyDecisionLimit: result.dailyDecisionLimit }),
|
|
173
191
|
...(validUsage ? { dailyDecisionUsed: result.dailyDecisionUsed, dailyDecisionResetsAt: reset } : {}),
|
|
174
192
|
...(lifetime === undefined ? {} : { decisionsSinceRollout: lifetime }),
|
|
193
|
+
...(result.jevSavingsEnabled === true && typeof result.jevSavingsGeneration === 'string' && /^[a-f0-9]{32}$/.test(result.jevSavingsGeneration)
|
|
194
|
+
? { jevSavingsGeneration: result.jevSavingsGeneration } : {}),
|
|
175
195
|
...windowed,
|
|
176
196
|
...(unlimited === undefined ? {} : { unlimited }),
|
|
177
197
|
...(billing === undefined ? {} : { billingUrl: billing }) };
|
|
@@ -212,6 +232,118 @@ export const getGraphMembership = createGraphMembership({
|
|
|
212
232
|
membership: (signal, home) => getMembership(signal, home),
|
|
213
233
|
subject: async () => (await getAuthStatus()).subject,
|
|
214
234
|
});
|
|
235
|
+
/** How often the signed-out JEV switch is read at most: once every four hours, machine wide. */
|
|
236
|
+
const ANONYMOUS_JEV_TTL_MS = 4 * 60 * 60 * 1000;
|
|
237
|
+
/** How long one answer stays in this process's memory, so the stored file is not read per call. */
|
|
238
|
+
const ANONYMOUS_JEV_MEMORY_TTL_MS = 60_000;
|
|
239
|
+
let anonymousJevCache = { until: 0, allowed: false };
|
|
240
|
+
/** Clears the in-memory switch answer; the stored answer on disk stands. For tests. */
|
|
241
|
+
export function resetAnonymousJevCache() {
|
|
242
|
+
anonymousJevCache = { until: 0, allowed: false };
|
|
243
|
+
}
|
|
244
|
+
const anonymousJevFile = (directory) => join(directory, 'anonymous-jev.json');
|
|
245
|
+
/** The switch answer a previous read left, or undefined when there is none within its four hours. */
|
|
246
|
+
async function readStoredAnonymousJev(home) {
|
|
247
|
+
try {
|
|
248
|
+
const raw = await readFile(anonymousJevFile(home ?? configDirectory()), 'utf8');
|
|
249
|
+
const value = JSON.parse(raw);
|
|
250
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
251
|
+
return undefined;
|
|
252
|
+
const { checkedAt, allowed } = value;
|
|
253
|
+
if (typeof checkedAt !== 'number' || !Number.isFinite(checkedAt) || checkedAt > Date.now()
|
|
254
|
+
|| Date.now() - checkedAt > ANONYMOUS_JEV_TTL_MS)
|
|
255
|
+
return undefined;
|
|
256
|
+
return allowed === true;
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
return undefined;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
async function storeAnonymousJev(allowed, home) {
|
|
263
|
+
try {
|
|
264
|
+
const directory = home ?? configDirectory();
|
|
265
|
+
const file = anonymousJevFile(directory);
|
|
266
|
+
await mkdir(directory, { recursive: true });
|
|
267
|
+
const pending = `${file}.${randomUUID()}.pending`;
|
|
268
|
+
await writeFile(pending, JSON.stringify({ checkedAt: Date.now(), allowed }), { mode: 0o600, flag: 'wx' });
|
|
269
|
+
await rename(pending, file);
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
// A switch answer that cannot be stored is no loss: the next ask reads the service again.
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Whether the service currently serves Jev to users who are not signed in.
|
|
277
|
+
*
|
|
278
|
+
* An operator switch (`config#jev-guest` in the account service) is served on an unauthenticated
|
|
279
|
+
* route, so the answer carries no account and is safe to ask before any sign-in. The answer is kept
|
|
280
|
+
* for four hours on disk in the config directory — shared by every process on the machine — so the
|
|
281
|
+
* switch is asked over the network at most once per machine per four hours, never once per call;
|
|
282
|
+
* this process also keeps the answer in memory for a minute so it does not re-read the file. A
|
|
283
|
+
* read, parse or shape failure reads as off and is retried after a minute, without extending the
|
|
284
|
+
* stored answer: a network outage must not cost a user four hours.
|
|
285
|
+
*/
|
|
286
|
+
export async function anonymousJevAllowed(signal, home) {
|
|
287
|
+
if (Date.now() < anonymousJevCache.until)
|
|
288
|
+
return anonymousJevCache.allowed;
|
|
289
|
+
const stored = await readStoredAnonymousJev(home);
|
|
290
|
+
if (stored !== undefined) {
|
|
291
|
+
anonymousJevCache = { until: Date.now() + ANONYMOUS_JEV_MEMORY_TTL_MS, allowed: stored };
|
|
292
|
+
return stored;
|
|
293
|
+
}
|
|
294
|
+
try {
|
|
295
|
+
const base = new URL(getAuthConfiguration().apiBaseUrl);
|
|
296
|
+
if ((base.protocol !== 'https:' && !(base.protocol === 'http:' && LOOPBACK_HOSTS.has(base.hostname)))
|
|
297
|
+
|| base.username || base.password || base.search || base.hash)
|
|
298
|
+
throw new Error('public-config');
|
|
299
|
+
const bounded = signal ? AbortSignal.any([signal, AbortSignal.timeout(5000)]) : AbortSignal.timeout(5000);
|
|
300
|
+
const response = await fetch(new URL('./public-config', `${base.href.replace(/\/+$/, '')}/`), { signal: bounded, redirect: 'error' });
|
|
301
|
+
const reader = response.body?.getReader();
|
|
302
|
+
if (!response.ok || !reader) {
|
|
303
|
+
await response.body?.cancel().catch(() => { });
|
|
304
|
+
throw new Error('public-config');
|
|
305
|
+
}
|
|
306
|
+
const chunks = [];
|
|
307
|
+
let size = 0;
|
|
308
|
+
try {
|
|
309
|
+
for (;;) {
|
|
310
|
+
const { done, value } = await reader.read();
|
|
311
|
+
if (done)
|
|
312
|
+
break;
|
|
313
|
+
size += value.byteLength;
|
|
314
|
+
if (size > 16_384)
|
|
315
|
+
throw new Error('public-config');
|
|
316
|
+
chunks.push(value);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
finally {
|
|
320
|
+
await reader.cancel().catch(() => { });
|
|
321
|
+
reader.releaseLock();
|
|
322
|
+
}
|
|
323
|
+
const value = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
324
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)
|
|
325
|
+
|| typeof value.anonymousJev !== 'boolean')
|
|
326
|
+
throw new Error('public-config');
|
|
327
|
+
const allowed = value.anonymousJev === true;
|
|
328
|
+
anonymousJevCache = { until: Date.now() + ANONYMOUS_JEV_MEMORY_TTL_MS, allowed };
|
|
329
|
+
await storeAnonymousJev(allowed, home);
|
|
330
|
+
return allowed;
|
|
331
|
+
}
|
|
332
|
+
catch {
|
|
333
|
+
anonymousJevCache = { until: Date.now() + ANONYMOUS_JEV_MEMORY_TTL_MS, allowed: false };
|
|
334
|
+
return false;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* The membership a decision policy should see. While the service allows signed-out Jev, a signed-out
|
|
339
|
+
* answer is marked `anonymousJev`, which turns the hosted provider back on without an account: no
|
|
340
|
+
* plan, no limits, no savings sync. A signed-in answer is returned unchanged.
|
|
341
|
+
*/
|
|
342
|
+
export async function withAnonymousJev(membership, signal, home) {
|
|
343
|
+
if (membership.subject || membership.anonymousJev)
|
|
344
|
+
return membership;
|
|
345
|
+
return (await anonymousJevAllowed(signal, home)) ? { ...membership, anonymousJev: true } : membership;
|
|
346
|
+
}
|
|
215
347
|
export async function requirePaidMembership(signal) {
|
|
216
348
|
const access = await getMembership(signal);
|
|
217
349
|
if (!access.paid)
|
|
@@ -6,7 +6,7 @@ import { readCodexCatalog } from './codex-provider.js';
|
|
|
6
6
|
import { codexConnectFor } from './codex-rpc.js';
|
|
7
7
|
import { readClaudeCatalog } from './claude-provider.js';
|
|
8
8
|
import { knownClaudeContextWindow } from './model-context-windows.js';
|
|
9
|
-
import {
|
|
9
|
+
import { GOOGLE_LEGACY_MESSAGE } from './google-provider.js';
|
|
10
10
|
import { readGrokCatalog } from './grok-provider.js';
|
|
11
11
|
import { readOpenCodeCatalog } from './opencode-cli-provider.js';
|
|
12
12
|
import { ANDORRA_SIGN_IN_MESSAGE, ANDORRA_UNAVAILABLE_MESSAGE } from './andorra/endpoint.js';
|
|
@@ -136,12 +136,8 @@ async function listModelMetadata(provider, signal) {
|
|
|
136
136
|
throw new Error('Sign in to Grok on this machine before listing its models.');
|
|
137
137
|
return catalog.models.map(id => ({ id }));
|
|
138
138
|
}
|
|
139
|
-
if (provider.type === 'google')
|
|
140
|
-
|
|
141
|
-
if (!catalog.signedIn)
|
|
142
|
-
throw new Error('Sign in with Google in the Antigravity CLI on this machine before listing its models.');
|
|
143
|
-
return catalog.models.map(id => ({ id }));
|
|
144
|
-
}
|
|
139
|
+
if (provider.type === 'google')
|
|
140
|
+
throw new Error(GOOGLE_LEGACY_MESSAGE);
|
|
145
141
|
if (provider.type === 'opencode')
|
|
146
142
|
return (await readOpenCodeCatalog(signal)).models.map(model => ({ id: model.id, ...(model.contextWindow ? { contextWindow: model.contextWindow } : {}) }));
|
|
147
143
|
if (provider.type === 'opencode-go')
|
|
@@ -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,12 +27,16 @@ 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;
|
|
@@ -41,6 +45,14 @@ export interface TierDecision {
|
|
|
41
45
|
export declare const RISK_WORDS: RegExp;
|
|
42
46
|
export declare const MECHANICAL_WORDS: RegExp;
|
|
43
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;
|
|
44
56
|
export declare function classifyTier(task: string, hints: DecisionBatch | undefined): {
|
|
45
57
|
tier: ModelTier;
|
|
46
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';
|
|
2
|
+
import { DEFAULT_POOL_CLASS_SCORES, MODEL_TIERS, POOL_EFFORTS, poolScoreKey } from './efficiency.js';
|
|
3
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
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
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
|
};
|