@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/app-server.js
CHANGED
|
@@ -1,19 +1,26 @@
|
|
|
1
1
|
import { createInterface } from 'node:readline';
|
|
2
2
|
import { createRequire } from 'node:module';
|
|
3
3
|
import { readFileSync } from 'node:fs';
|
|
4
|
+
import { acceptLegal, legalStatus, requireLegalAcceptance, legalMethodRequiresAcceptance, LegalAcceptanceRequired, LEGAL_ACCEPTANCE_REQUIRED } from './legal/gate.js';
|
|
5
|
+
import { legalDocument } from './legal/documents.js';
|
|
4
6
|
import { randomBytes, randomUUID } from 'node:crypto';
|
|
5
7
|
import { bootMark } from './boot-trace.js';
|
|
6
8
|
import { ModelHealthCache } from './model-health-cache.js';
|
|
7
|
-
import { mkdir, readFile, realpath, rm, stat
|
|
9
|
+
import { mkdir, readFile, realpath, rm, stat } from 'node:fs/promises';
|
|
8
10
|
import { homedir } from 'node:os';
|
|
9
11
|
import { fileURLToPath } from 'node:url';
|
|
10
12
|
import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
|
|
11
|
-
import { changeConfigFile, configDirectory, ConfigConflictError, readGitHubAgentWrites, readGitHubAppEventsEnabled, readGitHubAppReviewNewPullRequests, readGitHubAppReviewsEnabled, readGitHubAppTriggersEnabled, GITHUB_AGENT_WRITES, modelRelayAllowedFor, withModelRelayEntry, isProjectExtensionOverride, loadConfig, reconcileSubagentPair, resolveCodeIntelConfig, resolveConfiguredLimits, validateMcpServer, checkSearxngUrl, validateWebSearchConfig, WEB_SEARCH_FIELDS, WEB_SEARCH_KEY_FIELDS, WEB_SEARCH_PROVIDERS } from './config.js';
|
|
13
|
+
import { changeFunctionalConfigFile as changeConfigFile, changeConfigFile as changeLegacyConfigFile, configDirectory, ConfigConflictError, readGitHubAgentWrites, readGitHubAppEventsEnabled, readGitHubAppReviewNewPullRequests, readGitHubAppReviewsEnabled, readGitHubAppTriggersEnabled, GITHUB_AGENT_WRITES, modelRelayAllowedFor, withModelRelayEntry, isProjectExtensionOverride, loadFunctionalConfig as loadConfig, reconcileSubagentPair, resolveCodeIntelConfig, resolveConfiguredLimits, validateMcpServer, checkSearxngUrl, validateWebSearchConfig, WEB_SEARCH_FIELDS, WEB_SEARCH_KEY_FIELDS, WEB_SEARCH_PROVIDERS } from './config.js';
|
|
14
|
+
import { AppServerTelemetry, readTelemetryRunRecord } from './app-server/telemetry.js';
|
|
15
|
+
import { TELEMETRY_CONSENT_CAPABILITY } from './app-server/telemetry-protocol.js';
|
|
16
|
+
import { LEGAL_ACCEPTANCE_CAPABILITY, legalRequestRequiresAcceptance } from './app-server/legal-protocol.js';
|
|
17
|
+
import { TelemetryPrivacyError, telemetryLeaseSnapshot, sameTelemetryLease, withTelemetryAdmission } from './telemetry/permission.js';
|
|
12
18
|
import { isUnlimitedAlias } from './limits.js';
|
|
13
|
-
import { isPermissionMode, permissionMode as livePermissionMode, workspacePermissionKey } from './permissions.js';
|
|
19
|
+
import { cloudPermissionMode, isPermissionMode, permissionMode as livePermissionMode, workspacePermissionKey } from './permissions.js';
|
|
14
20
|
import { RunControl } from './run-control.js';
|
|
15
21
|
import { allocateCodexAccountSlots, createAdapter, findProviderById, isSignInProviderType, providerLabel, providerSecrets, resolveProviderApiKey, REASONING_EFFORTS, supportsReasoningEffort } from './providers.js';
|
|
16
22
|
import { ModelRelayBroker, RELAY_FAILURE_CODE } from './model-relay/remote.js';
|
|
23
|
+
import { readProviderTurnTiming } from './provider-turn-deadline.js';
|
|
17
24
|
import { LocalModelRelay, relayedModelIds } from './model-relay/local.js';
|
|
18
25
|
import { ModelRelayRunStore } from './model-relay/runs.js';
|
|
19
26
|
import { MODEL_RELAY_CONNECTION_PREFIX } from './model-relay/wire.js';
|
|
@@ -21,24 +28,27 @@ import { droppedCodexSlots, removeCodexAccount } from './codex-auth.js';
|
|
|
21
28
|
import { testProviderConnection } from './provider-connection.js';
|
|
22
29
|
import { CodexAccountAuth } from './codex-browser-auth.js';
|
|
23
30
|
import { AnthropicConsoleAuth, droppedAnthropicAccounts } from './anthropic-console-auth.js';
|
|
24
|
-
import { claudeSignIn,
|
|
31
|
+
import { claudeSignIn, grokSignIn, OpenCodeSignIn } from './managed-sign-in.js';
|
|
25
32
|
import { applySignInImports, detectSignIns, isDetectableSignInType } from './sign-in-detection.js';
|
|
26
33
|
import { OPENCODE_BASE_URL, sharedOpenCodeServer } from './opencode-cli-provider.js';
|
|
27
|
-
import { GOOGLE_BASE_URL } from './google-provider.js';
|
|
34
|
+
import { GOOGLE_BASE_URL, GOOGLE_LEGACY_MESSAGE } from './google-provider.js';
|
|
35
|
+
import { AntigravitySession } from './antigravity-acp.js';
|
|
28
36
|
import { GROK_BASE_URL } from './grok-provider.js';
|
|
29
37
|
import { anthropicAccountHome } from './anthropic-credentials.js';
|
|
30
38
|
import { codexAccountHome } from './codex-rpc.js';
|
|
31
39
|
import { configuredModelSnapshot, discoverModelMetadata, resolveModelContext, resolveModelContextWindows } from './model-metadata.js';
|
|
32
40
|
import { liveModelTarget } from './live-model.js';
|
|
41
|
+
import { decideEffort } from './effort-routing.js';
|
|
33
42
|
import { graphLeavesNodesToSession, graphMcpServers, isDeletedGraph, isNodeReasoningEffort, isReservedGraphId, listGraphs, loadGraph, maxNodeVisitsOf, withoutDeletedGraphs } from './graphs.js';
|
|
34
43
|
import { exportAgentDefinition, readAgentDefinition } from './agent-definitions.js';
|
|
35
44
|
import { blockingHealthFailures, checkGraphModelHealth, formatGraphHealthFailure, resumeModelNodes } from './graph-health.js';
|
|
36
45
|
import { bindPortableGraphProviders, GraphProviderUnavailableError } from './graph-provider-portability.js';
|
|
37
46
|
import { applyModelOverride, applyNodeModelOverrides } from './model-override.js';
|
|
38
|
-
import { autoLevels, enabledLevels, nearestEnabled, withDetectedLevels, withDisabledLevels } from './thinking-levels.js';
|
|
47
|
+
import { autoLevels, enabledLevels, nearestEnabled, withDetectedLevels, withDisabledLevels, validateThinkingLevels } from './thinking-levels.js';
|
|
39
48
|
import { detectProviderLevels } from './thinking-level-detect.js';
|
|
49
|
+
import { currentReasoningProbeSubject, flushReasoningProbes, queueReasoningProbe, readReasoningProbe } from './reasoning-probe-cloud.js';
|
|
40
50
|
import { freeTierGraphViolation, notePremiumGraphAccount, readGraphQuota } from './graph-quota.js';
|
|
41
|
-
import { RETIRED_ANDORRA_SELECTION, SOFTWARE_ENGINEER_HARNESS, createMembershipClient, currentGraphSelection, getGraphMembership, getMembership, loadAccessibleGraph, membershipPlanLabel, relayedGraph } from './membership.js';
|
|
51
|
+
import { RETIRED_ANDORRA_SELECTION, SOFTWARE_ENGINEER_HARNESS, createMembershipClient, currentGraphSelection, getGraphMembership, getMembership, loadAccessibleGraph, membershipPlanLabel, relayedGraph, withAnonymousJev } from './membership.js';
|
|
42
52
|
import { loadProfile, saveProfile, ProfileAccountError, ProfileTextError } from './profile.js';
|
|
43
53
|
import { hostedDecisionPolicy } from './decision/hostedPolicy.js';
|
|
44
54
|
import { createAccountPresentationReader, publishableMembership } from './account-presentation.js';
|
|
@@ -47,16 +57,16 @@ import { configuredGraphSelection, currentGraphSubject, identityStillHolds } fro
|
|
|
47
57
|
import { announceGraphVisibilityChange, graphVisibilityFor, importGraphVisibility, onGraphVisibilityChange, relinkGraphVisibility, setGraphVisibility } from './graph-visibility.js';
|
|
48
58
|
import { graphStorageAccess } from './graph-account.js';
|
|
49
59
|
import { GraphAccessSync } from './graph-sync.js';
|
|
50
|
-
import { checkoutState, discardPreparedWorktree, forgetPrepared, inPlaceCheckout, inspectWorktreeRemoval, locateTaskWorktree, prepareTaskWorktree, recreateTaskWorktree, removeTaskWorktree, takePrepared, taskStartPoints, TaskCheckoutError, worktreeInstructions } from './task-checkout.js';
|
|
60
|
+
import { checkoutState, discardPreparedWorktree, forgetPrepared, inPlaceCheckout, inspectWorktreeRemoval, isAutoTaskBranch, locateTaskWorktree, prepareTaskWorktree, recreateTaskWorktree, removeTaskWorktree, renameTaskBranch, revertTaskBranchRename, takePrepared, taskStartPoints, TaskCheckoutError, worktreeInstructions } from './task-checkout.js';
|
|
51
61
|
import { cleanRecorded, COMMAND_LIMIT, outputTail, readRevision, resolveEvidence } from './evidence.js';
|
|
52
62
|
import { reviewAfterTurn, canExtendLineage, displayHistory, hiddenSession, lineagePoints, lineageThrough, SessionStore, projectIdentity, removeSessionSnapshot, savedSessionFields, sessionName, validSavedSession } from './sessions.js';
|
|
53
63
|
import { folderChangeBusy, folderChangeHeld, reserveFolderChange } from './project-reservation.js';
|
|
54
64
|
import { writePendingAgentInteraction, removePendingAgentInteraction } from './session-monitor.js';
|
|
55
|
-
import { summarizeSessionPrompt, titleRequestSupported } from './session-summary.js';
|
|
65
|
+
import { summarizeSessionPrompt, summarizeTaskBranch, titleRequestSupported } from './session-summary.js';
|
|
56
66
|
import { createTools } from './tools.js';
|
|
57
67
|
import { TimerRegistry, WAKE_RETRY_MS } from './timers.js';
|
|
58
68
|
import { checksRollup, classifyGhError, classifyWriteError, PullRequestReader, runAsAccount, sameChecksRollup, PullRequestRefusal } from './pull-request-details.js';
|
|
59
|
-
import { commitBody, commitTitle, deleteBranch, dequeue,
|
|
69
|
+
import { commitBody, commitTitle, deleteBranch, dequeue, enqueue, headCommit, mergeMethod, mergePullRequest, setReadyForReview, updateBranch, updateMethod } from './pull-request-merge.js';
|
|
60
70
|
import { accountToken, branchName, createFromFolder, githubHttpsUrl, githubRepositoryOf, gitIn, PullRequestCreateBlocked, pullRequestTitle, readCreateDraft, repositoryName, tokenCredentials } from './pull-request-create.js';
|
|
61
71
|
import { addComment, applySuggestionText, commitFile, coAuthorTrailer, deleteComment, editComment, reactionContent, readFileAt, setReaction, suggestionOf, uniformLineEndings } from './pull-request-conversation.js';
|
|
62
72
|
import { changeAssignees, changeLabels, currentText, editBody, editTitle, nodeIds, setOpen, updateText } from './pull-request-edit.js';
|
|
@@ -64,12 +74,13 @@ import { actionsJobOf, fixChecksPrompt, jobId } from './pull-request-logs.js';
|
|
|
64
74
|
import { issueNamedIn, readRepositoryIssues, readReviewRequests } from './github-inbox.js';
|
|
65
75
|
import { changeReviewers, commentBody, draftComments, failedRunIds, githubLogin, nodeId, replyToThread, rerunFailedJobs, reviewerEntries, reviewerLogins, reviewEvent, reviewPath, runIds, setFileViewed, setThreadResolved, submitReview, teamSlugs, } from './pull-request-review.js';
|
|
66
76
|
import { chatReviewLoopActive, parseReviewModel, reviewLoopActive, reviewLoopSettings, REVIEW_SETTING_KEYS } from './pull-requests.js';
|
|
67
|
-
import {
|
|
77
|
+
import { isFinishedPullRequest, withChecks, newPullRequest, parsePullRequestUrl, PullRequestCreateDetector, pullRequestNeedsWatch, pullRequestSettings, PullRequestWatcher, listPullRequests, readPullRequest, removePullRequest, runGh, applyPullRequestSettingsAsReadableAccount, codexReviewsRepository, ghFor, newReviewComments, noAccountMessage, readReviewSignals, REVIEW_BUMP_COMMENT, REVIEW_BUMP_DELAY_MS, REVIEW_SIGNAL_INTERVAL_MS, readPullRequestAsAnyAccount, withPullRequest, withSupersededPullRequest, writePullRequest } from './pull-requests.js';
|
|
68
78
|
import { AutomationStore } from './automations.js';
|
|
69
79
|
import { executeAutomation } from './automation-runner.js';
|
|
70
80
|
import { automationService, automationServiceRunning, reconcileAutomationService } from './automation-service.js';
|
|
71
81
|
import { runGraph, stopReasonPhrase, timerReminderText, wakeMessageText } from './runtime.js';
|
|
72
|
-
import { configuredSurface,
|
|
82
|
+
import { configuredSurface, beginTelemetryRun, runTelemetryMetadata, drainTelemetry, graphShape, reportGitHubWatch, reportInstallationObserved, reportInterruptedRuns, reportRunFinished, reportRunStarted, reportSessionStarted } from './telemetry/surface.js';
|
|
83
|
+
import { desktopInstallationReceipt } from './telemetry/version.js';
|
|
73
84
|
import { telemetryGate } from './telemetry/gate.js';
|
|
74
85
|
import { accountApiTarget, defaultGitHubAppClient, GitHubAppError } from './github-app/client.js';
|
|
75
86
|
import { GITHUB_ACCOUNT, GITHUB_REPO } from './github-names.js';
|
|
@@ -79,14 +90,15 @@ import { applyReviewSettings, coverageAllowsReview, coverageRefusal, ReviewLoopC
|
|
|
79
90
|
import { newRequestId as newReviewLoopId } from './github-app/agent-writes.js';
|
|
80
91
|
import { asksBot, performAgentWrite } from './github-app/agent-writes.js';
|
|
81
92
|
import { createReviewNodeService, endGraphLoops } from './github-app/review-node.js';
|
|
82
|
-
import { analyticsGenerationFor, resolveAnalyticsConfig } from './analytics.js';
|
|
93
|
+
import { analyticsGenerationFor, resolveAnalyticsConfig, validateAnalyticsConfig } from './analytics.js';
|
|
83
94
|
import { telemetryDirectory } from './telemetry/identity.js';
|
|
84
95
|
import { recordPreference } from './telemetry/state.js';
|
|
85
|
-
import { createRunTelemetry, recordModelUse } from './telemetry/capture.js';
|
|
96
|
+
import { createRunTelemetry, hasRunTelemetry, mergeRunTelemetry, recordModelUse } from './telemetry/capture.js';
|
|
86
97
|
import { pricingFor } from './model-tiers.js';
|
|
87
98
|
import { purgeOutbox } from './telemetry/outbox.js';
|
|
88
|
-
import { acquireSessionMutationLock, checkpointFailure, claimProcessWorkspace, createCheckpointFailureTracker, createRunJournalWriter, claimRunResume, clearOpenRunClaim, clearWakeClaim, clearWakeClaims, isPidAlive, journalWriteFailed, readRunCheckpoints, releaseProcessWorkspace, releaseRunResumeClaim, removeRunCheckpoint, RUNNING_TURN_SUMMARY, reconcileInterruptedRuns, runIsOpen, runRecordPath, runRecordsDirectory, sessionHasArmedWake, sessionHasOpenRun, sessionsWithOpenRunClaims, SessionMutationLockHeldError, writeOpenRunRecord, writeRunCheckpoint, writeStudioRunSummary, writeWakeClaim } from './run-records.js';
|
|
99
|
+
import { acquireSessionMutationLock, checkpointFailure, claimProcessWorkspace, createCheckpointFailureTracker, createRunJournalWriter, claimRunResume, clearOpenRunClaim, clearWakeClaim, clearWakeClaims, isPidAlive, journalWriteFailed, readRunCheckpoints, releaseProcessWorkspace, releaseRunResumeClaim, removeRunCheckpoint, RUNNING_TURN_SUMMARY, reconcileInterruptedRuns, runIsOpen, runRecordPath, runRecordsDirectory, sessionHasArmedWake, sessionHasOpenRun, sessionsWithOpenRunClaims, SessionMutationLockHeldError, writeFinalRunRecord, functionalRunRecord, writeOpenRunRecord, writeRunCheckpoint, writeStudioRunSummary, writeWakeClaim } from './run-records.js';
|
|
89
100
|
import { ArtifactStore } from './artifacts.js';
|
|
101
|
+
import { artifactUnavailable, parseArtifactReference, readArtifactPreview } from './app-server/artifact.js';
|
|
90
102
|
import { coverUnsavedToolCalls, mergeRunProgress, replayRunJournal, toolBoundaryOpen } from './run-progress.js';
|
|
91
103
|
import { compactHistory, compactedContextEstimate } from './commands.js';
|
|
92
104
|
import { readFavicon } from './favicons.js';
|
|
@@ -106,7 +118,7 @@ import { TodoStore } from './todos.js';
|
|
|
106
118
|
import { LocalToolMemory } from './memory/LocalToolMemory.js';
|
|
107
119
|
import { ProjectMemory } from './memory/ProjectMemory.js';
|
|
108
120
|
import { CodeIntelligenceManager } from './code-intelligence/CodeIntelligenceManager.js';
|
|
109
|
-
import { startGraphServer } from './graph-server.js';
|
|
121
|
+
import { graphEditorParentOrigins, startGraphServer } from './graph-server.js';
|
|
110
122
|
import { createSessionTrajectory } from './trajectory.js';
|
|
111
123
|
import { readUsageAnalytics } from './usage-analytics.js';
|
|
112
124
|
import { TerminalFlow, TerminalManager } from './app-server/terminal.js';
|
|
@@ -132,8 +144,9 @@ import { AppServerError } from './app-server/error.js';
|
|
|
132
144
|
import { AUTH_DEPLOYMENT } from './auth/deployment.js';
|
|
133
145
|
import { AuthError } from './auth/types.js';
|
|
134
146
|
import { claimEnvironment, cloudDelete, cloudGet, cloudStart, cloudStop, ControlError, listEnvironments, removeEnvironment, renameEnvironment } from './bridge/control.js';
|
|
135
|
-
import { relayUrlFromEnvironment } from './bridge/host.js';
|
|
147
|
+
import { RESTARTING_MESSAGE, relayUrlFromEnvironment } from './bridge/host.js';
|
|
136
148
|
import { RelayClosedError, RelayLink } from './bridge/link.js';
|
|
149
|
+
import { CLOUD_BRIDGE_AUTO_UPDATE } from './bridge/protocol.js';
|
|
137
150
|
import { bothBridgeCommands, bridgeCommand } from './bridge/wording.js';
|
|
138
151
|
import { fallbackProviderId, hasAndorraEntry, virtualAndorraEntry } from './andorra/entry.js';
|
|
139
152
|
import { ANDORRA_CHANGED_MESSAGE, ANDORRA_UNAVAILABLE_MESSAGE } from './andorra/endpoint.js';
|
|
@@ -141,8 +154,16 @@ import { andorraAnnouncement } from './andorra/notices.js';
|
|
|
141
154
|
import { ANDORRA_REMOVE_FAILED, recordAndorraRemoved, removingAndorraEntry } from './andorra/state.js';
|
|
142
155
|
import { addAndorraEntry, saveAndorraAnswer } from './andorra/opt-in.js';
|
|
143
156
|
import { HostedMonitor } from './andorra/monitor.js';
|
|
157
|
+
import { createUsageReader, poolUsageReader } from './subscription-usage.js';
|
|
158
|
+
import { refreshPoolScores, scoreSubjects } from './pool-scores.js';
|
|
159
|
+
import { MAX_POOL_SCORES, validateEfficiencyConfig } from './efficiency.js';
|
|
160
|
+
import { adaptiveRoutingView, mergeAdaptiveRoutingSettings } from './app-server/adaptive-routing-settings.js';
|
|
144
161
|
import { watchRequests } from './andorra/request-watch.js';
|
|
145
162
|
const SELECTION_HEALTH_TIMEOUT_MS = 60_000;
|
|
163
|
+
/** Only this explicit capability refusal permanently closes a link as consent-unsupported. */
|
|
164
|
+
class RemoteConsentUnsupportedError extends AppServerError {
|
|
165
|
+
constructor() { super('remote', 'Telemetry permission unavailable: update the paired host and deliberately restart its older engines. Existing engines have not been stopped.'); }
|
|
166
|
+
}
|
|
146
167
|
const SESSION_HISTORY_TURNS = 6;
|
|
147
168
|
const MAX_TASK_CHARS = 100_000;
|
|
148
169
|
/** A note the desktop sends with a message for the agent only (`run.note`), such as the person's hand edits. */
|
|
@@ -225,8 +246,10 @@ const RELAY_ERROR_CODES = new Set(['invalid-request', 'unknown-method', 'invalid
|
|
|
225
246
|
const RELAY_DEADLINE_MS = 290_000;
|
|
226
247
|
const RELAY_LONG_METHODS = new Set(['browser.runtime.install']);
|
|
227
248
|
const RELAY_LONG_DEADLINE_MS = 1_260_000;
|
|
249
|
+
const CLOUD_BRIDGE_RETRY_MS = 1_000;
|
|
250
|
+
const CLOUD_BRIDGE_RETRY_LIMIT_MS = 60_000;
|
|
228
251
|
const MAX_RESUME_LINEAGE = 32;
|
|
229
|
-
const EDITABLE_CONFIG_KEYS = ['provider', 'providers', 'graph', 'graphSelections', 'jevEnabled', 'decisions', 'commandMemory', 'projectMemory', 'limits', 'workspacePermissions', 'projectExtensions', 'mcpServers', 'extensions', 'memory', 'codeIntel', 'externalSubagent', 'analytics', 'systemPromptOverride', 'autoArchiveDays', 'browser', 'webSearch'];
|
|
252
|
+
const EDITABLE_CONFIG_KEYS = ['provider', 'providers', 'graph', 'graphSelections', 'jevEnabled', 'decisions', 'commandMemory', 'projectMemory', 'limits', 'workspacePermissions', 'projectExtensions', 'mcpServers', 'extensions', 'memory', 'codeIntel', 'externalSubagent', 'analytics', 'systemPromptOverride', 'autoArchiveDays', 'browser', 'webSearch', 'adaptiveRouting'];
|
|
230
253
|
function message(error) { return error instanceof Error ? error.message : String(error); }
|
|
231
254
|
const MERGE_METHOD_WORD = { merge: 'A merge commit', squash: 'Squash and merge', rebase: 'Rebase and merge' };
|
|
232
255
|
const NEW_COMMITS = 'This pull request has new commits since you read it. Look at them before merging or updating it.';
|
|
@@ -286,7 +309,7 @@ function providerAuthView(view, includeUrl) {
|
|
|
286
309
|
return result;
|
|
287
310
|
}
|
|
288
311
|
const MANAGED_SIGN_IN_HOSTS = {
|
|
289
|
-
claude: ['claude.com', 'claude.ai', 'anthropic.com'], grok: ['x.ai', 'grok.com'],
|
|
312
|
+
claude: ['claude.com', 'claude.ai', 'anthropic.com'], grok: ['x.ai', 'grok.com'], opencode: undefined,
|
|
290
313
|
};
|
|
291
314
|
function managedAuthView(type, view, includeUrl) {
|
|
292
315
|
if (!['signedOut', 'starting', 'waiting', 'signedIn', 'cancelled', 'error'].includes(view.state))
|
|
@@ -353,6 +376,9 @@ function managedAuthView(type, view, includeUrl) {
|
|
|
353
376
|
const TITLE_RETRY_DELAYS_MS = [60_000, 180_000];
|
|
354
377
|
/** How often a retry may find its session busy and step back without spending one of the attempts above. */
|
|
355
378
|
const MAX_TITLE_RETRY_DEFERRALS = 10;
|
|
379
|
+
/** A sibling session whose lock is busy while its branch is renamed: retry this often at this spacing. */
|
|
380
|
+
const MAX_SIBLING_LOCK_TRIES = 10;
|
|
381
|
+
const SIBLING_LOCK_RETRY_MS = 1_000;
|
|
356
382
|
function profileSubject(params) {
|
|
357
383
|
const subject = params.subject;
|
|
358
384
|
if (subject === undefined)
|
|
@@ -449,7 +475,11 @@ function viewUrl(value) {
|
|
|
449
475
|
function permissionMode(value) {
|
|
450
476
|
if (!isPermissionMode(value))
|
|
451
477
|
throw new AppServerError('invalid-params', 'permissions must be read-only, plan, ask-for-approval, approve-for-me, or full-access');
|
|
452
|
-
return value;
|
|
478
|
+
return cloudPermissionMode() ?? value;
|
|
479
|
+
}
|
|
480
|
+
/** The mode a request names, if any. On a Cloud instance that is always full access, named or not. */
|
|
481
|
+
function requestedPermissionMode(value) {
|
|
482
|
+
return value === undefined ? cloudPermissionMode() : permissionMode(value);
|
|
453
483
|
}
|
|
454
484
|
function reasoningEffort(value) {
|
|
455
485
|
if (typeof value !== 'string' || !REASONING_EFFORTS.includes(value)) {
|
|
@@ -531,6 +561,7 @@ function configView(config, analytics) {
|
|
|
531
561
|
...(config.autoArchiveDays === undefined ? {} : { autoArchiveDays: config.autoArchiveDays }),
|
|
532
562
|
...(resolveCapsolverKey(config) ? { browser: browserConfigView(config) } : {}),
|
|
533
563
|
...webSearchConfigView(config),
|
|
564
|
+
adaptiveRouting: adaptiveRoutingView(config.efficiency?.adaptiveRouting),
|
|
534
565
|
};
|
|
535
566
|
}
|
|
536
567
|
function browserConfigView(config) {
|
|
@@ -662,7 +693,7 @@ export function mergeProviderSecrets(stored, incoming) {
|
|
|
662
693
|
provider.modelContextWindows = previousEntry.modelContextWindows;
|
|
663
694
|
}
|
|
664
695
|
// Thinking levels are set through their own requests, so a provider list saved by a client never drops them.
|
|
665
|
-
if (previousEntry?.thinkingLevels !== undefined &&
|
|
696
|
+
if (previousEntry?.thinkingLevels !== undefined && provider.type === previousEntry.type && provider.baseUrl === previousEntry.baseUrl)
|
|
666
697
|
provider.thinkingLevels = structuredClone(previousEntry.thinkingLevels);
|
|
667
698
|
// The engine keeps an Andorra entry's display names from the router; a client never sets them.
|
|
668
699
|
if (provider.type === 'andorra' && previousEntry?.type === 'andorra' && previousEntry.modelNames !== undefined)
|
|
@@ -739,10 +770,7 @@ function foldUsage(target, delta) {
|
|
|
739
770
|
target.cacheWrite = (target.cacheWrite ?? 0) + delta.cacheWrite;
|
|
740
771
|
}
|
|
741
772
|
const TIMER_DELIVERY_RETRY_MS = 1_000;
|
|
742
|
-
const
|
|
743
|
-
function pullRequestForClients(pullRequest) {
|
|
744
|
-
return pullRequest ? { ...pullRequest, autoArchive: false } : null;
|
|
745
|
-
}
|
|
773
|
+
const REVIEW_CONFIRM_RETRY_MS = 60_000;
|
|
746
774
|
/** How many commands a turn's evidence keeps a record of: the newest are the ones outcomes cite. */
|
|
747
775
|
const MAX_TURN_OBSERVATIONS = 200;
|
|
748
776
|
/** Notes when the agent edits files, so evidence can say a check was followed by edits. */
|
|
@@ -787,7 +815,9 @@ function sessionSummary(record) {
|
|
|
787
815
|
: undefined;
|
|
788
816
|
return {
|
|
789
817
|
id: record.id, name: record.name, workspace: record.workspace, updatedAt: record.updatedAt, turns: (record.history ?? []).length,
|
|
818
|
+
...(record.placeholder === undefined ? {} : { placeholder: record.placeholder }),
|
|
790
819
|
...(record.parentId === undefined ? {} : { parentId: record.parentId }),
|
|
820
|
+
...(record.handoffParentId === undefined ? {} : { handoffParentId: record.handoffParentId }),
|
|
791
821
|
...(record.projectId === undefined ? {} : { projectId: record.projectId }),
|
|
792
822
|
...(record.archived === undefined ? {} : { archived: record.archived }),
|
|
793
823
|
...(record.pinned === true ? { pinned: true } : {}),
|
|
@@ -818,11 +848,8 @@ function requestCompaction(state) {
|
|
|
818
848
|
}
|
|
819
849
|
/** The gh-backed PR settings and the Andorra review loop's, apart: the first change the PR on GitHub, the second never. */
|
|
820
850
|
function splitPullRequestSettings(settings) {
|
|
821
|
-
const gh = {};
|
|
851
|
+
const gh = settings.draft === undefined ? {} : { draft: settings.draft };
|
|
822
852
|
const review = {};
|
|
823
|
-
for (const key of ['autoFix', 'mergeWhenReady', 'draft'])
|
|
824
|
-
if (settings[key] !== undefined)
|
|
825
|
-
gh[key] = settings[key];
|
|
826
853
|
for (const key of REVIEW_SETTING_KEYS)
|
|
827
854
|
if (settings[key] !== undefined)
|
|
828
855
|
Object.assign(review, { [key]: settings[key] });
|
|
@@ -907,7 +934,7 @@ function readNodeModelOverrides(value) {
|
|
|
907
934
|
}
|
|
908
935
|
return read;
|
|
909
936
|
}
|
|
910
|
-
const RELAYED_PROVIDER_FIELDS = new Set(['id', 'model', 'models', 'modelContextWindows', 'reasoningEffort']);
|
|
937
|
+
const RELAYED_PROVIDER_FIELDS = new Set(['id', 'model', 'models', 'modelContextWindows', 'reasoningEffort', 'thinkingLevels']);
|
|
911
938
|
const MAX_RELAYED_PROVIDERS = 64;
|
|
912
939
|
const RELAYED_RESUME_NEEDS_DESKTOP = 'This task uses your computer\'s models. Resume it from Andorra Code on your computer.';
|
|
913
940
|
const RELAYED_GRAPH_NEEDS_DESKTOP = 'This task uses a graph from your computer. Resume it from Andorra Code on your computer.';
|
|
@@ -950,7 +977,7 @@ function readRelay(value, options = {}) {
|
|
|
950
977
|
throw new AppServerError('invalid-params', 'Each relayed provider must be an object.');
|
|
951
978
|
const source = entry;
|
|
952
979
|
if (Object.keys(source).some(key => !RELAYED_PROVIDER_FIELDS.has(key))) {
|
|
953
|
-
throw new AppServerError('invalid-params', 'A relayed provider carries only id, model, models, modelContextWindows and
|
|
980
|
+
throw new AppServerError('invalid-params', 'A relayed provider carries only id, model, models, modelContextWindows, reasoningEffort and thinkingLevels.');
|
|
954
981
|
}
|
|
955
982
|
if (typeof source.id !== 'string' || !/^[\w-]{1,128}$/.test(source.id))
|
|
956
983
|
throw new AppServerError('invalid-params', 'A relayed provider id must be up to 128 word characters and dashes.');
|
|
@@ -974,6 +1001,18 @@ function readRelay(value, options = {}) {
|
|
|
974
1001
|
}
|
|
975
1002
|
provider.modelContextWindows = Object.fromEntries(Object.entries(windows));
|
|
976
1003
|
}
|
|
1004
|
+
if (source.thinkingLevels !== undefined) {
|
|
1005
|
+
try {
|
|
1006
|
+
validateThinkingLevels(source.thinkingLevels, 'relayed');
|
|
1007
|
+
if (Object.keys(source.thinkingLevels).some(key => key !== provider.model && !provider.models?.includes(key))) {
|
|
1008
|
+
throw new Error('reasoning levels must belong to a declared model');
|
|
1009
|
+
}
|
|
1010
|
+
provider.thinkingLevels = source.thinkingLevels;
|
|
1011
|
+
}
|
|
1012
|
+
catch (error) {
|
|
1013
|
+
throw new AppServerError('invalid-params', `Invalid relay thinking levels: ${message(error)}`);
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
977
1016
|
if (source.reasoningEffort !== undefined)
|
|
978
1017
|
provider.reasoningEffort = reasoningEffort(source.reasoningEffort);
|
|
979
1018
|
return provider;
|
|
@@ -998,7 +1037,9 @@ function readRelayFailure(value) {
|
|
|
998
1037
|
return undefined;
|
|
999
1038
|
const source = value;
|
|
1000
1039
|
const kind = RELAY_ERROR_KINDS.includes(source.kind) ? source.kind : 'other';
|
|
1040
|
+
const timeout = kind === 'provider-request' && source.code === 'provider_timeout' ? readProviderTurnTiming(source.timeout) : undefined;
|
|
1001
1041
|
return {
|
|
1042
|
+
...(timeout ? { timeout } : {}),
|
|
1002
1043
|
message: typeof source.message === 'string' ? source.message.slice(0, 4_000) : '', kind,
|
|
1003
1044
|
...(source.contextOverflow === true ? { contextOverflow: true } : {}),
|
|
1004
1045
|
...(typeof source.code === 'string' && RELAY_FAILURE_CODE.test(source.code) ? { code: source.code } : {}),
|
|
@@ -1013,6 +1054,7 @@ export class AppServer {
|
|
|
1013
1054
|
manualAutomationTasks = new Set();
|
|
1014
1055
|
automationController = new AbortController();
|
|
1015
1056
|
directory;
|
|
1057
|
+
telemetry;
|
|
1016
1058
|
output;
|
|
1017
1059
|
error;
|
|
1018
1060
|
checkGraphHealth;
|
|
@@ -1023,7 +1065,6 @@ export class AppServer {
|
|
|
1023
1065
|
anthropicAuth;
|
|
1024
1066
|
claudeSignIn;
|
|
1025
1067
|
grokSignIn;
|
|
1026
|
-
googleSignIn;
|
|
1027
1068
|
openCodeSignIn;
|
|
1028
1069
|
signInProbes;
|
|
1029
1070
|
detectedSignIns = new Map();
|
|
@@ -1038,18 +1079,17 @@ export class AppServer {
|
|
|
1038
1079
|
githubEvents;
|
|
1039
1080
|
/** "@andorra-code" mentions on a task's PR (phase 3): the access check, the 👀 and the wake. */
|
|
1040
1081
|
mentions;
|
|
1041
|
-
/** The App's bot login (`bot` from `GET /v1/github`, or `as` from a bot write), for
|
|
1082
|
+
/** The App's bot login (`bot` from `GET /v1/github`, or `as` from a bot write), for review findings. */
|
|
1042
1083
|
githubBot;
|
|
1043
1084
|
pullRequestReader;
|
|
1044
1085
|
sessionChanges;
|
|
1045
|
-
autoFixWakes = new Set();
|
|
1046
1086
|
/** Wakes the PR tab's Fix with Agent armed: delivered as the person's request, not as a timer. */
|
|
1047
1087
|
fixWakes = new Set();
|
|
1048
1088
|
/** Wakes a mention of the App's bot on the task's PR armed: delivered as "Mentioned on GitHub", not as a timer. */
|
|
1049
1089
|
mentionWakes = new Set();
|
|
1050
1090
|
reviewWaiters = new Map();
|
|
1051
1091
|
reviewWaitsStarting = new Set();
|
|
1052
|
-
/** The Andorra review loop's fixer wakes,
|
|
1092
|
+
/** The Andorra review loop's fixer wakes, routed to the node that took the pull request. */
|
|
1053
1093
|
reviewWakes = new Set();
|
|
1054
1094
|
/** Each review wait's run, when it started, and the review loop it watches (the one running when it started, or after). */
|
|
1055
1095
|
reviewWaitRuns = new Map();
|
|
@@ -1129,6 +1169,7 @@ export class AppServer {
|
|
|
1129
1169
|
sessionTitles = new Map();
|
|
1130
1170
|
/** Automatic titles waiting to be asked again, by session, after an attempt was refused, failed, or cut short. */
|
|
1131
1171
|
titleRetries = new Map();
|
|
1172
|
+
draftGraphProbes = new Map();
|
|
1132
1173
|
operations = new Set();
|
|
1133
1174
|
prepareTask;
|
|
1134
1175
|
foreignEngineWatch;
|
|
@@ -1137,6 +1178,8 @@ export class AppServer {
|
|
|
1137
1178
|
codeIntel;
|
|
1138
1179
|
codeIntelOpening = Promise.resolve();
|
|
1139
1180
|
engineLinks = new Map();
|
|
1181
|
+
/** The telemetry lease in force when the current GitHub watch window began; its counts are reported only under that lease. */
|
|
1182
|
+
githubWatchLease;
|
|
1140
1183
|
environmentOptions;
|
|
1141
1184
|
relay;
|
|
1142
1185
|
environmentIds;
|
|
@@ -1148,6 +1191,8 @@ export class AppServer {
|
|
|
1148
1191
|
/** Bumped when the account changes, so an answer fetched for the previous account is never cached. */
|
|
1149
1192
|
accountGeneration = 0;
|
|
1150
1193
|
closed = false;
|
|
1194
|
+
antigravityStartups = new Set();
|
|
1195
|
+
antigravitySessions = new Map();
|
|
1151
1196
|
emitsStopped = false;
|
|
1152
1197
|
hosted;
|
|
1153
1198
|
hostedStarted = false;
|
|
@@ -1155,6 +1200,7 @@ export class AppServer {
|
|
|
1155
1200
|
onStop;
|
|
1156
1201
|
constructor(options) {
|
|
1157
1202
|
this.directory = options.directory ?? configDirectory();
|
|
1203
|
+
this.telemetry = new AppServerTelemetry(this.directory, result => this.emit('telemetry.changed', { ...result }), () => this.emit('config.changed', {})); // invalidate outside display data without polling auth
|
|
1158
1204
|
this.sessionChanges = new SessionChangeStore(this.directory);
|
|
1159
1205
|
this.output = options.output;
|
|
1160
1206
|
this.error = options.error;
|
|
@@ -1185,7 +1231,6 @@ export class AppServer {
|
|
|
1185
1231
|
this.environmentOptions = options.environments ?? {};
|
|
1186
1232
|
this.claudeSignIn = options.managedSignIn?.claude ?? claudeSignIn();
|
|
1187
1233
|
this.grokSignIn = options.managedSignIn?.grok ?? grokSignIn();
|
|
1188
|
-
this.googleSignIn = options.managedSignIn?.google ?? googleSignIn();
|
|
1189
1234
|
this.openCodeSignIn = options.managedSignIn?.opencode ?? new OpenCodeSignIn();
|
|
1190
1235
|
this.signInProbes = options.signInProbes;
|
|
1191
1236
|
this.retireCodexAccount = options.removeCodexAccount ?? removeCodexAccount;
|
|
@@ -1199,17 +1244,9 @@ export class AppServer {
|
|
|
1199
1244
|
this.pullRequestWatcher = new PullRequestWatcher({
|
|
1200
1245
|
home: this.directory, gh: this.gh, intervalMs: options.pullRequestPollMs,
|
|
1201
1246
|
onUpdated: (sessionId, pullRequest) => this.emitPullRequest(sessionId, pullRequest),
|
|
1202
|
-
wake: (sessionId, prompt, carry, origin) => {
|
|
1203
|
-
const wakeId = this.wakeForPullRequest(sessionId, prompt, carry, origin);
|
|
1204
|
-
this.githubEvents.woke(sessionId);
|
|
1205
|
-
return wakeId;
|
|
1206
|
-
},
|
|
1207
|
-
wakePending: id => this.timers.list().some(timer => timer.id === id),
|
|
1208
|
-
isWaiting: sessionId => this.reviewWaiters.has(sessionId) || this.reviewWaitsStarting.has(sessionId),
|
|
1209
1247
|
log: (level, detail) => this.log(level, detail),
|
|
1210
1248
|
covered: sessionId => this.githubEvents.covers(sessionId),
|
|
1211
1249
|
onGhCall: sessionId => this.githubEvents.countGhCall(sessionId),
|
|
1212
|
-
agentWrites: sessionId => this.autoFixWrites(sessionId),
|
|
1213
1250
|
onRead: (sessionId, pullRequest) => this.reviewLoop.pullRequestRead(sessionId, pullRequest),
|
|
1214
1251
|
...(options.githubApp?.now === undefined ? {} : { now: options.githubApp.now }),
|
|
1215
1252
|
...(options.githubApp?.checkNowDelayMs === undefined ? {} : { checkNowDelayMs: options.githubApp.checkNowDelayMs }),
|
|
@@ -1245,8 +1282,11 @@ export class AppServer {
|
|
|
1245
1282
|
onSummary: summary => {
|
|
1246
1283
|
// The window is gated like a run's events, on the signed-in account's plan and opt-out. Without a readable
|
|
1247
1284
|
// subject that cannot be checked, so the window is not sent at all.
|
|
1285
|
+
// The window's counts carry the lease latched when it began; the next window latches the one current now.
|
|
1286
|
+
const lease = this.githubWatchLease;
|
|
1287
|
+
this.githubWatchLease = telemetryLeaseSnapshot({ home: this.directory, signals: this.telemetry.signals });
|
|
1248
1288
|
const work = this.githubAccount().catch(() => undefined).then(subject => subject === undefined ? undefined
|
|
1249
|
-
: reportGitHubWatch({ home: this.directory, surface: configuredSurface('desktop'), subject }, summary));
|
|
1289
|
+
: reportGitHubWatch({ home: this.directory, signals: this.telemetry.signals, surface: configuredSurface('desktop'), subject, ...(lease ? { lease } : {}) }, summary));
|
|
1250
1290
|
this.telemetrySettle = this.telemetrySettle.then(() => work).catch(() => { });
|
|
1251
1291
|
return work;
|
|
1252
1292
|
},
|
|
@@ -1280,7 +1320,7 @@ export class AppServer {
|
|
|
1280
1320
|
const provider = config.providers.find(entry => entry.id === config.provider);
|
|
1281
1321
|
return provider?.model ? { provider: provider.id, model: provider.model } : undefined;
|
|
1282
1322
|
},
|
|
1283
|
-
writes: sessionId => this.
|
|
1323
|
+
writes: sessionId => this.reviewCommentWrites(sessionId),
|
|
1284
1324
|
wake: (sessionId, prompt, pullRequest) => this.wakeForReview(sessionId, prompt, pullRequest),
|
|
1285
1325
|
wakeArmed: wakeId => this.timers.get(wakeId) !== undefined,
|
|
1286
1326
|
cancelWake: (sessionId, wakeId) => this.cancelReviewWake(sessionId, wakeId),
|
|
@@ -1418,8 +1458,20 @@ export class AppServer {
|
|
|
1418
1458
|
}
|
|
1419
1459
|
async ready() {
|
|
1420
1460
|
setAuthSignOutReporter(error => this.accountSignedOut(error.message));
|
|
1461
|
+
this.telemetry.watch();
|
|
1421
1462
|
this.emit('ready', await this.hostInfo());
|
|
1422
1463
|
bootMark('ready.emitted');
|
|
1464
|
+
if (process.env.ANDORRA_AUTOMATION_WORKER !== '1')
|
|
1465
|
+
this.flushReasoningProbeQueue();
|
|
1466
|
+
if (process.env.ANDORRA_DESKTOP_RELEASE_VERSION && process.env.ANDORRA_AUTOMATION_WORKER !== '1' &&
|
|
1467
|
+
configuredSurface('desktop') === 'desktop') {
|
|
1468
|
+
// The observation is made now, so it carries the lease current now; a later Yes does not authorize it.
|
|
1469
|
+
const observedLease = telemetryLeaseSnapshot({ home: this.directory, signals: this.telemetry.signals });
|
|
1470
|
+
const input = { home: this.directory, surface: 'desktop', signals: this.telemetry.signals, ...(observedLease ? { lease: observedLease } : {}) };
|
|
1471
|
+
this.telemetrySettle = this.telemetrySettle
|
|
1472
|
+
.then(() => reportInstallationObserved(input, desktopInstallationReceipt()))
|
|
1473
|
+
.then(() => drainTelemetry(input, AbortSignal.timeout(2_000)));
|
|
1474
|
+
}
|
|
1423
1475
|
if (process.env.ANDORRA_AUTOMATION_WORKER !== '1' && !this.closed && !this.automationCheck) {
|
|
1424
1476
|
const reconcile = reconcileAutomationService(this.directory)
|
|
1425
1477
|
.catch(error => this.log('warn', `Automation sign-in registration: ${message(error)}`))
|
|
@@ -1578,7 +1630,7 @@ export class AppServer {
|
|
|
1578
1630
|
return { run: {
|
|
1579
1631
|
runId: live.runId, sessionId: live.sessionId, workspace: live.workspace,
|
|
1580
1632
|
questions: waiting.flatMap(item => item.kind === 'question'
|
|
1581
|
-
? [{ id: item.id, question: item.question, ...(item.choices === undefined ? {} : { choices: [...item.choices] }) }] : []),
|
|
1633
|
+
? [{ id: item.id, question: item.question, ...(item.choices === undefined ? {} : { choices: [...item.choices] }), ...(item.handoff ? { handoff: item.handoff } : {}) }] : []),
|
|
1582
1634
|
approvals: waiting.flatMap(item => item.kind === 'approval'
|
|
1583
1635
|
? [{ id: item.id, name: item.name, arguments: item.arguments }] : []),
|
|
1584
1636
|
...(this.modelRelay.awaiting(live.runId) ? { state: 'awaiting-desktop' } : {}),
|
|
@@ -1635,7 +1687,7 @@ export class AppServer {
|
|
|
1635
1687
|
this.write({ id: request.id, result: result ?? null });
|
|
1636
1688
|
}
|
|
1637
1689
|
catch (error) {
|
|
1638
|
-
this.write({ id: request.id, error: { code: error instanceof AppServerError ? error.code : 'internal', message: message(error) } });
|
|
1690
|
+
this.write({ id: request.id, error: { code: error instanceof AppServerError || error instanceof TelemetryPrivacyError || error instanceof LegalAcceptanceRequired ? error.code : 'internal', message: message(error) } });
|
|
1639
1691
|
}
|
|
1640
1692
|
}
|
|
1641
1693
|
write(response) {
|
|
@@ -1644,10 +1696,130 @@ export class AppServer {
|
|
|
1644
1696
|
}
|
|
1645
1697
|
catch { }
|
|
1646
1698
|
}
|
|
1699
|
+
async antigravityRequest(method, params) {
|
|
1700
|
+
if (this.closed)
|
|
1701
|
+
throw new AppServerError('cancelled', 'Engine is shutting down');
|
|
1702
|
+
if (method === 'antigravity.start') {
|
|
1703
|
+
if (typeof params.cwd !== 'string' || !isAbsolute(params.cwd)) {
|
|
1704
|
+
throw new AppServerError('invalid-params', 'Choose a local project directory for Antigravity.');
|
|
1705
|
+
}
|
|
1706
|
+
const sessionId = randomUUID();
|
|
1707
|
+
const startup = new AbortController();
|
|
1708
|
+
const permissions = new Map();
|
|
1709
|
+
const clearPermissions = () => {
|
|
1710
|
+
for (const answer of permissions.values())
|
|
1711
|
+
answer();
|
|
1712
|
+
permissions.clear();
|
|
1713
|
+
};
|
|
1714
|
+
this.antigravityStartups.add(startup);
|
|
1715
|
+
try {
|
|
1716
|
+
const session = await AntigravitySession.start({
|
|
1717
|
+
cwd: params.cwd,
|
|
1718
|
+
signal: startup.signal,
|
|
1719
|
+
version: await this.version(),
|
|
1720
|
+
onUpdate: update => this.emit('antigravity.update', { sessionId, update }),
|
|
1721
|
+
requestPermission: request => new Promise(resolve => {
|
|
1722
|
+
const requestId = randomUUID();
|
|
1723
|
+
permissions.set(requestId, resolve);
|
|
1724
|
+
this.emit('antigravity.permissionRequested', {
|
|
1725
|
+
sessionId, requestId, toolCall: request.toolCall, options: request.options,
|
|
1726
|
+
});
|
|
1727
|
+
}),
|
|
1728
|
+
onClosed: message => {
|
|
1729
|
+
clearPermissions();
|
|
1730
|
+
this.antigravitySessions.delete(sessionId);
|
|
1731
|
+
this.emit('antigravity.closed', { sessionId, message });
|
|
1732
|
+
},
|
|
1733
|
+
});
|
|
1734
|
+
if (this.closed) {
|
|
1735
|
+
await session.close();
|
|
1736
|
+
throw new AppServerError('cancelled', 'Engine is shutting down');
|
|
1737
|
+
}
|
|
1738
|
+
if (!session.isOpen) {
|
|
1739
|
+
await session.close();
|
|
1740
|
+
throw new AppServerError('not-found', 'Antigravity closed during startup. Start a new session to try again.');
|
|
1741
|
+
}
|
|
1742
|
+
this.antigravitySessions.set(sessionId, { session, permissions, clearPermissions, prompting: false });
|
|
1743
|
+
return { sessionId, options: session.options };
|
|
1744
|
+
}
|
|
1745
|
+
finally {
|
|
1746
|
+
this.antigravityStartups.delete(startup);
|
|
1747
|
+
}
|
|
1748
|
+
}
|
|
1749
|
+
const sessionId = identifier(params.sessionId, 'sessionId');
|
|
1750
|
+
const entry = this.antigravitySessions.get(sessionId);
|
|
1751
|
+
if (!entry) {
|
|
1752
|
+
if (method === 'antigravity.close')
|
|
1753
|
+
return {};
|
|
1754
|
+
throw new AppServerError('invalid-params', 'This Antigravity session has closed. Start a new session to continue.');
|
|
1755
|
+
}
|
|
1756
|
+
switch (method) {
|
|
1757
|
+
case 'antigravity.prompt': {
|
|
1758
|
+
if (typeof params.text !== 'string' || !params.text.trim() || params.text.length > 100_000) {
|
|
1759
|
+
throw new AppServerError('invalid-params', 'Enter an Antigravity prompt of up to 100,000 characters.');
|
|
1760
|
+
}
|
|
1761
|
+
if (entry.prompting)
|
|
1762
|
+
throw new AppServerError('busy', 'Antigravity is already processing a prompt.');
|
|
1763
|
+
entry.prompting = true;
|
|
1764
|
+
try {
|
|
1765
|
+
return await entry.session.prompt(params.text);
|
|
1766
|
+
}
|
|
1767
|
+
finally {
|
|
1768
|
+
entry.clearPermissions();
|
|
1769
|
+
entry.prompting = false;
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
case 'antigravity.permission': {
|
|
1773
|
+
const requestId = identifier(params.requestId, 'requestId');
|
|
1774
|
+
if (params.optionId !== undefined && typeof params.optionId !== 'string') {
|
|
1775
|
+
throw new AppServerError('invalid-params', 'Choose an Antigravity permission option.');
|
|
1776
|
+
}
|
|
1777
|
+
const answer = entry.permissions.get(requestId);
|
|
1778
|
+
entry.permissions.delete(requestId);
|
|
1779
|
+
answer?.(params.optionId);
|
|
1780
|
+
return {};
|
|
1781
|
+
}
|
|
1782
|
+
case 'antigravity.cancel':
|
|
1783
|
+
entry.clearPermissions();
|
|
1784
|
+
await entry.session.cancel();
|
|
1785
|
+
return {};
|
|
1786
|
+
case 'antigravity.close':
|
|
1787
|
+
this.antigravitySessions.delete(sessionId);
|
|
1788
|
+
entry.clearPermissions();
|
|
1789
|
+
await entry.session.close();
|
|
1790
|
+
return {};
|
|
1791
|
+
case 'antigravity.option': {
|
|
1792
|
+
if (typeof params.configId !== 'string' || typeof params.value !== 'string') {
|
|
1793
|
+
throw new AppServerError('invalid-params', 'Choose an Antigravity option and value.');
|
|
1794
|
+
}
|
|
1795
|
+
return { options: await entry.session.setOption(params.configId, params.value) };
|
|
1796
|
+
}
|
|
1797
|
+
default: throw new AppServerError('unknown-method', `Unknown method: ${method}`);
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1647
1800
|
async dispatch(method, params) {
|
|
1801
|
+
if (method.startsWith('antigravity.')) {
|
|
1802
|
+
// Starting a session and sending a prompt are coding work; cancelling, closing and answering stay available.
|
|
1803
|
+
if (legalMethodRequiresAcceptance(method))
|
|
1804
|
+
await requireLegalAcceptance(this.directory);
|
|
1805
|
+
return this.antigravityRequest(method, params);
|
|
1806
|
+
}
|
|
1648
1807
|
if (this.closed && method.startsWith('automations.'))
|
|
1649
1808
|
throw new AppServerError('cancelled', 'Engine is shutting down');
|
|
1809
|
+
if (legalRequestRequiresAcceptance(method, params))
|
|
1810
|
+
await requireLegalAcceptance(this.directory);
|
|
1650
1811
|
switch (method) {
|
|
1812
|
+
case 'legal.status': return legalStatus(this.directory, {}, params.refresh === true);
|
|
1813
|
+
case 'legal.documents': {
|
|
1814
|
+
if (params.kind !== 'terms' && params.kind !== 'privacy')
|
|
1815
|
+
throw new AppServerError('invalid-params', 'Choose terms or privacy');
|
|
1816
|
+
return { html: await legalDocument(params.kind) };
|
|
1817
|
+
}
|
|
1818
|
+
case 'legal.accept': {
|
|
1819
|
+
if (params.confirmed !== true || typeof params.releaseId !== 'string' || (params.expectedSubject !== null && typeof params.expectedSubject !== 'string'))
|
|
1820
|
+
throw new AppServerError('invalid-params', 'Review the policies and confirm explicitly.');
|
|
1821
|
+
return acceptLegal({ releaseId: params.releaseId, expectedSubject: params.expectedSubject, confirmed: true }, this.directory, {}, 'desktop');
|
|
1822
|
+
}
|
|
1651
1823
|
case 'automations.list': return { automations: await new AutomationStore(this.directory).list(), service: await automationService('status', this.directory) };
|
|
1652
1824
|
case 'automations.create': return { automation: await new AutomationStore(this.directory).create(params) };
|
|
1653
1825
|
case 'automations.update': {
|
|
@@ -1670,9 +1842,12 @@ export class AppServer {
|
|
|
1670
1842
|
}
|
|
1671
1843
|
case 'host.info': return { ...(await this.hostInfo()), running: this.run !== undefined || this.starting };
|
|
1672
1844
|
case 'run.current': return this.currentRun();
|
|
1845
|
+
case 'telemetry.status': return this.telemetry.status(params);
|
|
1846
|
+
case 'telemetry.setConsent': return this.telemetry.setConsent(params);
|
|
1673
1847
|
case 'config.get': return { config: await this.analyticsConfigView(await loadConfig(this.directory)) };
|
|
1674
1848
|
case 'config.set': return this.setConfig(params);
|
|
1675
1849
|
case 'project.extensions': return this.projectExtensionEntry(params);
|
|
1850
|
+
case 'workspace.permission': return this.workspacePermissionEntry(params);
|
|
1676
1851
|
case 'project.extensions.set': return this.setProjectExtensionEntry(params);
|
|
1677
1852
|
case 'providers.list': {
|
|
1678
1853
|
const config = await loadConfig(this.directory);
|
|
@@ -1699,8 +1874,11 @@ export class AppServer {
|
|
|
1699
1874
|
case 'andorra.remove': return this.hideListedEntry();
|
|
1700
1875
|
case 'providers.discover': return this.discoverModels(params);
|
|
1701
1876
|
case 'providers.test': return this.testProviderEndpoint(params);
|
|
1877
|
+
case 'providers.getThinkingLevels': return this.getThinkingLevels(params);
|
|
1702
1878
|
case 'providers.detectThinkingLevels': return this.detectThinkingLevels(params);
|
|
1703
1879
|
case 'providers.setThinkingLevels': return this.setThinkingLevels(params);
|
|
1880
|
+
case 'providers.usage': return this.providerUsage();
|
|
1881
|
+
case 'routing.refreshScores': return this.refreshRoutingScores();
|
|
1704
1882
|
case 'providers.detectSignIns': return this.detectProviderSignIns(params);
|
|
1705
1883
|
case 'providers.importSignIns': return this.importProviderSignIns(params);
|
|
1706
1884
|
case 'providers.auth.status': return this.providerAuth('status', params);
|
|
@@ -1738,9 +1916,10 @@ export class AppServer {
|
|
|
1738
1916
|
case 'sessions.setJev': return { session: this.summary(await this.setSessionJev(params)) };
|
|
1739
1917
|
case 'sessions.setArchived': return { session: this.summary(await this.setSessionArchived(params)) };
|
|
1740
1918
|
case 'sessions.setPinned': return { session: this.summary(await this.setSessionPinned(params)) };
|
|
1919
|
+
case 'sessions.setWorkspace': return { session: this.summary(await this.setSessionWorkspace(params)) };
|
|
1741
1920
|
case 'sessions.delete': return this.deleteSession(params);
|
|
1742
|
-
case 'sessions.pullRequest.get': return { pullRequest:
|
|
1743
|
-
case 'sessions.pullRequest.list': return { pullRequests: (await listPullRequests(this.directory)).map(entry => ({ sessionId: entry.sessionId, pullRequest:
|
|
1921
|
+
case 'sessions.pullRequest.get': return { pullRequest: this.pullRequestForClient(await readPullRequest(this.directory, identifier(params.id, 'id'))) };
|
|
1922
|
+
case 'sessions.pullRequest.list': return { pullRequests: (await listPullRequests(this.directory)).map(entry => ({ sessionId: entry.sessionId, pullRequest: this.pullRequestForClient(entry.pullRequest) })) };
|
|
1744
1923
|
case 'sessions.pullRequest.update': {
|
|
1745
1924
|
let settings;
|
|
1746
1925
|
try {
|
|
@@ -1749,7 +1928,7 @@ export class AppServer {
|
|
|
1749
1928
|
catch (error) {
|
|
1750
1929
|
throw new AppServerError('invalid-params', message(error));
|
|
1751
1930
|
}
|
|
1752
|
-
return { pullRequest:
|
|
1931
|
+
return { pullRequest: this.pullRequestForClient(await this.updatePullRequest(identifier(params.id, 'id'), settings)) };
|
|
1753
1932
|
}
|
|
1754
1933
|
case 'sessions.pullRequest.dismiss':
|
|
1755
1934
|
await this.dismissPullRequest(identifier(params.id, 'id'));
|
|
@@ -1819,10 +1998,11 @@ export class AppServer {
|
|
|
1819
1998
|
case 'graphs.list': return this.listGraphs(params);
|
|
1820
1999
|
case 'graphs.get': return this.getGraph(params);
|
|
1821
2000
|
case 'graphs.select': return this.selectGraph(params);
|
|
2001
|
+
case 'graphs.checkModels': return this.checkDraftGraphModels(params);
|
|
1822
2002
|
case 'graphs.visibility.set': return this.setGraphVisibilityMethod(params);
|
|
1823
2003
|
case 'graphs.visibility.import': return this.importGraphVisibilityMethod(params);
|
|
1824
2004
|
case 'agents.export': return this.exportAgent(params);
|
|
1825
|
-
case 'editor.open': return this.openEditor();
|
|
2005
|
+
case 'editor.open': return this.openEditor(params);
|
|
1826
2006
|
case 'editor.close': return this.closeEditor();
|
|
1827
2007
|
case 'terminal.open': {
|
|
1828
2008
|
const root = await workspaceRoot(params.cwd);
|
|
@@ -2083,7 +2263,7 @@ export class AppServer {
|
|
|
2083
2263
|
case 'workspace.image': {
|
|
2084
2264
|
const root = await workspaceRoot(params.workspace);
|
|
2085
2265
|
try {
|
|
2086
|
-
return await readWorkspaceImage(root, params.path);
|
|
2266
|
+
return await readWorkspaceImage(root, params.path, { outside: params.outside === true });
|
|
2087
2267
|
}
|
|
2088
2268
|
catch (error) {
|
|
2089
2269
|
throw new AppServerError('invalid-params', message(error));
|
|
@@ -2183,6 +2363,14 @@ export class AppServer {
|
|
|
2183
2363
|
}
|
|
2184
2364
|
return sessionTrajectoryFile(this.directory, await this.trajectoryIdOf(id));
|
|
2185
2365
|
}
|
|
2366
|
+
case 'sessions.artifact.read': {
|
|
2367
|
+
const id = identifier(params.id, 'id');
|
|
2368
|
+
const reference = parseArtifactReference(params.ref);
|
|
2369
|
+
const session = await this.readSession(id);
|
|
2370
|
+
if (!session.history.some(turn => turn.runId === reference.runId))
|
|
2371
|
+
throw artifactUnavailable();
|
|
2372
|
+
return readArtifactPreview(this.directory, reference);
|
|
2373
|
+
}
|
|
2186
2374
|
case 'sessions.trajectory': {
|
|
2187
2375
|
const id = params.id;
|
|
2188
2376
|
if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(id)) {
|
|
@@ -2280,7 +2468,7 @@ export class AppServer {
|
|
|
2280
2468
|
this.slotWrites.delete(slot); });
|
|
2281
2469
|
return next;
|
|
2282
2470
|
}
|
|
2283
|
-
async setConfig(params) {
|
|
2471
|
+
async setConfig(params, admittedLegacy = false) {
|
|
2284
2472
|
const patch = params.config;
|
|
2285
2473
|
if (!patch || typeof patch !== 'object' || Array.isArray(patch))
|
|
2286
2474
|
throw new AppServerError('invalid-params', 'config must be an object');
|
|
@@ -2291,13 +2479,48 @@ export class AppServer {
|
|
|
2291
2479
|
const unknown = entries.map(([key]) => key).filter(key => !EDITABLE_CONFIG_KEYS.includes(key));
|
|
2292
2480
|
if (unknown.length)
|
|
2293
2481
|
throw new AppServerError('invalid-params', `Unknown configuration field: ${unknown.join(', ')}`);
|
|
2482
|
+
const analytics = patch.analytics;
|
|
2483
|
+
if (analytics !== undefined && !admittedLegacy) {
|
|
2484
|
+
try {
|
|
2485
|
+
validateAnalyticsConfig(analytics);
|
|
2486
|
+
}
|
|
2487
|
+
catch (error) {
|
|
2488
|
+
throw new AppServerError('invalid-params', message(error));
|
|
2489
|
+
}
|
|
2490
|
+
const permission = await this.telemetry.permission();
|
|
2491
|
+
if (!permission.permissionRequired) {
|
|
2492
|
+
const saved = await withTelemetryAdmission({ home: this.directory, signals: this.telemetry.signals }, async (admission) => {
|
|
2493
|
+
if (admission.lease.mode !== 'out')
|
|
2494
|
+
throw new AppServerError('busy', 'Privacy settings changed. Reload and try again.');
|
|
2495
|
+
return this.setConfig(params, true);
|
|
2496
|
+
});
|
|
2497
|
+
if (saved === undefined)
|
|
2498
|
+
throw new AppServerError('busy', 'Privacy settings changed. Reload and try again.');
|
|
2499
|
+
return saved;
|
|
2500
|
+
}
|
|
2501
|
+
// An old on is never permission, a migration, or an analytics config write. Old off
|
|
2502
|
+
// is a safe explicit refusal on every plan, before taking any configuration lock.
|
|
2503
|
+
if (analytics.enabled === false) {
|
|
2504
|
+
const result = await this.telemetry.setConsent({ answer: 'no', expectedRevision: permission.revision, noticeVersion: permission.noticeVersion });
|
|
2505
|
+
if (result.conflict)
|
|
2506
|
+
throw new AppServerError('busy', 'Privacy settings changed. Reload and try again.');
|
|
2507
|
+
if (result.cleanupError)
|
|
2508
|
+
throw new AppServerError('storage', 'Reports are off; privacy cleanup needs to finish. Retry the setting.');
|
|
2509
|
+
}
|
|
2510
|
+
const functional = Object.fromEntries(entries.filter(([key]) => key !== 'analytics'));
|
|
2511
|
+
if (Object.keys(functional).length)
|
|
2512
|
+
return this.setConfig({ ...params, config: functional, ...(expects ? { expects: Object.fromEntries(Object.entries(expects).filter(([key]) => key !== 'analytics')) } : {}) });
|
|
2513
|
+
const view = await this.analyticsConfigView(await loadConfig(this.directory));
|
|
2514
|
+
this.emit('config.changed', { config: view });
|
|
2515
|
+
return { config: view };
|
|
2516
|
+
}
|
|
2294
2517
|
if (patch.analytics?.enabled === false) {
|
|
2295
2518
|
const current = await loadConfig(this.directory);
|
|
2296
2519
|
const status = await getAuthStatus().catch(() => undefined);
|
|
2297
|
-
const gate = await telemetryGate({ home: this.directory, config: current, subject: status?.signedIn ? status.subject : undefined });
|
|
2520
|
+
const gate = await telemetryGate({ home: this.directory, signals: this.telemetry.signals, config: current, subject: status?.signedIn ? status.subject : undefined });
|
|
2298
2521
|
if (!gate.canOptOut) {
|
|
2299
2522
|
const named = gate.plan === 'free' ? 'Free' : gate.plan === 'legacy' ? 'Legacy' : 'current';
|
|
2300
|
-
throw new AppServerError('invalid-params', `
|
|
2523
|
+
throw new AppServerError('invalid-params', `Product usage reports stay on: collection is included with the ${named} plan outside the EEA, UK and Switzerland. Upgrade to Plus to turn it off.`);
|
|
2301
2524
|
}
|
|
2302
2525
|
}
|
|
2303
2526
|
let turnedOff = false;
|
|
@@ -2305,7 +2528,7 @@ export class AppServer {
|
|
|
2305
2528
|
const removedAnthropic = [];
|
|
2306
2529
|
const saved = await this.serializeConfig(async () => {
|
|
2307
2530
|
try {
|
|
2308
|
-
return await changeConfigFile(this.directory, current => {
|
|
2531
|
+
return await (admittedLegacy ? changeLegacyConfigFile : changeConfigFile)(this.directory, current => {
|
|
2309
2532
|
for (const [key, value] of Object.entries((expects ?? {}))) {
|
|
2310
2533
|
const stored = current[key];
|
|
2311
2534
|
const expected = value === null && ['decisions', 'jevEnabled', 'systemPromptOverride', 'autoArchiveDays'].includes(key) ? undefined : value;
|
|
@@ -2313,6 +2536,18 @@ export class AppServer {
|
|
|
2313
2536
|
throw new AppServerError('busy', `That setting changed elsewhere: ${key}. Reload it and try again.`);
|
|
2314
2537
|
}
|
|
2315
2538
|
const merged = { ...current, ...Object.fromEntries(entries) };
|
|
2539
|
+
if (Object.hasOwn(patch, 'adaptiveRouting')) {
|
|
2540
|
+
// The settings key is a view of efficiency.adaptiveRouting: it is merged there and never stored at the top level.
|
|
2541
|
+
delete merged.adaptiveRouting;
|
|
2542
|
+
const { adaptiveRouting: _savedRouting, ...otherEfficiency } = current.efficiency ?? {};
|
|
2543
|
+
const routing = mergeAdaptiveRoutingSettings(_savedRouting, patch.adaptiveRouting);
|
|
2544
|
+
const efficiency = { ...otherEfficiency, ...(routing === undefined ? {} : { adaptiveRouting: routing }) };
|
|
2545
|
+
validateEfficiencyConfig(efficiency);
|
|
2546
|
+
if (Object.keys(efficiency).length)
|
|
2547
|
+
merged.efficiency = efficiency;
|
|
2548
|
+
else
|
|
2549
|
+
delete merged.efficiency;
|
|
2550
|
+
}
|
|
2316
2551
|
if (patch.analytics !== undefined) {
|
|
2317
2552
|
turnedOff = resolveAnalyticsConfig(current).enabled && merged.analytics?.enabled === false;
|
|
2318
2553
|
merged.analytics = { ...merged.analytics, generation: analyticsGenerationFor(current.analytics, merged.analytics?.enabled !== false) };
|
|
@@ -2356,14 +2591,14 @@ export class AppServer {
|
|
|
2356
2591
|
}
|
|
2357
2592
|
});
|
|
2358
2593
|
if (turnedOff)
|
|
2359
|
-
await purgeOutbox(telemetryDirectory(this.directory));
|
|
2594
|
+
await purgeOutbox(telemetryDirectory(this.directory), { signals: this.telemetry.signals });
|
|
2360
2595
|
if (patch.analytics !== undefined) {
|
|
2361
2596
|
const status = await getAuthStatus().catch(() => undefined);
|
|
2362
2597
|
let failure;
|
|
2363
2598
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
2364
2599
|
try {
|
|
2365
2600
|
await recordPreference({
|
|
2366
|
-
directory: telemetryDirectory(this.directory),
|
|
2601
|
+
directory: telemetryDirectory(this.directory), signals: this.telemetry.signals,
|
|
2367
2602
|
subject: status?.signedIn ? status.subject : undefined,
|
|
2368
2603
|
preference: saved.analytics?.enabled === false ? 'off' : 'on',
|
|
2369
2604
|
});
|
|
@@ -2399,6 +2634,14 @@ export class AppServer {
|
|
|
2399
2634
|
const entry = config.projectExtensions?.[workspacePermissionKey(path)];
|
|
2400
2635
|
return { entry: entry ? structuredClone(entry) : { override: false } };
|
|
2401
2636
|
}
|
|
2637
|
+
// Mirrors projectExtensionEntry: the desktop sends the project path and the engine resolves the stored entry
|
|
2638
|
+
// with the same workspacePermissionKey and workspaceRoot every run applies, so the desktop's permission picker
|
|
2639
|
+
// shows the mode a task would actually start in instead of guessing the CLI's fallback.
|
|
2640
|
+
async workspacePermissionEntry(params) {
|
|
2641
|
+
const root = await workspaceRoot(params.workspace);
|
|
2642
|
+
const config = await loadConfig(this.directory);
|
|
2643
|
+
return { mode: config.workspacePermissions?.[workspacePermissionKey(root)] ?? 'ask-for-approval' };
|
|
2644
|
+
}
|
|
2402
2645
|
async setProjectExtensionEntry(params) {
|
|
2403
2646
|
const path = text(params.path, 'path', 4096);
|
|
2404
2647
|
if (!isProjectExtensionOverride(params.entry))
|
|
@@ -2802,10 +3045,12 @@ export class AppServer {
|
|
|
2802
3045
|
return { config: view, added };
|
|
2803
3046
|
}
|
|
2804
3047
|
async providerAuth(action, params) {
|
|
2805
|
-
if (params.providerType === '
|
|
3048
|
+
if (params.providerType === 'google')
|
|
3049
|
+
throw new AppServerError('invalid-params', GOOGLE_LEGACY_MESSAGE);
|
|
3050
|
+
if (params.providerType === 'claude' || params.providerType === 'grok' || params.providerType === 'opencode')
|
|
2806
3051
|
return this.managedProviderAuth(action, params);
|
|
2807
3052
|
if (action === 'submit')
|
|
2808
|
-
throw new AppServerError('invalid-params', 'Only Claude, Grok
|
|
3053
|
+
throw new AppServerError('invalid-params', 'Only Claude, Grok and OpenCode sign-ins accept a pasted code.');
|
|
2809
3054
|
if (params.providerType === 'anthropic')
|
|
2810
3055
|
return this.anthropicProviderAuth(action, params);
|
|
2811
3056
|
if (params.providerType !== 'codex' || Object.keys(params).some(key => !['providerType', 'attemptId', 'providerId'].includes(key))) {
|
|
@@ -2838,7 +3083,7 @@ export class AppServer {
|
|
|
2838
3083
|
}
|
|
2839
3084
|
async managedProviderAuth(action, params) {
|
|
2840
3085
|
const type = params.providerType;
|
|
2841
|
-
const product = type === 'claude' ? 'Claude' : type === 'grok' ? 'Grok' :
|
|
3086
|
+
const product = type === 'claude' ? 'Claude' : type === 'grok' ? 'Grok' : 'OpenCode';
|
|
2842
3087
|
const allowed = ['providerType', 'attemptId', 'providerId', 'code', ...(type === 'opencode' ? ['signInProvider', 'signInMethod'] : [])];
|
|
2843
3088
|
if (Object.keys(params).some(key => !allowed.includes(key))) {
|
|
2844
3089
|
throw new AppServerError('invalid-params', `${product} sign-in accepts providerType, an optional attemptId and providerId${type === 'opencode' ? ', signInProvider and signInMethod' : ''}, and a code to submit.`);
|
|
@@ -2870,7 +3115,7 @@ export class AppServer {
|
|
|
2870
3115
|
: await service.status(id);
|
|
2871
3116
|
}
|
|
2872
3117
|
else {
|
|
2873
|
-
const service = type === 'claude' ? this.claudeSignIn :
|
|
3118
|
+
const service = type === 'claude' ? this.claudeSignIn : this.grokSignIn;
|
|
2874
3119
|
view = action === 'start' ? await service.start(id)
|
|
2875
3120
|
: action === 'cancel' ? await service.cancel(id)
|
|
2876
3121
|
: action === 'submit' ? await service.submitCode(id, code)
|
|
@@ -2955,21 +3200,68 @@ export class AppServer {
|
|
|
2955
3200
|
const entry = provider.thinkingLevels?.[model];
|
|
2956
3201
|
return { providerId: provider.id, model, detected, supported: entry?.supported ?? [...REASONING_EFFORTS], disabled: entry?.disabled ?? [], enabled: enabledLevels(provider, model) };
|
|
2957
3202
|
}
|
|
3203
|
+
async getThinkingLevels(params) {
|
|
3204
|
+
const { provider, model } = this.thinkingLevelTarget(await loadConfig(this.directory), params);
|
|
3205
|
+
if (provider.thinkingLevels?.[model]?.supported !== undefined)
|
|
3206
|
+
return this.thinkingLevelsView(provider, model, true);
|
|
3207
|
+
if (provider.type === 'andorra')
|
|
3208
|
+
return this.thinkingLevelsView(provider, model, false);
|
|
3209
|
+
this.flushReasoningProbeQueue();
|
|
3210
|
+
const generation = this.accountGeneration;
|
|
3211
|
+
const supported = await this.operation(6000, signal => readReasoningProbe(provider, model, signal));
|
|
3212
|
+
if (supported === undefined || generation !== this.accountGeneration)
|
|
3213
|
+
return this.thinkingLevelsView(provider, model, false);
|
|
3214
|
+
const saved = await this.saveThinkingLevels(provider.id, current => {
|
|
3215
|
+
if (generation !== this.accountGeneration)
|
|
3216
|
+
return current;
|
|
3217
|
+
if (current.type !== provider.type || current.baseUrl !== provider.baseUrl)
|
|
3218
|
+
throw new AppServerError('busy', 'The provider changed. Reopen the model picker.');
|
|
3219
|
+
if (Object.hasOwn(current.thinkingLevels ?? {}, model) && current.thinkingLevels?.[model]?.supported !== undefined)
|
|
3220
|
+
return current;
|
|
3221
|
+
return withDetectedLevels(current, model, supported);
|
|
3222
|
+
});
|
|
3223
|
+
this.emit('config.changed', { config: await this.analyticsConfigView(await loadConfig(this.directory)) });
|
|
3224
|
+
return this.thinkingLevelsView(saved, model, saved.thinkingLevels?.[model]?.supported !== undefined);
|
|
3225
|
+
}
|
|
2958
3226
|
/** Finds out which thinking levels a model accepts and saves them. An inconclusive answer saves nothing. */
|
|
2959
3227
|
async detectThinkingLevels(params) {
|
|
2960
3228
|
const { provider, model } = this.thinkingLevelTarget(await loadConfig(this.directory), params);
|
|
3229
|
+
if (provider.type === 'andorra')
|
|
3230
|
+
return this.thinkingLevelsView(provider, model, provider.thinkingLevels?.[model]?.supported !== undefined);
|
|
3231
|
+
const subject = await currentReasoningProbeSubject(AbortSignal.timeout(1500));
|
|
3232
|
+
const probeId = typeof params.probeId === 'string' && /^[a-zA-Z0-9-]{1,64}$/.test(params.probeId) ? params.probeId : undefined;
|
|
3233
|
+
const onAccepted = probeId === undefined ? undefined : (level) => {
|
|
3234
|
+
this.emit('providers.thinkingLevelAccepted', { probeId, providerId: provider.id, model, level });
|
|
3235
|
+
};
|
|
2961
3236
|
let supported;
|
|
2962
3237
|
try {
|
|
2963
|
-
supported = await this.operation(90_000, signal => detectProviderLevels(provider, model, signal));
|
|
3238
|
+
supported = await this.operation(90_000, signal => detectProviderLevels(provider, model, signal, undefined, onAccepted));
|
|
2964
3239
|
}
|
|
2965
3240
|
catch (error) {
|
|
2966
3241
|
throw new AppServerError('network', message(error));
|
|
2967
3242
|
}
|
|
2968
3243
|
if (supported === undefined)
|
|
2969
3244
|
return this.thinkingLevelsView(provider, model, false);
|
|
2970
|
-
const saved = await this.saveThinkingLevels(provider.id, current =>
|
|
3245
|
+
const saved = await this.saveThinkingLevels(provider.id, current => {
|
|
3246
|
+
if (current.type !== provider.type || current.baseUrl !== provider.baseUrl)
|
|
3247
|
+
throw new AppServerError('busy', 'The provider changed. Reopen the model picker.');
|
|
3248
|
+
return withDetectedLevels(current, model, supported);
|
|
3249
|
+
});
|
|
3250
|
+
if (subject !== undefined) {
|
|
3251
|
+
try {
|
|
3252
|
+
await queueReasoningProbe(this.directory, subject, provider, model, supported);
|
|
3253
|
+
}
|
|
3254
|
+
catch {
|
|
3255
|
+
this.log('warn', 'Could not queue reasoning levels for account sync. They were saved locally.');
|
|
3256
|
+
}
|
|
3257
|
+
this.flushReasoningProbeQueue();
|
|
3258
|
+
}
|
|
3259
|
+
this.emit('config.changed', { config: await this.analyticsConfigView(await loadConfig(this.directory)) });
|
|
2971
3260
|
return this.thinkingLevelsView(saved, model, true);
|
|
2972
3261
|
}
|
|
3262
|
+
flushReasoningProbeQueue() {
|
|
3263
|
+
void this.operation(30_000, signal => flushReasoningProbes(this.directory, signal)).catch(() => { });
|
|
3264
|
+
}
|
|
2973
3265
|
async setThinkingLevels(params) {
|
|
2974
3266
|
const { provider, model } = this.thinkingLevelTarget(await loadConfig(this.directory), params);
|
|
2975
3267
|
const disabled = params.disabled;
|
|
@@ -2987,6 +3279,36 @@ export class AppServer {
|
|
|
2987
3279
|
}
|
|
2988
3280
|
return this.thinkingLevelsView(saved, model, saved.thinkingLevels?.[model]?.supported !== undefined);
|
|
2989
3281
|
}
|
|
3282
|
+
/** The subscription usage windows of every provider whose client reports them, by provider id. */
|
|
3283
|
+
async providerUsage() {
|
|
3284
|
+
const config = await loadConfig(this.directory);
|
|
3285
|
+
const read = createUsageReader(() => config.providers, { hosted: () => this.hosted.usage() });
|
|
3286
|
+
const readings = await this.operation(20_000, signal => read(signal));
|
|
3287
|
+
return { usage: Object.entries(readings).flatMap(([providerId, windows]) => windows?.length ? [{ providerId, windows: [...windows] }] : []) };
|
|
3288
|
+
}
|
|
3289
|
+
/**
|
|
3290
|
+
* Scores every configured model from published benchmarks (the average of three providers' general-purpose scores,
|
|
3291
|
+
* at each thinking level they list) and saves the scores that routing chooses by
|
|
3292
|
+
* (`efficiency.adaptiveRouting.scores`). A refresh that scores no model saves nothing.
|
|
3293
|
+
*/
|
|
3294
|
+
async refreshRoutingScores() {
|
|
3295
|
+
const config = await loadConfig(this.directory);
|
|
3296
|
+
const subjects = scoreSubjects(config.providers, (providerId, name) => enabledLevels(config.providers.find(item => item.id === providerId), name)).slice(0, MAX_POOL_SCORES);
|
|
3297
|
+
if (!subjects.length)
|
|
3298
|
+
throw new AppServerError('invalid-params', 'No models are configured to score');
|
|
3299
|
+
const previous = config.efficiency?.adaptiveRouting?.scores;
|
|
3300
|
+
let result;
|
|
3301
|
+
try {
|
|
3302
|
+
result = await this.operation(240_000, signal => refreshPoolScores({ subjects, signal, ...(previous ? { previous } : {}) }));
|
|
3303
|
+
}
|
|
3304
|
+
catch (error) {
|
|
3305
|
+
throw new AppServerError('network', message(error));
|
|
3306
|
+
}
|
|
3307
|
+
const scoresUpdatedAt = new Date().toISOString();
|
|
3308
|
+
const saved = await changeConfigFile(this.directory, current => ({ ...current, efficiency: { ...current.efficiency, adaptiveRouting: { ...current.efficiency?.adaptiveRouting, scores: result.scores, scoresUpdatedAt } } }));
|
|
3309
|
+
this.emit('config.changed', { config: await this.analyticsConfigView(saved) });
|
|
3310
|
+
return { scoresUpdatedAt, models: subjects.length, rated: result.rated.length, kept: result.kept.length, unrated: result.unrated, benchmarks: result.benchmarks };
|
|
3311
|
+
}
|
|
2990
3312
|
async saveThinkingLevels(id, change) {
|
|
2991
3313
|
let next;
|
|
2992
3314
|
await changeConfigFile(this.directory, current => {
|
|
@@ -3093,6 +3415,7 @@ export class AppServer {
|
|
|
3093
3415
|
// The new account's machines that are allowed here get their links.
|
|
3094
3416
|
this.syncModelRelayLinks();
|
|
3095
3417
|
this.githubEvents.refresh();
|
|
3418
|
+
this.flushReasoningProbeQueue();
|
|
3096
3419
|
return { signedIn: status.signedIn, subject: status.subject };
|
|
3097
3420
|
}
|
|
3098
3421
|
catch (error) {
|
|
@@ -3433,6 +3756,40 @@ export class AppServer {
|
|
|
3433
3756
|
return updated;
|
|
3434
3757
|
});
|
|
3435
3758
|
}
|
|
3759
|
+
/** Moves a task into another project folder: the rail lists it there, and its next run works there. */
|
|
3760
|
+
async setSessionWorkspace(params) {
|
|
3761
|
+
const id = identifier(params.id, 'id');
|
|
3762
|
+
const root = await workspaceRoot(params.workspace);
|
|
3763
|
+
if (this.run?.sessionId === id || this.startingSession === id || this.starting)
|
|
3764
|
+
throw new AppServerError('busy', 'That task is running. Stop the run or wait for it to finish, then move it.');
|
|
3765
|
+
if (await folderChangeHeld(this.directory, root))
|
|
3766
|
+
throw new AppServerError('busy', folderChangeBusy);
|
|
3767
|
+
let rekey = false;
|
|
3768
|
+
const result = await this.withSessionMutation(id, async () => {
|
|
3769
|
+
if (await sessionHasOpenRun(this.directory, id))
|
|
3770
|
+
throw new AppServerError('busy', 'That task is running in another window. Stop the run or wait for it to finish, then move it.');
|
|
3771
|
+
const record = await this.readSession(id);
|
|
3772
|
+
if (resolve(record.workspace) === resolve(root))
|
|
3773
|
+
return record;
|
|
3774
|
+
if (this.timers.list(id).length > 0 || await sessionHasArmedWake(this.directory, id))
|
|
3775
|
+
throw new AppServerError('busy', 'That task has a timer set. Wait for it or cancel it, then move it.');
|
|
3776
|
+
// A worktree belongs to the repository of the project the task left; the task would go on editing that one.
|
|
3777
|
+
if (record.checkout?.kind === 'worktree' && record.checkout.removedAt === undefined) {
|
|
3778
|
+
throw new AppServerError('invalid-params', 'That task works in its own worktree of its project. Remove the worktree first, then move it.');
|
|
3779
|
+
}
|
|
3780
|
+
const { checkout: _checkout, ...rest } = record;
|
|
3781
|
+
const moved = { ...rest, workspace: root, projectId: await this.projectIdFor(root) };
|
|
3782
|
+
await this.store().save(savedSessionFields(moved));
|
|
3783
|
+
rekey = AppServer.panelProfileKey(record) !== AppServer.panelProfileKey(moved);
|
|
3784
|
+
this.emit('session.updated', { session: this.summary(moved) });
|
|
3785
|
+
return moved;
|
|
3786
|
+
});
|
|
3787
|
+
// The panel browser picks its profile once, when it opens: a moved task must lose the one it holds, or it would go
|
|
3788
|
+
// on browsing with the cookies and logins of the project it left.
|
|
3789
|
+
if (rekey)
|
|
3790
|
+
await this.browserViews.rekeyProfiles([id]).catch(() => { });
|
|
3791
|
+
return result;
|
|
3792
|
+
}
|
|
3436
3793
|
async deleteSession(params) {
|
|
3437
3794
|
const id = identifier(params.id, 'id');
|
|
3438
3795
|
if (this.run?.sessionId === id || this.startingSession === id || this.starting)
|
|
@@ -3457,7 +3814,18 @@ export class AppServer {
|
|
|
3457
3814
|
return { removed: true };
|
|
3458
3815
|
});
|
|
3459
3816
|
}
|
|
3817
|
+
beginRunTelemetry(params) {
|
|
3818
|
+
const startedAt = new Date().toISOString();
|
|
3819
|
+
// Snapshot before the first await: a pending start can never be upgraded by a later Yes.
|
|
3820
|
+
const lease = telemetryLeaseSnapshot({ home: this.directory, signals: this.telemetry.signals });
|
|
3821
|
+
if (!lease)
|
|
3822
|
+
return Promise.resolve({ startedAt });
|
|
3823
|
+
return beginTelemetryRun({ home: this.directory, signals: this.telemetry.signals, lease, surface: configuredSurface('desktop') }, startedAt, {
|
|
3824
|
+
graphId: typeof params.graph === 'string' ? params.graph : 'default', nodes: 0, subagents: false,
|
|
3825
|
+
}).then(handle => ({ startedAt, handle }), () => ({ startedAt }));
|
|
3826
|
+
}
|
|
3460
3827
|
async startRun(params, internal) {
|
|
3828
|
+
await requireLegalAcceptance(this.directory);
|
|
3461
3829
|
bootMark('run.start.received');
|
|
3462
3830
|
if (this.run || this.starting)
|
|
3463
3831
|
throw new AppServerError('engine-busy', 'This engine is already running a task. Cancel it before starting another.');
|
|
@@ -3493,10 +3861,12 @@ export class AppServer {
|
|
|
3493
3861
|
}
|
|
3494
3862
|
}
|
|
3495
3863
|
async resumeRun(params, internal) {
|
|
3864
|
+
await requireLegalAcceptance(this.directory);
|
|
3496
3865
|
if (this.run || this.starting)
|
|
3497
3866
|
throw new AppServerError('engine-busy', 'This engine is already running a task. Cancel it before starting another.');
|
|
3498
3867
|
if (this.checkout)
|
|
3499
3868
|
throw new AppServerError('busy', 'The working tree is being switched to another branch. Try again when it finishes.');
|
|
3869
|
+
const telemetryStart = this.beginRunTelemetry(params);
|
|
3500
3870
|
const originalRunId = identifier(params.runId, 'runId');
|
|
3501
3871
|
let direction = params.direction === undefined ? undefined : text(params.direction, 'direction', MAX_TASK_CHARS);
|
|
3502
3872
|
// A note rides on a direction the person sent; a resume without one has nothing to carry it.
|
|
@@ -3506,7 +3876,7 @@ export class AppServer {
|
|
|
3506
3876
|
this.assertRunning();
|
|
3507
3877
|
let source;
|
|
3508
3878
|
try {
|
|
3509
|
-
source =
|
|
3879
|
+
source = await readTelemetryRunRecord(this.directory, runRecordPath(this.directory, originalRunId, 'json'), { signals: this.telemetry.signals });
|
|
3510
3880
|
}
|
|
3511
3881
|
catch {
|
|
3512
3882
|
throw new AppServerError('invalid-params', 'There is no saved record for that run, so it cannot be resumed.');
|
|
@@ -3571,10 +3941,14 @@ export class AppServer {
|
|
|
3571
3941
|
}
|
|
3572
3942
|
const rawSelection = typeof source.graphSelection === 'string' ? source.graphSelection : source.graph?.id;
|
|
3573
3943
|
const graphId = rawSelection === 'software-engineer' ? 'default' : rawSelection === 'andorra' ? RETIRED_ANDORRA_SELECTION : rawSelection;
|
|
3944
|
+
if (params.runPermissions !== undefined && params.permissions !== undefined) {
|
|
3945
|
+
throw new AppServerError('invalid-params', 'Choose either runPermissions for this run or permissions for the workspace default.');
|
|
3946
|
+
}
|
|
3947
|
+
const resumeRunPermissions = params.runPermissions === undefined ? undefined : permissionMode(params.runPermissions);
|
|
3574
3948
|
if (!await claimRunResume(this.directory, originalRunId))
|
|
3575
3949
|
throw new AppServerError('busy', 'That run is already being resumed by another engine.');
|
|
3576
|
-
const inheritedPermissions = params.permissions === undefined && isPermissionMode(source.permissions)
|
|
3577
|
-
? source.permissions : undefined;
|
|
3950
|
+
const inheritedPermissions = resumeRunPermissions ?? (params.permissions === undefined && isPermissionMode(source.permissions)
|
|
3951
|
+
? source.permissions : undefined);
|
|
3578
3952
|
const carriedModel = typeof source.model === 'string' && source.model ? source.model : undefined;
|
|
3579
3953
|
const carriedNodeModelOverrides = readNodeModelOverrides(source.nodeModelOverrides);
|
|
3580
3954
|
this.startingSession = sessionId;
|
|
@@ -3587,16 +3961,19 @@ export class AppServer {
|
|
|
3587
3961
|
...(params.model === undefined ? {} : { model: params.model }),
|
|
3588
3962
|
...(source.runInput !== undefined && typeof source.runInput === 'object' && source.runInput !== null ? { input: source.runInput } : {}),
|
|
3589
3963
|
...(source.runState !== undefined && typeof source.runState === 'object' && source.runState !== null ? { state: source.runState } : {}),
|
|
3590
|
-
...(typeof source.reasoningEffort === 'string' && (params.provider === undefined || params.provider === source.provider) ? { reasoningEffort: source.reasoningEffort } : {}),
|
|
3964
|
+
...(params.reasoningEffort !== undefined ? { reasoningEffort: params.reasoningEffort } : typeof source.reasoningEffort === 'string' && (params.provider === undefined || params.provider === source.provider) && (params.model === undefined || params.model === source.model) ? { reasoningEffort: source.reasoningEffort } : {}),
|
|
3591
3965
|
...(params.overrideAllNodes === undefined ? (source.overrideAllNodes === true ? { overrideAllNodes: true } : {}) : { overrideAllNodes: params.overrideAllNodes }),
|
|
3966
|
+
// A resume keeps Auto unless it names its own choice: a pair without autoModel is an explicit pick.
|
|
3967
|
+
...(params.autoModel === true || (params.autoModel === undefined && params.provider === undefined && params.model === undefined && source.autoModel === true) ? { autoModel: true } : {}),
|
|
3592
3968
|
...(params.overrideAllNodes === true || carriedNodeModelOverrides === undefined ? {} : { nodeModelOverrides: carriedNodeModelOverrides }),
|
|
3593
3969
|
...(source.entryHistory === true ? { entryHistory: true } : {}),
|
|
3594
3970
|
...(params.panelBrowserRelay === true ? { panelBrowserRelay: true } : {}),
|
|
3971
|
+
...(params.chatHandoffs === true ? { chatHandoffs: true } : {}),
|
|
3595
3972
|
...(params.relay === undefined ? {} : { relay: params.relay }),
|
|
3596
3973
|
...(params.permissions === undefined ? {} : { permissions: params.permissions }),
|
|
3597
3974
|
...(sentAttachments === undefined ? {} : { attachments: sentAttachments }),
|
|
3598
3975
|
...(note === undefined ? {} : { note }),
|
|
3599
|
-
}, { sameSession: sessionId, resumedFrom: originalRunId, ...(turn?.note ? { priorNote: turn.note } : {}), ...(inheritedPermissions === undefined ? {} : { inheritedPermissions }), ...(direction === undefined ? {} : { direction }), ...(recoveredOwnDirection ? { recoveredDirection: true } : {}), ...(carried.length === 0 ? {} : { carried }), ...(armedRunIds.length === 0 ? {} : { armedRunIds }), ...(resumedAttachments === undefined ? {} : { attachments: resumedAttachments }), ...(carriedModel === undefined || params.model !== undefined || params.provider !== undefined ? {} : { carriedModel }), ...(stoppedTurnAttachments === undefined ? {} : { stoppedTurnAttachments }), ...(params.model === undefined && params.provider === undefined && source.liveModelChanged !== true ? {} : { explicitPair: true }), ...(ownWake === undefined ? {} : { wake: ownWake }), ...(ownWakeNode === undefined ? {} : { wakeNode: ownWakeNode }), ...(internal?.freshAllowance === true ? { freshAllowance: true } : {}), ...(params.compact === true ? { compact: true } : {}) });
|
|
3976
|
+
}, { telemetryStart, sameSession: sessionId, resumedFrom: originalRunId, ...(turn?.note ? { priorNote: turn.note } : {}), ...(inheritedPermissions === undefined ? {} : { inheritedPermissions }), ...(direction === undefined ? {} : { direction }), ...(recoveredOwnDirection ? { recoveredDirection: true } : {}), ...(carried.length === 0 ? {} : { carried }), ...(armedRunIds.length === 0 ? {} : { armedRunIds }), ...(resumedAttachments === undefined ? {} : { attachments: resumedAttachments }), ...(carriedModel === undefined || params.model !== undefined || params.provider !== undefined ? {} : { carriedModel }), ...(stoppedTurnAttachments === undefined ? {} : { stoppedTurnAttachments }), ...(params.model === undefined && params.provider === undefined && source.liveModelChanged !== true ? {} : { explicitPair: true }), ...(ownWake === undefined ? {} : { wake: ownWake }), ...(ownWakeNode === undefined ? {} : { wakeNode: ownWakeNode }), ...(internal?.freshAllowance === true ? { freshAllowance: true } : {}), ...(params.compact === true ? { compact: true } : {}) });
|
|
3600
3977
|
}
|
|
3601
3978
|
catch (error) {
|
|
3602
3979
|
await releaseRunResumeClaim(this.directory, originalRunId);
|
|
@@ -3749,6 +4126,7 @@ export class AppServer {
|
|
|
3749
4126
|
throw new AppServerError('cancelled', 'The engine is shutting down.');
|
|
3750
4127
|
}
|
|
3751
4128
|
async prepareRun(params, internal) {
|
|
4129
|
+
const start = await (internal?.telemetryStart ?? this.beginRunTelemetry(params));
|
|
3752
4130
|
// New work owns the provider from here: abort the title work of the session it is about to use. A
|
|
3753
4131
|
// brand-new session has no title of its own pending, so nothing is cancelled for it, and other
|
|
3754
4132
|
// sessions' titles are left alone — a task started elsewhere never costs them their name.
|
|
@@ -3768,7 +4146,7 @@ export class AppServer {
|
|
|
3768
4146
|
}
|
|
3769
4147
|
}
|
|
3770
4148
|
try {
|
|
3771
|
-
return await this.prepareRunValidated(params, internal, createdSpools);
|
|
4149
|
+
return await this.prepareRunValidated(start, params, internal, createdSpools);
|
|
3772
4150
|
}
|
|
3773
4151
|
catch (error) {
|
|
3774
4152
|
await Promise.all(createdSpools.map(dir => rm(dir, { recursive: true, force: true }).catch(() => { })));
|
|
@@ -3802,7 +4180,7 @@ export class AppServer {
|
|
|
3802
4180
|
}
|
|
3803
4181
|
return applyNodeModelOverrides(bindPortableGraphProviders(prebound, config), nodeModelOverrides);
|
|
3804
4182
|
}
|
|
3805
|
-
async prepareRunValidated(params, internal, createdSpools) {
|
|
4183
|
+
async prepareRunValidated(start, params, internal, createdSpools) {
|
|
3806
4184
|
const root = await workspaceRoot(params.workspace);
|
|
3807
4185
|
this.assertRunning();
|
|
3808
4186
|
const submitted = text(params.task, 'task', MAX_TASK_CHARS);
|
|
@@ -3853,7 +4231,10 @@ export class AppServer {
|
|
|
3853
4231
|
throw new AppServerError('invalid-params', `The ${provider.type} provider does not support a thinking effort`);
|
|
3854
4232
|
const overrideAllNodes = params.overrideAllNodes === true;
|
|
3855
4233
|
const nodeModelOverrides = readNodeModelOverrides(params.nodeModelOverrides);
|
|
3856
|
-
|
|
4234
|
+
// Auto: the provider and model name the starting pair only, so adaptive routing may still choose the run's model.
|
|
4235
|
+
// An override of every node is an explicit choice and wins over it.
|
|
4236
|
+
const autoModel = params.autoModel === true && !overrideAllNodes;
|
|
4237
|
+
const modelPinned = !autoModel && (overrideAllNodes || params.model !== undefined || params.provider !== undefined);
|
|
3857
4238
|
const panelRelay = params.panelBrowserRelay === true;
|
|
3858
4239
|
const entryHistory = params.entryHistory === true;
|
|
3859
4240
|
const runInput = params.input !== undefined && typeof params.input === 'object' && params.input !== null && !Array.isArray(params.input)
|
|
@@ -3868,7 +4249,7 @@ export class AppServer {
|
|
|
3868
4249
|
: internal?.resumedFrom !== undefined ? identifier(params.graph, 'graph') : currentGraphSelection(identifier(params.graph, 'graph'));
|
|
3869
4250
|
if (relay?.graph === undefined && implicit && await this.selectionIsDeleted(selection))
|
|
3870
4251
|
selection = 'default';
|
|
3871
|
-
const requested =
|
|
4252
|
+
const requested = requestedPermissionMode(params.permissions);
|
|
3872
4253
|
if (requested) {
|
|
3873
4254
|
const next = await this.serializeConfig(async () => {
|
|
3874
4255
|
try {
|
|
@@ -3889,8 +4270,22 @@ export class AppServer {
|
|
|
3889
4270
|
throw new AppServerError('busy', folderChangeBusy);
|
|
3890
4271
|
const store = this.store();
|
|
3891
4272
|
let record;
|
|
4273
|
+
let handoffParentId;
|
|
4274
|
+
if (params.handoffParentId !== undefined) {
|
|
4275
|
+
if (params.sessionId !== undefined || params.continueSession === true || params.entryHistory === true || internal?.resumedFrom !== undefined) {
|
|
4276
|
+
throw new AppServerError('invalid-params', 'A chat handoff must start a fresh session');
|
|
4277
|
+
}
|
|
4278
|
+
const origin = await this.readSession(identifier(params.handoffParentId, 'handoffParentId'));
|
|
4279
|
+
if (resolve(origin.workspace) !== root)
|
|
4280
|
+
throw new AppServerError('invalid-params', 'The originating chat belongs to a different project');
|
|
4281
|
+
handoffParentId = origin.id;
|
|
4282
|
+
}
|
|
3892
4283
|
if (params.sessionId === undefined) {
|
|
3893
|
-
|
|
4284
|
+
// The name the session shows at once is the first few words of its first prompt, never the worktree's
|
|
4285
|
+
// temporary id. The same string is kept as the `placeholder`, so a model title (first attempt or a later
|
|
4286
|
+
// retry) can still replace it, while a name the user chose is never overwritten.
|
|
4287
|
+
const name = sessionName(task);
|
|
4288
|
+
record = { version: 1, id: randomUUID(), name, placeholder: name, workspace: root, updatedAt: new Date().toISOString(), history: [], usage: { inputTokens: 0, outputTokens: 0, requests: 0 }, ...(handoffParentId === undefined ? {} : { handoffParentId }) };
|
|
3894
4289
|
}
|
|
3895
4290
|
else if (internal?.sameSession !== undefined) {
|
|
3896
4291
|
const continuedId = identifier(params.sessionId, 'sessionId');
|
|
@@ -3910,7 +4305,7 @@ export class AppServer {
|
|
|
3910
4305
|
// The pin belongs to the task the user pinned; its continuation is listed under it and shares its place.
|
|
3911
4306
|
const { archived: _archived, autoArchived: _autoArchived, pinned: _pinned, ...continued } = existing;
|
|
3912
4307
|
// A continuation is its own task in Needs you: it waits for review once its own turn completes.
|
|
3913
|
-
const { trajectoryId: _parentTrajectory, review: _parentReview, ...forked } = continued;
|
|
4308
|
+
const { trajectoryId: _parentTrajectory, review: _parentReview, handoffParentId: _originalHandoff, ...forked } = continued;
|
|
3914
4309
|
if (!canExtendLineage(existing.ancestors)) {
|
|
3915
4310
|
throw new AppServerError('invalid-params', 'This session has been continued too many times to keep its lineage, so it cannot be continued again. Start a new session instead.');
|
|
3916
4311
|
}
|
|
@@ -3935,6 +4330,9 @@ export class AppServer {
|
|
|
3935
4330
|
throw error;
|
|
3936
4331
|
}
|
|
3937
4332
|
record = { ...record, checkout };
|
|
4333
|
+
// The worktree and its branch keep the `task/<id>` name the start drew them under (renamed to a model
|
|
4334
|
+
// summary later, in nameWorktreeBranch); the session's name stays the prompt's first words set above, so
|
|
4335
|
+
// the rail never shows the temporary worktree id — also when a collision made the start draw a fresh id.
|
|
3938
4336
|
}
|
|
3939
4337
|
else if (record.checkout !== undefined) {
|
|
3940
4338
|
const state = await checkoutState(record.checkout, root);
|
|
@@ -3944,8 +4342,13 @@ export class AppServer {
|
|
|
3944
4342
|
const workRoot = sessionWorkRoot(record);
|
|
3945
4343
|
const controller = new AbortController();
|
|
3946
4344
|
const runId = randomUUID();
|
|
3947
|
-
const
|
|
3948
|
-
const
|
|
4345
|
+
const { startedAt, handle: telemetryHandle } = start;
|
|
4346
|
+
const telemetryAccess = { home: this.directory, signals: this.telemetry.signals, lease: telemetryHandle?.lease };
|
|
4347
|
+
const telemetrySurface = { ...telemetryAccess, surface: configuredSurface('desktop'), config };
|
|
4348
|
+
if (telemetryHandle?.lease && sameTelemetryLease(telemetryHandle.lease, telemetryLeaseSnapshot(telemetryAccess))) {
|
|
4349
|
+
telemetryHandle.workspace = root;
|
|
4350
|
+
telemetryHandle.dimensions = { graphId: selection, nodes: 0, subagents: false, jevEnabled: config.jevEnabled !== false, decisionRouting: config.decisions?.mode ?? 'off', permissionMode: internal?.inheritedPermissions ?? effective };
|
|
4351
|
+
}
|
|
3949
4352
|
const accountSubject = await currentGraphSubject();
|
|
3950
4353
|
const resumedFrom = internal?.resumedFrom;
|
|
3951
4354
|
// A relayed run's graph is bound to the desktop's providers here, before it starts, so a node naming a provider the
|
|
@@ -3991,7 +4394,7 @@ export class AppServer {
|
|
|
3991
4394
|
const attempt = cursor;
|
|
3992
4395
|
cursor = undefined;
|
|
3993
4396
|
try {
|
|
3994
|
-
const value =
|
|
4397
|
+
const value = await readTelemetryRunRecord(this.directory, runRecordPath(this.directory, attempt, 'json'), { signals: this.telemetry.signals });
|
|
3995
4398
|
if (typeof value.resumedFrom === 'string' && value.resumedFrom !== attempt)
|
|
3996
4399
|
cursor = value.resumedFrom;
|
|
3997
4400
|
if (typeof value.toolCalls === 'number' && Number.isFinite(value.toolCalls))
|
|
@@ -4265,7 +4668,7 @@ export class AppServer {
|
|
|
4265
4668
|
openingAttachments = { refs: stoppedRefs, images: await loadResolvedImages(this.directory, root, stoppedRefs) };
|
|
4266
4669
|
}
|
|
4267
4670
|
}
|
|
4268
|
-
lineageArtifacts = new ArtifactStore(runId);
|
|
4671
|
+
lineageArtifacts = new ArtifactStore(runId, this.directory);
|
|
4269
4672
|
for (const attempt of chain)
|
|
4270
4673
|
await lineageArtifacts.importFrom(attempt).catch(() => { });
|
|
4271
4674
|
resumeWarnings = warnings;
|
|
@@ -4293,11 +4696,12 @@ export class AppServer {
|
|
|
4293
4696
|
const openRecord = { id: runId, status: 'running', sessionId: record.id, startedAt, pid: process.pid, graphSelection: selection, graph: { id: selection }, provider: provider.id, model: modelId,
|
|
4294
4697
|
surface: configuredSurface('desktop'),
|
|
4295
4698
|
...(accountSubject ? { accountSubject } : {}),
|
|
4296
|
-
telemetry:
|
|
4699
|
+
telemetry: runTelemetryMetadata(telemetrySurface, telemetryHandle),
|
|
4297
4700
|
...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }), ...(effort === undefined ? autoEffort ? { reasoningEffort: 'auto' } : {} : { reasoningEffort: effort }),
|
|
4298
4701
|
...(automationContext === undefined ? {} : { automationContext }),
|
|
4299
4702
|
...(internal?.inheritedPermissions === undefined ? {} : { permissions: internal.inheritedPermissions }),
|
|
4300
4703
|
...(overrideAllNodes ? { overrideAllNodes: true } : {}),
|
|
4704
|
+
...(autoModel ? { autoModel: true } : {}),
|
|
4301
4705
|
...(nodeModelOverrides === undefined ? {} : { nodeModelOverrides }),
|
|
4302
4706
|
...(entryHistory ? { entryHistory: true } : {}),
|
|
4303
4707
|
// Only the fact is kept: the desktop's provider list never reaches this machine's disk.
|
|
@@ -4309,7 +4713,7 @@ export class AppServer {
|
|
|
4309
4713
|
...(directionNode === undefined ? {} : { directionNode }),
|
|
4310
4714
|
...(armedCarried.length === 0 ? {} : { pendingDirections: armedCarried.map(entry => ({ runId: entry.runId, direction: entry.direction, ...(entry.id === undefined ? {} : { id: entry.id }), ...wakeProvenance(entry.wake, entry.node) })) }) };
|
|
4311
4715
|
bootMark('run.prepare.record-write.start');
|
|
4312
|
-
await writeOpenRunRecord(this.directory, openRecord)
|
|
4716
|
+
await writeOpenRunRecord(this.directory, openRecord, telemetryAccess)
|
|
4313
4717
|
.catch(async (error) => {
|
|
4314
4718
|
this.log('warn', `Could not write the open run record: ${message(error)}`);
|
|
4315
4719
|
await rm(runRecordPath(this.directory, runId, 'json'), { force: true }).catch(() => { });
|
|
@@ -4349,7 +4753,7 @@ export class AppServer {
|
|
|
4349
4753
|
permissionControl.yolo = effective === 'full-access';
|
|
4350
4754
|
this.run = { runId, sessionId: record.id, controller, workspace: root, workRoot, steers: liveSteers, subagents: new Set(), steersClosed: false,
|
|
4351
4755
|
permissionControl, permissionRevision: 0, approvals: new Set(), boundPermissions: internal?.inheritedPermissions !== undefined,
|
|
4352
|
-
codeIntelPermissions: effective, ...(lineage.length === 0 ? {} : { lineage: [...lineage] }), ...(relay === undefined ? {} : { relayProviders: relay.providers }) };
|
|
4756
|
+
telemetryAccess, codeIntelPermissions: effective, ...(lineage.length === 0 ? {} : { lineage: [...lineage] }), ...(relay === undefined ? {} : { relayProviders: relay.providers }) };
|
|
4353
4757
|
{
|
|
4354
4758
|
const continues = new Set([runId, ...lineage]);
|
|
4355
4759
|
for (const timer of this.timers.list(record.id)) {
|
|
@@ -4371,7 +4775,7 @@ export class AppServer {
|
|
|
4371
4775
|
const preparedGraph = resumedGraph ?? relayPrepared;
|
|
4372
4776
|
const invocationText = internal?.resumedFrom === undefined ? task
|
|
4373
4777
|
: internal.recoveredDirection === true || internal.wake !== undefined ? undefined : internal.direction;
|
|
4374
|
-
const runTask = this.executeRun({ runId, startedAt,
|
|
4778
|
+
const runTask = this.executeRun({ runId, startedAt, telemetryHandle, ...(accountSubject ? { accountSubject } : {}), ...(invocationText === undefined ? {} : { invocationText }), task, ...(note === undefined ? {} : { note }), ...(turnNote === undefined ? {} : { turnNote }), selection, providerId: provider.id, modelId, root: workRoot, project: root, permissions: effective, liveSteers, ...(internal?.inheritedPermissions === undefined ? {} : { boundPermissions: internal.inheritedPermissions }), ...(effort === undefined ? {} : { reasoningEffort: effort }), ...(autoEffort ? { autoEffort: true } : {}), ...(overrideAllNodes ? { overrideAllNodes: true } : {}), ...(autoModel ? { autoModel: true } : {}), ...(modelPinned ? { modelPinned: true } : {}), ...(nodeModelOverrides === undefined ? {} : { nodeModelOverrides }), ...(panelRelay ? { panelBrowserRelay: true } : {}), chatHandoffs: params.chatHandoffs === true, ...(entryHistory ? { entryHistory: true } : {}), ...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }), ...(automationContext === undefined ? {} : { automationContext }), ...(resumedDirection === undefined ? {} : { direction: resumedDirection }), ...(wake === undefined ? {} : { wake }), ...(directionNode === undefined ? {} : { directionNode }), ...(internal?.startNode === undefined ? {} : { startNode: internal.startNode }), ...(armedCarried.length === 0 ? {} : { carriedDirections: armedCarried, pendingDirections: armedCarried.map(entry => ({ runId: entry.runId, direction: entry.direction, ...(entry.id === undefined ? {} : { id: entry.id }), ...wakeProvenance(entry.wake, entry.node) })) }), ownDirectionId: `${runId}#own`, ...(seedExclusions.length === 0 ? {} : { armedRunIds: seedExclusions }), ...(openingAttachments === undefined ? {} : { openingAttachments }), record, controller, ...(attachments === undefined ? {} : { attachments }), ...(internal?.resumedFrom === undefined ? {} : { resumedFrom: internal.resumedFrom }), ...(resumeFrom === undefined ? {} : { resumeFrom }), lineage, ...(lineageArtifacts === undefined ? {} : { lineageArtifacts }), ...(preparedGraph === undefined ? {} : { prepared: preparedGraph }), ...(relay === undefined ? {} : { relayProviders: relay.providers }), ...(relay?.graph === undefined ? {} : { relayedGraph: true }) })
|
|
4375
4779
|
.catch(error => this.log('error', `Run ${runId} failed: ${message(error)}`));
|
|
4376
4780
|
this.runTask = runTask;
|
|
4377
4781
|
runTask.finally(() => {
|
|
@@ -4397,7 +4801,12 @@ export class AppServer {
|
|
|
4397
4801
|
.then(async (summary) => {
|
|
4398
4802
|
// No name landed: the run was refused, the request was cut short by new work, it failed, or the save
|
|
4399
4803
|
// had to step aside. The retry asks again later instead of keeping the prompt's first words forever.
|
|
4400
|
-
if (!summary || controller.signal.aborted
|
|
4804
|
+
if (!summary || controller.signal.aborted) {
|
|
4805
|
+
this.scheduleTitleRetry(record.id, task, provider, modelId, 0);
|
|
4806
|
+
return;
|
|
4807
|
+
}
|
|
4808
|
+
this.nameWorktreeBranchTracked(record.id, task, provider, modelId);
|
|
4809
|
+
if (record.renamed === true) {
|
|
4401
4810
|
this.scheduleTitleRetry(record.id, task, provider, modelId, 0);
|
|
4402
4811
|
return;
|
|
4403
4812
|
}
|
|
@@ -4444,6 +4853,86 @@ export class AppServer {
|
|
|
4444
4853
|
return 'saved';
|
|
4445
4854
|
});
|
|
4446
4855
|
}
|
|
4856
|
+
/**
|
|
4857
|
+
* Names a new task's branch from a model summary of the task (`task/fix-login-redirect-loop`), replacing the random
|
|
4858
|
+
* id the start gave it. Runs once the run has answered once, beside the title work. Any failure keeps the random
|
|
4859
|
+
* id: the branch name is a nicety, never worth a retry of its own.
|
|
4860
|
+
*/
|
|
4861
|
+
async nameWorktreeBranch(recordId, task, provider, modelId) {
|
|
4862
|
+
const controller = new AbortController();
|
|
4863
|
+
this.operations.add(controller);
|
|
4864
|
+
try {
|
|
4865
|
+
if (!titleRequestSupported(provider))
|
|
4866
|
+
return;
|
|
4867
|
+
// A retry path can land here after the branch was named: skip the request when it no longer carries the start's name.
|
|
4868
|
+
const prior = await this.readSession(recordId).catch(() => undefined);
|
|
4869
|
+
if (!prior?.checkout || !isAutoTaskBranch(prior.checkout.branch))
|
|
4870
|
+
return;
|
|
4871
|
+
const name = await summarizeTaskBranch(task, createAdapter(provider), modelId, controller.signal);
|
|
4872
|
+
if (!name || this.closed)
|
|
4873
|
+
return;
|
|
4874
|
+
await this.withSessionMutation(recordId, async () => {
|
|
4875
|
+
const fresh = await this.readSession(recordId).catch(() => undefined);
|
|
4876
|
+
if (!fresh?.checkout)
|
|
4877
|
+
return;
|
|
4878
|
+
const branch = await renameTaskBranch(fresh.checkout, name);
|
|
4879
|
+
if (!branch || branch === fresh.checkout.branch)
|
|
4880
|
+
return;
|
|
4881
|
+
try {
|
|
4882
|
+
const updated = { ...fresh, checkout: { ...fresh.checkout, branch } };
|
|
4883
|
+
await this.store().save(savedSessionFields(updated));
|
|
4884
|
+
this.emit('session.updated', { session: this.summary(updated) });
|
|
4885
|
+
}
|
|
4886
|
+
catch (error) {
|
|
4887
|
+
// Git already moved the branch; with the record left behind the two would disagree for good, and a
|
|
4888
|
+
// later naming attempt could no longer repair it (the recorded branch no longer matches HEAD). Put the
|
|
4889
|
+
// branch back under its recorded name, so record and repository agree and the rename can be retried.
|
|
4890
|
+
await revertTaskBranchRename(fresh.checkout, branch, fresh.checkout.branch).catch(() => { });
|
|
4891
|
+
throw error;
|
|
4892
|
+
}
|
|
4893
|
+
// A continuation started while this request was pending copied the automatic branch over. Every record
|
|
4894
|
+
// still sharing that worktree under the old name moves with it, so its commands and worktree recovery
|
|
4895
|
+
// point at the branch that holds the task's work. Each sibling is locked, reread and revalidated under
|
|
4896
|
+
// its own lock, so a turn that completes meanwhile is never overwritten with this stale snapshot.
|
|
4897
|
+
const worktree = resolve(fresh.checkout.path);
|
|
4898
|
+
const oldBranch = fresh.checkout.branch;
|
|
4899
|
+
const siblings = (await this.store().list(fresh.workspace)).filter(other => other.id !== fresh.id
|
|
4900
|
+
&& other.checkout?.kind === 'worktree' && other.checkout.removedAt === undefined
|
|
4901
|
+
&& other.checkout.branch === oldBranch && resolve(other.checkout.path) === worktree);
|
|
4902
|
+
for (const sibling of siblings) {
|
|
4903
|
+
// A sibling's lock is only held briefly by ordinary saves. Retry a busy lock instead of skipping it:
|
|
4904
|
+
// a skipped sibling would keep pointing at a ref the rename just removed (checkoutState never refreshes
|
|
4905
|
+
// the branch), which breaks its commands and its worktree recovery.
|
|
4906
|
+
for (let attempt = 0; attempt < MAX_SIBLING_LOCK_TRIES && !this.closed; attempt++) {
|
|
4907
|
+
try {
|
|
4908
|
+
await this.withSessionMutation(sibling.id, async () => {
|
|
4909
|
+
const shared = await this.readSession(sibling.id).catch(() => undefined);
|
|
4910
|
+
if (!shared || shared.checkout?.kind !== 'worktree' || shared.checkout.removedAt !== undefined
|
|
4911
|
+
|| shared.checkout.branch !== oldBranch || resolve(shared.checkout.path) !== worktree)
|
|
4912
|
+
return;
|
|
4913
|
+
const update = { ...shared, checkout: { ...shared.checkout, branch } };
|
|
4914
|
+
await this.store().save(savedSessionFields(update));
|
|
4915
|
+
this.emit('session.updated', { session: this.summary(update) });
|
|
4916
|
+
});
|
|
4917
|
+
break;
|
|
4918
|
+
}
|
|
4919
|
+
catch {
|
|
4920
|
+
await new Promise(resolve => { const timer = setTimeout(resolve, SIBLING_LOCK_RETRY_MS); timer.unref?.(); });
|
|
4921
|
+
}
|
|
4922
|
+
}
|
|
4923
|
+
}
|
|
4924
|
+
});
|
|
4925
|
+
}
|
|
4926
|
+
catch { /* A failed or refused name keeps the random id the task started under. */ }
|
|
4927
|
+
finally {
|
|
4928
|
+
this.operations.delete(controller);
|
|
4929
|
+
}
|
|
4930
|
+
}
|
|
4931
|
+
nameWorktreeBranchTracked(recordId, task, provider, modelId) {
|
|
4932
|
+
const pending = this.nameWorktreeBranch(recordId, task, provider, modelId).catch(() => { });
|
|
4933
|
+
this.requests.add(pending);
|
|
4934
|
+
pending.finally(() => { this.requests.delete(pending); });
|
|
4935
|
+
}
|
|
4447
4936
|
/** A title that never landed waits and asks again, so one busy moment does not leave the session with its prompt's first words. */
|
|
4448
4937
|
scheduleTitleRetry(sessionId, task, provider, modelId, attempt, deferrals = 0) {
|
|
4449
4938
|
if (this.closed || !titleRequestSupported(provider))
|
|
@@ -4475,7 +4964,7 @@ export class AppServer {
|
|
|
4475
4964
|
return;
|
|
4476
4965
|
const fresh = await this.readSession(sessionId).catch(() => undefined);
|
|
4477
4966
|
// Deleted, renamed by the user, or already carrying a real name: nothing left to do.
|
|
4478
|
-
if (!fresh || fresh.renamed === true || fresh.name !== sessionName(task))
|
|
4967
|
+
if (!fresh || fresh.renamed === true || fresh.name !== (fresh.placeholder ?? sessionName(task)))
|
|
4479
4968
|
return;
|
|
4480
4969
|
// A run is working on the session, so the save would step aside anyway. Step back without
|
|
4481
4970
|
// spending one of the bounded attempts: the title is not lost, it is just not this minute's.
|
|
@@ -4495,6 +4984,7 @@ export class AppServer {
|
|
|
4495
4984
|
this.scheduleTitleRetry(sessionId, task, provider, modelId, attempt + 1);
|
|
4496
4985
|
return;
|
|
4497
4986
|
}
|
|
4987
|
+
this.nameWorktreeBranchTracked(sessionId, task, provider, modelId);
|
|
4498
4988
|
const outcome = await this.saveSessionTitle(sessionId, undefined, summary);
|
|
4499
4989
|
if (outcome === 'busy' && pending.deferrals < MAX_TITLE_RETRY_DEFERRALS) {
|
|
4500
4990
|
// The name was made but the session was claimed meanwhile: stand back, spend nothing.
|
|
@@ -4544,8 +5034,9 @@ export class AppServer {
|
|
|
4544
5034
|
this.titleRetries.clear();
|
|
4545
5035
|
}
|
|
4546
5036
|
async executeRun(input) {
|
|
4547
|
-
const { runId, startedAt,
|
|
5037
|
+
const { runId, startedAt, telemetryHandle, accountSubject, task, note, turnNote, selection, providerId, modelId, root, project, permissions, liveSteers, boundPermissions, reasoningEffort, autoEffort = false, overrideAllNodes = false, autoModel = false, modelPinned = overrideAllNodes, panelBrowserRelay = false, entryHistory = false, runInput, runState, automationContext, direction, wake, carriedDirections, ownDirectionId, armedRunIds, pendingDirections, directionNode, startNode, controller, attachments, openingAttachments, resumedFrom, resumeFrom, lineage, lineageArtifacts, prepared, nodeModelOverrides } = input;
|
|
4548
5038
|
const signal = controller.signal;
|
|
5039
|
+
const telemetryAccess = { home: this.directory, signals: this.telemetry.signals, lease: telemetryHandle?.lease };
|
|
4549
5040
|
const turnObservations = [];
|
|
4550
5041
|
const turnEdits = [];
|
|
4551
5042
|
const panelHold = createPanelBrowserHold(this.browserViews, input.record.id, panelBrowserRelay ? this.panelBrowserRelayFor(input.record.id) : undefined);
|
|
@@ -4560,7 +5051,7 @@ export class AppServer {
|
|
|
4560
5051
|
...(meta?.generation === undefined ? {} : { generation: meta.generation }),
|
|
4561
5052
|
...(meta?.provider === undefined ? {} : { provider: meta.provider }), ...(meta?.model === undefined ? {} : { model: meta.model }),
|
|
4562
5053
|
...(meta?.routedFrom === undefined ? {} : { routedFrom: meta.routedFrom }),
|
|
4563
|
-
...(deliveredIds.size === 0 ? {} : { steeringDelivered: [...deliveredIds] }) }))
|
|
5054
|
+
...(deliveredIds.size === 0 ? {} : { steeringDelivered: [...deliveredIds] }) }, telemetryAccess))
|
|
4564
5055
|
.then(() => checkpointHealth.succeeded({ nodeId, generation: meta?.generation }), async (error) => {
|
|
4565
5056
|
await checkpointHealth.failed({ nodeId, generation: meta?.generation }, error);
|
|
4566
5057
|
this.log('warn', `Could not write the run checkpoint: ${message(error)}`);
|
|
@@ -4578,7 +5069,7 @@ export class AppServer {
|
|
|
4578
5069
|
let localCacheInputTokens = 0;
|
|
4579
5070
|
let localCacheReadTokens = 0;
|
|
4580
5071
|
const probeUsage = { requests: 0, inputTokens: 0, outputTokens: 0 };
|
|
4581
|
-
const
|
|
5072
|
+
const probeCapture = createRunTelemetry(telemetryAccess);
|
|
4582
5073
|
// Set by the first model request this run sends to an Andorra provider (the health probe's included): the
|
|
4583
5074
|
// hosted usage is asked for again when such a run ends.
|
|
4584
5075
|
let askedAndorra = false;
|
|
@@ -4625,7 +5116,6 @@ export class AppServer {
|
|
|
4625
5116
|
let result;
|
|
4626
5117
|
let failure;
|
|
4627
5118
|
let runConfig;
|
|
4628
|
-
let telemetryHandle;
|
|
4629
5119
|
let telemetryFinished = false;
|
|
4630
5120
|
let telemetryStart = Promise.resolve();
|
|
4631
5121
|
let healthProviderFailed = false;
|
|
@@ -4634,38 +5124,27 @@ export class AppServer {
|
|
|
4634
5124
|
let codeIntelSettled = Promise.resolve();
|
|
4635
5125
|
let mcpTeardown = Promise.resolve();
|
|
4636
5126
|
const telemetrySurfaceFor = (config) => ({
|
|
4637
|
-
|
|
5127
|
+
...telemetryAccess, ...(config === undefined ? {} : { config }),
|
|
4638
5128
|
...(accountSubject === undefined ? {} : { subject: accountSubject }), surface: configuredSurface('desktop'),
|
|
4639
5129
|
});
|
|
4640
5130
|
const trackTelemetry = (work) => {
|
|
4641
5131
|
this.telemetrySettle = this.telemetrySettle.then(() => work).catch(() => { });
|
|
4642
5132
|
};
|
|
4643
5133
|
const settleTelemetry = (status, reason) => {
|
|
4644
|
-
if (telemetryFinished)
|
|
5134
|
+
if (telemetryFinished || !telemetryHandle)
|
|
4645
5135
|
return;
|
|
4646
|
-
|
|
4647
|
-
|
|
4648
|
-
|
|
4649
|
-
}, project);
|
|
4650
|
-
const placeholder = telemetryHandle;
|
|
4651
|
-
telemetryStart = reportRunStarted(telemetrySurfaceFor(runConfig), placeholder).catch(() => { });
|
|
4652
|
-
}
|
|
5136
|
+
// Setup failure still uses the original admitted handle, never a new finish-time lease.
|
|
5137
|
+
if (telemetryHandle.started === undefined)
|
|
5138
|
+
telemetryStart = reportRunStarted(telemetrySurfaceFor(runConfig), telemetryHandle).catch(() => { });
|
|
4653
5139
|
telemetryFinished = true;
|
|
4654
|
-
const finishedTelemetry = result?.telemetry ?? createRunTelemetry();
|
|
4655
|
-
|
|
4656
|
-
const provider = runConfig?.providers.find(item => item.id === probe.provider);
|
|
4657
|
-
recordModelUse(finishedTelemetry, {
|
|
4658
|
-
...(provider === undefined ? {} : { providerType: provider.type, baseUrl: provider.baseUrl }),
|
|
4659
|
-
model: probe.model, role: 'other', usage: probe.usage,
|
|
4660
|
-
...(provider === undefined ? {} : { pricing: pricingFor(runConfig?.efficiency?.adaptiveRouting, probe.provider, probe.model) }),
|
|
4661
|
-
});
|
|
4662
|
-
}
|
|
5140
|
+
const finishedTelemetry = result?.telemetry ?? createRunTelemetry(telemetryAccess);
|
|
5141
|
+
mergeRunTelemetry(finishedTelemetry, probeCapture);
|
|
4663
5142
|
trackTelemetry(telemetryStart.then(() => reportRunFinished(telemetrySurfaceFor(runConfig), telemetryHandle, {
|
|
4664
5143
|
status, reason,
|
|
4665
5144
|
...(result?.providerRequestFailed || healthProviderFailed ? { providerRequestFailed: true } : {}),
|
|
4666
5145
|
...(result?.providerOverflow ? { providerOverflow: true } : {}),
|
|
4667
5146
|
...(result?.failureCode === undefined ? {} : { errorCode: result.failureCode }),
|
|
4668
|
-
...(
|
|
5147
|
+
...(hasRunTelemetry(finishedTelemetry) ? { telemetry: finishedTelemetry } : {}),
|
|
4669
5148
|
...(result?.toolCalls === undefined ? {} : { toolCalls: result.toolCalls }),
|
|
4670
5149
|
})));
|
|
4671
5150
|
};
|
|
@@ -4675,7 +5154,7 @@ export class AppServer {
|
|
|
4675
5154
|
const config = input.relayProviders === undefined ? saved : withRelayedProviders(saved, input.relayProviders);
|
|
4676
5155
|
bootMark('run.exec.config-loaded');
|
|
4677
5156
|
runConfig = config;
|
|
4678
|
-
if (archive.length === 0)
|
|
5157
|
+
if (archive.length === 0 && telemetryHandle?.lease)
|
|
4679
5158
|
trackTelemetry(reportSessionStarted({ ...telemetrySurfaceFor(config), workspace: project }));
|
|
4680
5159
|
const provider = config.providers.find(item => item.id === providerId);
|
|
4681
5160
|
if (!provider)
|
|
@@ -4696,22 +5175,20 @@ export class AppServer {
|
|
|
4696
5175
|
liveRun.modelGraph = graph;
|
|
4697
5176
|
liveRun.originalModelGraph = this.originalModelGraphs.get(graph) ?? structuredClone(graph);
|
|
4698
5177
|
}
|
|
4699
|
-
|
|
4700
|
-
graphId: selection, ...graphShape(graph), permissionMode: boundPermissions ?? permissions,
|
|
4701
|
-
|
|
4702
|
-
|
|
4703
|
-
|
|
4704
|
-
telemetryStart = reportRunStarted(telemetrySurfaceFor(config), startedHandle).catch(() => { });
|
|
5178
|
+
if (telemetryHandle?.lease && sameTelemetryLease(telemetryHandle.lease, telemetryLeaseSnapshot(telemetryAccess))) {
|
|
5179
|
+
telemetryHandle.dimensions = { graphId: selection, ...graphShape(graph), permissionMode: boundPermissions ?? permissions,
|
|
5180
|
+
jevEnabled: config.jevEnabled !== false && input.record.jevEnabled !== false, decisionRouting: config.decisions?.mode ?? 'off' };
|
|
5181
|
+
telemetryStart = reportRunStarted(telemetrySurfaceFor(config), telemetryHandle).catch(() => { });
|
|
5182
|
+
}
|
|
4705
5183
|
await telemetryStart;
|
|
4706
5184
|
bootMark('run.exec.telemetry-start.queued');
|
|
4707
5185
|
try {
|
|
4708
5186
|
const stamp = async () => {
|
|
4709
5187
|
const path = runRecordPath(this.directory, runId, 'json');
|
|
4710
|
-
const existing =
|
|
4711
|
-
|
|
4712
|
-
|
|
4713
|
-
|
|
4714
|
-
await writeOpenRunRecord(this.directory, existing);
|
|
5188
|
+
const existing = await readTelemetryRunRecord(this.directory, path, this.run?.telemetryAccess);
|
|
5189
|
+
if (existing.status === 'running') {
|
|
5190
|
+
existing.telemetry = runTelemetryMetadata(telemetrySurfaceFor(config), telemetryHandle);
|
|
5191
|
+
await writeOpenRunRecord(this.directory, existing, telemetryAccess);
|
|
4715
5192
|
}
|
|
4716
5193
|
};
|
|
4717
5194
|
if (liveRun)
|
|
@@ -4735,14 +5212,10 @@ export class AppServer {
|
|
|
4735
5212
|
onUsage: (delta, reference) => {
|
|
4736
5213
|
foldUsage(probeUsage, delta);
|
|
4737
5214
|
foldUsage(runUsage, delta);
|
|
4738
|
-
const
|
|
4739
|
-
|
|
4740
|
-
|
|
4741
|
-
|
|
4742
|
-
if (typeof value === 'number')
|
|
4743
|
-
entry.usage[field] = (entry.usage[field] ?? 0) + value;
|
|
4744
|
-
}
|
|
4745
|
-
probeModels.set(key, entry);
|
|
5215
|
+
const provider = config.providers.find(item => item.id === reference.provider);
|
|
5216
|
+
recordModelUse(probeCapture, { ...(provider ? { providerType: provider.type, baseUrl: provider.baseUrl } : {}),
|
|
5217
|
+
model: reference.model, role: 'other', usage: delta,
|
|
5218
|
+
pricing: pricingFor(config.efficiency?.adaptiveRouting, reference.provider, reference.model) });
|
|
4746
5219
|
},
|
|
4747
5220
|
createAdapter: provider => watchAndorra(provider.type, this.tracedAdapter(createAdapter(provider), provider.id)),
|
|
4748
5221
|
andorra: () => this.hosted.gate(),
|
|
@@ -4814,6 +5287,7 @@ export class AppServer {
|
|
|
4814
5287
|
// A run on Auto thinking hands Auto to the runs its wakes start, as it hands a fixed level.
|
|
4815
5288
|
...(reasoningEffort === undefined ? autoEffort ? { reasoningEffort: 'auto' } : {} : { reasoningEffort }),
|
|
4816
5289
|
...(overrideAllNodes ? { overrideAllNodes: true } : {}),
|
|
5290
|
+
...(autoModel ? { autoModel: true } : {}),
|
|
4817
5291
|
...(panelBrowserRelay ? { panelBrowserRelay: true } : {}),
|
|
4818
5292
|
...(input.relayProviders === undefined ? {} : { relayed: true }),
|
|
4819
5293
|
...(runInput === undefined ? {} : { input: runInput }),
|
|
@@ -4844,7 +5318,8 @@ export class AppServer {
|
|
|
4844
5318
|
...(liveRun ? { runControl: liveRun.permissionControl } : {}),
|
|
4845
5319
|
attachmentRoots,
|
|
4846
5320
|
approve: (name, args, toolSignal) => this.approve(runId, name, args, toolSignal),
|
|
4847
|
-
|
|
5321
|
+
chatHandoffs: input.chatHandoffs === true,
|
|
5322
|
+
askUser: (question, toolSignal, choices, handoff) => this.ask(runId, question, choices, toolSignal, handoff),
|
|
4848
5323
|
...(liveRun ? { approvePlan: () => this.approvePlan(liveRun) } : {}),
|
|
4849
5324
|
onApprovalEvent: (type, data) => {
|
|
4850
5325
|
const event = { type, time: new Date().toISOString(), data };
|
|
@@ -4860,7 +5335,6 @@ export class AppServer {
|
|
|
4860
5335
|
},
|
|
4861
5336
|
timers: this.timers, sessionScope: input.record.id, sessionId: input.record.id, wakesArmed, automationDirectory: this.directory,
|
|
4862
5337
|
wakeCarry,
|
|
4863
|
-
pullRequests: this.pullRequestControl(input.record.id, wakeCarry),
|
|
4864
5338
|
fileChanges: notingEdits(this.sessionChanges.recorder(input.record.id, root, changes => this.emitSessionChanges(changes), error => this.log('warn', `Could not record a file change for review: ${message(error)}`), () => livePermissionMode(toolContext) !== 'full-access'), turnEdits),
|
|
4865
5339
|
observeCommand,
|
|
4866
5340
|
};
|
|
@@ -4885,11 +5359,18 @@ export class AppServer {
|
|
|
4885
5359
|
if (codeIntel && liveRun)
|
|
4886
5360
|
await this.syncCodeIntelPermissions(liveRun).catch(error => this.log('warn', `Could not bring code intelligence to the run's mode: ${message(error)}`));
|
|
4887
5361
|
bootMark('run.exec.code-intel.ready');
|
|
4888
|
-
const
|
|
5362
|
+
const jevWanted = config.jevEnabled !== false && input.record.jevEnabled !== false;
|
|
5363
|
+
// Only a run with JEV on asks the signed-out switch; a disabled run stays network-free.
|
|
5364
|
+
const membership = jevWanted ? await withAnonymousJev(await membershipRead, signal, this.directory) : await membershipRead;
|
|
4889
5365
|
bootMark('run.exec.membership.read');
|
|
5366
|
+
const decisionPolicy = hostedDecisionPolicy(membership, jevWanted, config.decisions);
|
|
5367
|
+
toolContext.pullRequests = this.pullRequestControl(input.record.id, wakeCarry, (body, origin, invocationId, classifySignal) => origin !== undefined && graph.nodes[origin.nodeId]?.jevEnabled === true
|
|
5368
|
+
? decisionPolicy.decisionManager.classifyPullRequestComment(body, { ...origin, invocationId }, classifySignal, event => this.recordRunEvent(runId, event))
|
|
5369
|
+
: Promise.resolve(undefined));
|
|
4890
5370
|
await healthGate;
|
|
4891
5371
|
runGoal = input.record.goal?.status === 'active' ? input.record.goal : undefined;
|
|
4892
5372
|
const options = {
|
|
5373
|
+
telemetry: telemetryHandle?.lease ? telemetryAccess : false,
|
|
4893
5374
|
task: note && direction === undefined ? `${task}\n\n${note}` : task, runId, provider: provider.id, model: snapshot.model, adapter: watchAndorra(provider.type, this.tracedAdapter(this.reasoningAdapter(this.adapterFor(snapshot, { sessionId: input.record.id, runId })), provider.id)),
|
|
4894
5375
|
...(openingAttachments === undefined ? {} : { attachments: openingAttachments }),
|
|
4895
5376
|
...(snapshot.contextWindow === undefined ? {} : { contextWindow: snapshot.contextWindow }),
|
|
@@ -4900,18 +5381,19 @@ export class AppServer {
|
|
|
4900
5381
|
instructions: `${await loadWorkspaceInstructions(root, signal, systemPromptOverrideFor(graph, config.systemPromptOverride))}${extension.instructions}${worktreeInstructions(input.record.checkout)}`,
|
|
4901
5382
|
codeIntel, todoStore: new TodoStore(), ...(commandMemory ? { commandMemory } : {}), ...(projectMemory ? { projectMemory } : {}),
|
|
4902
5383
|
limits: resolveConfiguredLimits(config),
|
|
4903
|
-
...
|
|
5384
|
+
...decisionPolicy,
|
|
4904
5385
|
...(config.efficiency ? { efficiency: config.efficiency } : {}),
|
|
4905
5386
|
...(runGoal ? { goalCompletionVerification: { goal: runGoal.text } } : {}),
|
|
4906
5387
|
modelPinned: modelPinned || overrideAllNodes,
|
|
4907
5388
|
...(entryHistory ? { entryHistory: true } : {}),
|
|
4908
5389
|
...(startNode === undefined ? {} : { startNode }),
|
|
4909
|
-
configuredModels: config.providers.map(item => ({ id: item.id, model: item.model, ...(item.models ? { models: [...item.models] } : {}) })),
|
|
5390
|
+
configuredModels: config.providers.map(item => ({ id: item.id, type: item.type, model: item.model, ...(item.models ? { models: [...item.models] } : {}) })),
|
|
5391
|
+
...(config.efficiency?.adaptiveRouting?.strategy === 'pool' ? { quotaReadings: poolUsageReader(config, () => this.hosted.usage()) } : {}),
|
|
4910
5392
|
resolveModel: (id, model, modelSignal, levelled) => this.resolveModel(config, id, model, modelSignal, levelled ?? (id === provider.id && (model === undefined || model === modelId) ? reasoningEffort : undefined), input.record.id).then(watchResolved),
|
|
4911
5393
|
...(autoEffort ? { sessionEffortAuto: true } : {}),
|
|
4912
5394
|
thinkingLevels: (id, model, forAuto) => (forAuto ? autoLevels : enabledLevels)(config.providers.find(item => item.id === id), model),
|
|
4913
5395
|
resolveProvider: id => watchResolved(this.resolveProvider(config, id, input.record.id)),
|
|
4914
|
-
getLiveModel: async (nodeId, fallbackProvider, fallbackModel, modelSignal) => {
|
|
5396
|
+
getLiveModel: async (nodeId, fallbackProvider, fallbackModel, modelSignal, appliedRevision, hints) => {
|
|
4915
5397
|
while (true) {
|
|
4916
5398
|
const current = liveRun?.modelSelection;
|
|
4917
5399
|
if (!current)
|
|
@@ -4921,20 +5403,27 @@ export class AppServer {
|
|
|
4921
5403
|
return undefined;
|
|
4922
5404
|
const targetProvider = target.provider, targetModel = target.model;
|
|
4923
5405
|
const effectiveModel = targetModel ?? current.config.providers.find(item => item.id === targetProvider)?.model;
|
|
4924
|
-
|
|
4925
|
-
|
|
5406
|
+
const scope = nodeId?.split('/')[0]?.replace(/#fallback$/, '');
|
|
5407
|
+
const nodeOverride = scope === undefined ? undefined : current.nodeOverrides?.[scope];
|
|
4926
5408
|
const onSessionModel = targetProvider === current.provider && effectiveModel === current.model;
|
|
4927
|
-
const
|
|
5409
|
+
const onNodeModel = nodeOverride?.provider === targetProvider && nodeOverride.model === effectiveModel;
|
|
5410
|
+
const appliesSelection = onNodeModel || (!current.nodeOnly && onSessionModel);
|
|
5411
|
+
if (targetProvider === fallbackProvider && effectiveModel === fallbackModel && (!appliesSelection || appliedRevision === current.revision))
|
|
5412
|
+
return undefined;
|
|
5413
|
+
const selectedEffort = onNodeModel ? nodeOverride.reasoningEffort : onSessionModel
|
|
5414
|
+
? current.autoEffort ? 'auto' : current.reasoningEffort : undefined;
|
|
4928
5415
|
// A level switched off for the replacement model is never sent, whether it is the run's or the provider's
|
|
4929
5416
|
// saved one. The runtime installs this adapter mid-attempt, past the attempt-start check.
|
|
4930
5417
|
const liveProvider = current.config.providers.find(item => item.id === targetProvider);
|
|
4931
5418
|
const saved = selectedEffort ?? (effectiveModel === liveProvider?.model ? liveProvider?.reasoningEffort : undefined);
|
|
4932
5419
|
const allowed = effectiveModel === undefined ? [] : enabledLevels(liveProvider, effectiveModel);
|
|
4933
|
-
const liveEffort = saved ===
|
|
5420
|
+
const liveEffort = saved === 'auto'
|
|
5421
|
+
? effectiveModel === undefined ? undefined : decideEffort({ task, levels: autoLevels(liveProvider, effectiveModel), hints, fallback: effectiveModel === liveProvider?.model ? liveProvider?.reasoningEffort : undefined }).level
|
|
5422
|
+
: saved === undefined || allowed.length === 0 ? (selectedEffort === 'auto' ? undefined : selectedEffort) : nearestEnabled(allowed, saved);
|
|
4934
5423
|
const resolved = watchResolved(await this.resolveModel(current.config, targetProvider, targetModel, modelSignal, liveEffort, input.record.id));
|
|
4935
5424
|
if (liveRun?.modelSelection !== current)
|
|
4936
5425
|
continue;
|
|
4937
|
-
return { ...resolved, provider: targetProvider, ...(onSessionModel ? { sessionModel: true } : {}) };
|
|
5426
|
+
return { ...resolved, provider: targetProvider, selectionRevision: current.revision, ...(onSessionModel ? { sessionModel: true } : {}) };
|
|
4938
5427
|
}
|
|
4939
5428
|
},
|
|
4940
5429
|
context: toolContext,
|
|
@@ -5038,7 +5527,7 @@ export class AppServer {
|
|
|
5038
5527
|
return [...directed, ...own].map(entry => ({ role: 'user', content: entry.content, ...(entry.images.length ? { images: entry.images } : {}) }));
|
|
5039
5528
|
},
|
|
5040
5529
|
...(resumeFrom === undefined ? {} : { resumeFrom }),
|
|
5041
|
-
|
|
5530
|
+
artifactStore: lineageArtifacts ?? new ArtifactStore(runId, this.directory),
|
|
5042
5531
|
reviewNode: this.reviewNodeService(input.record.id, runId, input.resumedFrom, () => liveSteers.filter(entry => entry.wake === undefined && entry.subagentId === undefined).map(entry => entry.id)),
|
|
5043
5532
|
};
|
|
5044
5533
|
bootMark('run.exec.options-built');
|
|
@@ -5154,6 +5643,9 @@ export class AppServer {
|
|
|
5154
5643
|
...((liveRun?.modelSelection ? liveRun.modelSelection.reasoningEffort : reasoningEffort) === undefined
|
|
5155
5644
|
? ((liveRun?.modelSelection ? liveRun.modelSelection.autoEffort === true : autoEffort) ? { reasoningEffort: 'auto' } : {}) : { reasoningEffort: liveRun?.modelSelection ? liveRun.modelSelection.reasoningEffort : reasoningEffort }),
|
|
5156
5645
|
...((liveRun?.modelSelection?.overrideAllNodes ?? overrideAllNodes) ? { overrideAllNodes: true } : {}),
|
|
5646
|
+
// A model picked for the whole run while it was live is an explicit choice, so the run is no longer on Auto.
|
|
5647
|
+
// A pick for one node leaves the rest of the run on Auto.
|
|
5648
|
+
...(autoModel && (!liveRun?.modelSelection || liveRun?.modelSelection?.nodeOnly === true) ? { autoModel: true } : {}),
|
|
5157
5649
|
...((liveNodeOverrides !== undefined && Object.keys(liveNodeOverrides).length > 0)
|
|
5158
5650
|
? { nodeModelOverrides: liveNodeOverrides } : {}),
|
|
5159
5651
|
...(entryHistory ? { entryHistory: true } : {}),
|
|
@@ -5166,8 +5658,8 @@ export class AppServer {
|
|
|
5166
5658
|
...(resumedFrom === undefined ? {} : { resumedFrom }),
|
|
5167
5659
|
...(journalIntact ? {} : { journalIntegrity: 'failed' }),
|
|
5168
5660
|
...(checkpointHealth.intact ? {} : { checkpointIntegrity: 'failed', checkpointFailures: checkpointHealth.failures }),
|
|
5169
|
-
...(boundPermissions === undefined ? {} : { permissions: liveRun?.permissionControl.permissions ?? boundPermissions }) };
|
|
5170
|
-
const writeFinal = () =>
|
|
5661
|
+
...(boundPermissions === undefined && liveRun?.boundPermissions !== true ? {} : { permissions: liveRun?.permissionControl.permissions ?? boundPermissions }) };
|
|
5662
|
+
const writeFinal = () => writeFinalRunRecord(this.directory, finalRecord, telemetryAccess);
|
|
5171
5663
|
if (liveRun)
|
|
5172
5664
|
await this.serializeRunRecordWrite(liveRun, writeFinal);
|
|
5173
5665
|
else
|
|
@@ -5207,9 +5699,11 @@ export class AppServer {
|
|
|
5207
5699
|
this.spendAttemptWakes(record.id, new Set([runId, ...lineage]), finishedOwn);
|
|
5208
5700
|
this.settleSessionTimers(record.id);
|
|
5209
5701
|
this.emit('session.updated', { session: this.terminalSummary(snapshot) });
|
|
5210
|
-
const
|
|
5211
|
-
?
|
|
5212
|
-
|
|
5702
|
+
const visibleResult = result === undefined || (telemetryHandle?.lease && sameTelemetryLease(telemetryHandle.lease, telemetryLeaseSnapshot({ home: this.directory, signals: this.telemetry.signals })))
|
|
5703
|
+
? result : functionalRunRecord(result);
|
|
5704
|
+
const eventResult = closedWithRun && visibleResult !== undefined && visibleResult.status === 'cancelled'
|
|
5705
|
+
? { ...visibleResult, status: 'interrupted', reason: APP_CLOSED_REASON }
|
|
5706
|
+
: visibleResult;
|
|
5213
5707
|
const undelivered = undeliveredSteers.length
|
|
5214
5708
|
? { undeliveredSteers: undeliveredSteers.map(entry => ({ id: entry.id, text: entry.text, ...(entry.note ? { note: entry.note } : {}), ...(entry.refs?.length ? { attachments: entry.refs } : {}) })) }
|
|
5215
5709
|
: {};
|
|
@@ -5275,6 +5769,9 @@ export class AppServer {
|
|
|
5275
5769
|
throw new AppServerError('invalid-params', 'That run is no longer active.');
|
|
5276
5770
|
const provider = identifier(params.provider, 'provider');
|
|
5277
5771
|
const model = text(params.model, 'model', 200);
|
|
5772
|
+
const requestedEffort = params.reasoningEffort === undefined || params.reasoningEffort === null ? undefined
|
|
5773
|
+
: params.reasoningEffort === 'auto' ? 'auto' : reasoningEffort(params.reasoningEffort);
|
|
5774
|
+
const selection = { provider, model, ...(requestedEffort === undefined ? {} : { reasoningEffort: requestedEffort }) };
|
|
5278
5775
|
const scopedNode = params.nodeId === undefined ? undefined : identifier(params.nodeId, 'nodeId');
|
|
5279
5776
|
if (scopedNode === undefined && typeof params.overrideAllNodes !== 'boolean')
|
|
5280
5777
|
throw new AppServerError('invalid-params', 'overrideAllNodes must be a boolean');
|
|
@@ -5290,7 +5787,7 @@ export class AppServer {
|
|
|
5290
5787
|
if (scopedNode !== undefined && run.modelGraph.nodes[scopedNode]?.type !== 'agent')
|
|
5291
5788
|
throw new AppServerError('invalid-params', `Unknown agent node: ${scopedNode}`);
|
|
5292
5789
|
const replacement = scopedNode === undefined
|
|
5293
|
-
? params.overrideAllNodes ? applyModelOverride(original,
|
|
5790
|
+
? params.overrideAllNodes ? applyModelOverride(original, selection) : bindPortableGraphProviders(original, config)
|
|
5294
5791
|
: undefined;
|
|
5295
5792
|
let switched;
|
|
5296
5793
|
await this.serializeRunRecordWrite(run, async () => {
|
|
@@ -5299,7 +5796,7 @@ export class AppServer {
|
|
|
5299
5796
|
if (run.modelChangeGeneration !== generation)
|
|
5300
5797
|
throw new AppServerError('busy', 'A newer model selection superseded this one.');
|
|
5301
5798
|
const path = runRecordPath(this.directory, run.runId, 'json');
|
|
5302
|
-
const existing =
|
|
5799
|
+
const existing = await readTelemetryRunRecord(this.directory, path, this.run?.telemetryAccess);
|
|
5303
5800
|
if (existing.status !== 'running')
|
|
5304
5801
|
throw new AppServerError('invalid-params', 'That run is no longer active.');
|
|
5305
5802
|
if (scopedNode !== undefined) {
|
|
@@ -5309,11 +5806,14 @@ export class AppServer {
|
|
|
5309
5806
|
const previousModel = existingOverride?.model ?? (typeof node.model === 'string' ? node.model
|
|
5310
5807
|
: node.provider === undefined ? existing.model
|
|
5311
5808
|
: config.providers.find(item => item.id === node.provider)?.model);
|
|
5312
|
-
existing.nodeModelOverrides = { ...(existing.nodeModelOverrides ?? {}), [scopedNode]:
|
|
5809
|
+
existing.nodeModelOverrides = { ...(existing.nodeModelOverrides ?? {}), [scopedNode]: selection };
|
|
5313
5810
|
existing.liveModelChanged = true;
|
|
5314
5811
|
// A model override replaces the node's whole model choice, its own thinking level included, as one given at
|
|
5315
5812
|
// run start does (applyNodeModelOverrides).
|
|
5316
|
-
|
|
5813
|
+
if (requestedEffort === undefined)
|
|
5814
|
+
delete node.reasoningEffort;
|
|
5815
|
+
else
|
|
5816
|
+
node.reasoningEffort = requestedEffort;
|
|
5317
5817
|
switched = { scope: 'node', from: { provider: previousProvider, ...(previousModel === undefined ? {} : { model: String(previousModel) }) }, nodeName: node.name };
|
|
5318
5818
|
}
|
|
5319
5819
|
else {
|
|
@@ -5325,11 +5825,15 @@ export class AppServer {
|
|
|
5325
5825
|
existing.overrideAllNodes = true;
|
|
5326
5826
|
else
|
|
5327
5827
|
delete existing.overrideAllNodes;
|
|
5828
|
+
// A model picked for the whole run is an explicit choice: a resume after a crash must not restore Auto.
|
|
5829
|
+
delete existing.autoModel;
|
|
5328
5830
|
delete existing.nodeModelOverrides;
|
|
5329
|
-
if (
|
|
5831
|
+
if (requestedEffort !== undefined)
|
|
5832
|
+
existing.reasoningEffort = requestedEffort;
|
|
5833
|
+
else if (params.reasoningEffort === null || !supportsReasoningEffort(config.providers.find(item => item.id === provider)?.type ?? ''))
|
|
5330
5834
|
delete existing.reasoningEffort;
|
|
5331
5835
|
}
|
|
5332
|
-
await writeOpenRunRecord(this.directory, existing);
|
|
5836
|
+
await writeOpenRunRecord(this.directory, existing, this.run?.telemetryAccess);
|
|
5333
5837
|
if (replacement !== undefined) {
|
|
5334
5838
|
for (const [id, source] of Object.entries(replacement.nodes)) {
|
|
5335
5839
|
const target = run.modelGraph.nodes[id];
|
|
@@ -5380,7 +5884,7 @@ export class AppServer {
|
|
|
5380
5884
|
config,
|
|
5381
5885
|
...(liveEffort === undefined ? {} : { reasoningEffort: liveEffort }),
|
|
5382
5886
|
...(liveAuto ? { autoEffort: true } : {}),
|
|
5383
|
-
nodeOverrides: { ...(existing.nodeModelOverrides ?? previous?.nodeOverrides ?? {}), [scopedNode]:
|
|
5887
|
+
nodeOverrides: { ...(existing.nodeModelOverrides ?? previous?.nodeOverrides ?? {}), [scopedNode]: selection },
|
|
5384
5888
|
revision: (previous?.revision ?? 0) + 1,
|
|
5385
5889
|
};
|
|
5386
5890
|
}
|
|
@@ -5403,6 +5907,8 @@ export class AppServer {
|
|
|
5403
5907
|
run.wakeCarry.overrideAllNodes = true;
|
|
5404
5908
|
else
|
|
5405
5909
|
delete run.wakeCarry.overrideAllNodes;
|
|
5910
|
+
if (scopedNode === undefined)
|
|
5911
|
+
delete run.wakeCarry.autoModel;
|
|
5406
5912
|
}
|
|
5407
5913
|
});
|
|
5408
5914
|
if (switched !== undefined) {
|
|
@@ -5423,11 +5929,15 @@ export class AppServer {
|
|
|
5423
5929
|
if (live === undefined || live.runId !== runId || live.controller.signal.aborted || live.steersClosed) {
|
|
5424
5930
|
throw new AppServerError('not-found', 'That task is not running on this engine. The new mode applies to the next task.');
|
|
5425
5931
|
}
|
|
5426
|
-
|
|
5932
|
+
// `scope: "run"` keeps the change with this run: its record carries the mode, and the workspace default is left alone.
|
|
5933
|
+
if (params.scope !== undefined && params.scope !== 'run')
|
|
5934
|
+
throw new AppServerError('invalid-params', 'scope must be "run" when it is given.');
|
|
5935
|
+
const bind = params.scope === 'run';
|
|
5936
|
+
const change = (live.permissionChanges ?? Promise.resolve()).then(() => this.applyRunPermissions(live, next, bind));
|
|
5427
5937
|
live.permissionChanges = change.then(() => undefined, () => undefined);
|
|
5428
5938
|
return change;
|
|
5429
5939
|
}
|
|
5430
|
-
async applyRunPermissions(live, next) {
|
|
5940
|
+
async applyRunPermissions(live, next, bind = false) {
|
|
5431
5941
|
const stillLive = () => this.run === live && !live.controller.signal.aborted;
|
|
5432
5942
|
if (!stillLive())
|
|
5433
5943
|
throw new AppServerError('not-found', 'That task is not running on this engine. The new mode applies to the next task.');
|
|
@@ -5438,7 +5948,10 @@ export class AppServer {
|
|
|
5438
5948
|
await live.codeIntelReady;
|
|
5439
5949
|
await this.syncCodeIntelPermissions(live);
|
|
5440
5950
|
}
|
|
5441
|
-
await this.saveRunPermissions(live, next, stillLive);
|
|
5951
|
+
await this.saveRunPermissions(live, next, stillLive, bind);
|
|
5952
|
+
// From here on the run owns its mode: later changes stay with it too, and its final record carries the mode.
|
|
5953
|
+
if (bind)
|
|
5954
|
+
live.boundPermissions = true;
|
|
5442
5955
|
}
|
|
5443
5956
|
catch (error) {
|
|
5444
5957
|
live.codeIntelPermissions = live.permissionControl.permissions ?? previous;
|
|
@@ -5486,16 +5999,16 @@ export class AppServer {
|
|
|
5486
5999
|
live.permissionChanges = change.then(() => undefined, () => undefined);
|
|
5487
6000
|
return change;
|
|
5488
6001
|
}
|
|
5489
|
-
async saveRunPermissions(live, next, stillLive) {
|
|
5490
|
-
if (live.boundPermissions) {
|
|
6002
|
+
async saveRunPermissions(live, next, stillLive, bind = false) {
|
|
6003
|
+
if (live.boundPermissions || bind) {
|
|
5491
6004
|
await this.serializeRunRecordWrite(live, async () => {
|
|
5492
6005
|
if (!stillLive())
|
|
5493
6006
|
throw new AppServerError('not-found', 'That task is not running on this engine. The new mode applies to the next task.');
|
|
5494
|
-
const existing =
|
|
6007
|
+
const existing = await readTelemetryRunRecord(this.directory, runRecordPath(this.directory, live.runId, 'json'), live.telemetryAccess);
|
|
5495
6008
|
if (existing.status !== 'running')
|
|
5496
6009
|
throw new AppServerError('not-found', 'That task is not running on this engine. The new mode applies to the next task.');
|
|
5497
6010
|
existing.permissions = next;
|
|
5498
|
-
await writeOpenRunRecord(this.directory, existing);
|
|
6011
|
+
await writeOpenRunRecord(this.directory, existing, this.run?.telemetryAccess);
|
|
5499
6012
|
});
|
|
5500
6013
|
}
|
|
5501
6014
|
else {
|
|
@@ -5537,14 +6050,10 @@ export class AppServer {
|
|
|
5537
6050
|
return { model: resolved.model, adapter: this.tracedAdapter(this.reasoningAdapter(this.adapterFor(resolved, { sessionId })), id), ...(resolved.contextWindow === undefined ? {} : { contextWindow: resolved.contextWindow }), ...(resolved.reasoningEffort === undefined ? {} : { reasoningEffort: resolved.reasoningEffort }), providerType: provider.type, baseUrl: provider.baseUrl };
|
|
5538
6051
|
}
|
|
5539
6052
|
async analyticsConfigView(config) {
|
|
5540
|
-
|
|
5541
|
-
|
|
5542
|
-
|
|
5543
|
-
|
|
5544
|
-
}
|
|
5545
|
-
catch {
|
|
5546
|
-
return configView(config);
|
|
5547
|
-
}
|
|
6053
|
+
const { status, analytics } = await this.telemetry.snapshot();
|
|
6054
|
+
const functional = { ...config };
|
|
6055
|
+
delete functional.analytics;
|
|
6056
|
+
return { ...configView(functional), ...(analytics === undefined ? {} : { analytics }), telemetryConsent: status };
|
|
5548
6057
|
}
|
|
5549
6058
|
resolveProvider(config, id, sessionId = this.run?.sessionId) {
|
|
5550
6059
|
const provider = config.providers.find(item => item.id === id);
|
|
@@ -5584,7 +6093,7 @@ export class AppServer {
|
|
|
5584
6093
|
if (busy())
|
|
5585
6094
|
throw new AppServerError('engine-busy', 'This engine is already running a task.');
|
|
5586
6095
|
const root = await workspaceRoot(params.workspace);
|
|
5587
|
-
const requested =
|
|
6096
|
+
const requested = requestedPermissionMode(params.permissions);
|
|
5588
6097
|
const config = await loadConfig(this.directory);
|
|
5589
6098
|
const effective = requested ?? config.workspacePermissions?.[workspacePermissionKey(root)] ?? 'ask-for-approval';
|
|
5590
6099
|
const manager = await this.operation(undefined, signal => this.codeIntelligence(root, effective, signal, { onlyWhileIdle: true }));
|
|
@@ -5678,7 +6187,7 @@ export class AppServer {
|
|
|
5678
6187
|
return 'policy-changed';
|
|
5679
6188
|
return answer === 'approve';
|
|
5680
6189
|
}
|
|
5681
|
-
async ask(runId, question, choices, signal) {
|
|
6190
|
+
async ask(runId, question, choices, signal, handoff) {
|
|
5682
6191
|
const id = randomUUID();
|
|
5683
6192
|
const sessionId = this.run?.sessionId;
|
|
5684
6193
|
if (sessionId)
|
|
@@ -5686,8 +6195,8 @@ export class AppServer {
|
|
|
5686
6195
|
version: 1, id, runId, sessionId, kind: 'question',
|
|
5687
6196
|
prompt: question.slice(0, 2048), createdAt: new Date().toISOString(),
|
|
5688
6197
|
}).catch(error => this.log('warn', 'Could not record pending question: ' + message(error)));
|
|
5689
|
-
this.emit('run.question', { runId, id, question, ...(choices === undefined ? {} : { choices }) });
|
|
5690
|
-
this.waiting.set(id, { kind: 'question', runId, id, question, ...(choices === undefined ? {} : { choices: [...choices] }) });
|
|
6198
|
+
this.emit('run.question', { runId, id, question, ...(choices === undefined ? {} : { choices }), ...(handoff ? { handoff } : {}) });
|
|
6199
|
+
this.waiting.set(id, { kind: 'question', runId, id, question, ...(choices === undefined ? {} : { choices: [...choices] }), ...(handoff ? { handoff } : {}) });
|
|
5691
6200
|
this.emit('run.state', { runId, state: 'awaiting-input' });
|
|
5692
6201
|
try {
|
|
5693
6202
|
return await this.interaction(id, signal);
|
|
@@ -5869,17 +6378,23 @@ export class AppServer {
|
|
|
5869
6378
|
}
|
|
5870
6379
|
async graphDirectory(canClaim = false) {
|
|
5871
6380
|
const subject = await currentGraphSubject();
|
|
5872
|
-
if (subject === undefined)
|
|
6381
|
+
if (subject === undefined) {
|
|
6382
|
+
await this.graphSync.close();
|
|
5873
6383
|
return { directory: this.directory };
|
|
6384
|
+
}
|
|
5874
6385
|
let access;
|
|
6386
|
+
const legal = LEGAL_ACCEPTANCE_REQUIRED ? await legalStatus(this.directory) : undefined;
|
|
6387
|
+
const accepted = legal === undefined || (legal.accepted && legal.scope === 'account' && legal.subject === subject);
|
|
5875
6388
|
try {
|
|
5876
|
-
access = await graphStorageAccess(this.directory, subject, { claim: canClaim, paid: who => this.currentAccountIsConfirmed(who) });
|
|
6389
|
+
access = await graphStorageAccess(this.directory, subject, { claim: canClaim && accepted, paid: who => this.currentAccountIsConfirmed(who) });
|
|
5877
6390
|
}
|
|
5878
6391
|
catch {
|
|
5879
6392
|
return { directory: this.directory };
|
|
5880
6393
|
}
|
|
5881
|
-
if (!access.shared)
|
|
6394
|
+
if (!access.shared && accepted)
|
|
5882
6395
|
await this.graphSync.ensure(access.directory, subject);
|
|
6396
|
+
else
|
|
6397
|
+
await this.graphSync.close(); // Local metadata is harmless, but must not start autosync.
|
|
5883
6398
|
return { directory: access.directory, subject };
|
|
5884
6399
|
}
|
|
5885
6400
|
async currentAccountIsConfirmed(subject) {
|
|
@@ -5996,6 +6511,57 @@ export class AppServer {
|
|
|
5996
6511
|
}
|
|
5997
6512
|
return { graph, ...(execution !== undefined ? { execution } : {}), ...(subject === undefined ? {} : { subject }) };
|
|
5998
6513
|
}
|
|
6514
|
+
async checkDraftGraphModels(params) {
|
|
6515
|
+
const id = currentGraphSelection(identifier(params.id, 'id'));
|
|
6516
|
+
const scope = identifier(params.scope, 'scope');
|
|
6517
|
+
const provider = params.provider === undefined ? undefined : identifier(params.provider, 'provider');
|
|
6518
|
+
const model = params.model === undefined ? undefined : text(params.model, 'model', 200);
|
|
6519
|
+
const override = params.overrideAllNodes === true && provider !== undefined && model !== undefined
|
|
6520
|
+
? { provider, model } : undefined;
|
|
6521
|
+
this.draftGraphProbes.get(scope)?.abort();
|
|
6522
|
+
const controller = new AbortController();
|
|
6523
|
+
this.draftGraphProbes.set(scope, controller);
|
|
6524
|
+
try {
|
|
6525
|
+
return await this.operation(undefined, async (tracked) => {
|
|
6526
|
+
const signal = AbortSignal.any([tracked, controller.signal]);
|
|
6527
|
+
const config = await loadConfig(this.directory);
|
|
6528
|
+
if (config.providers.length === 0)
|
|
6529
|
+
return {};
|
|
6530
|
+
try {
|
|
6531
|
+
const graph = await this.loadGraph(id, signal, undefined, { bindProviders: override === undefined });
|
|
6532
|
+
signal.throwIfAborted();
|
|
6533
|
+
const warning = await this.graphModelWarning(override === undefined ? graph : applyModelOverride(graph, override), config, signal, { ...(provider === undefined ? {} : { provider }), ...(model === undefined ? {} : { model }) }, override === undefined
|
|
6534
|
+
? 'Open the graph in Studio, correct the model selections, then select it again.'
|
|
6535
|
+
: 'Choose another model to check its availability.');
|
|
6536
|
+
return warning === undefined ? {} : { modelWarning: warning };
|
|
6537
|
+
}
|
|
6538
|
+
catch (error) {
|
|
6539
|
+
if (!(error instanceof GraphProviderUnavailableError))
|
|
6540
|
+
throw error;
|
|
6541
|
+
return { modelWarning: this.graphProviderWarning(error) };
|
|
6542
|
+
}
|
|
6543
|
+
});
|
|
6544
|
+
}
|
|
6545
|
+
catch (error) {
|
|
6546
|
+
if (!controller.signal.aborted)
|
|
6547
|
+
throw error;
|
|
6548
|
+
return {};
|
|
6549
|
+
}
|
|
6550
|
+
finally {
|
|
6551
|
+
if (this.draftGraphProbes.get(scope) === controller)
|
|
6552
|
+
this.draftGraphProbes.delete(scope);
|
|
6553
|
+
}
|
|
6554
|
+
}
|
|
6555
|
+
async graphModelWarning(graph, config, signal, session, advice) {
|
|
6556
|
+
const health = await this.checkGraphHealth(graph, config, signal, {
|
|
6557
|
+
...(session === undefined ? {} : { session }), overallTimeoutMs: SELECTION_HEALTH_TIMEOUT_MS,
|
|
6558
|
+
verified: { has: () => false, add: (provider, model) => this.modelHealth.add(provider, model) },
|
|
6559
|
+
});
|
|
6560
|
+
return health.healthy ? undefined : formatGraphHealthFailure(health, advice);
|
|
6561
|
+
}
|
|
6562
|
+
graphProviderWarning(error) {
|
|
6563
|
+
return `${error.message}\nThe selection stands. A task on this graph starts only once it can run on this machine, or with a model override that runs every node on one provider.`;
|
|
6564
|
+
}
|
|
5999
6565
|
async selectGraph(params) {
|
|
6000
6566
|
const id = currentGraphSelection(identifier(params.id, 'id'));
|
|
6001
6567
|
const madeFor = params.subject === undefined || params.subject === '' ? undefined : identifier(params.subject, 'subject');
|
|
@@ -6013,25 +6579,23 @@ export class AppServer {
|
|
|
6013
6579
|
...(sessionProvider === undefined ? {} : { provider: sessionProvider }),
|
|
6014
6580
|
...(sessionModel === undefined ? {} : { model: sessionModel }),
|
|
6015
6581
|
};
|
|
6016
|
-
const
|
|
6582
|
+
const checkModels = params.skipModelHealth !== true;
|
|
6017
6583
|
let modelWarning;
|
|
6018
6584
|
let boundGraph;
|
|
6019
6585
|
try {
|
|
6020
|
-
boundGraph = await this.loadGraph(id);
|
|
6586
|
+
boundGraph = await this.loadGraph(id, undefined, undefined, { bindProviders: checkModels });
|
|
6021
6587
|
}
|
|
6022
6588
|
catch (error) {
|
|
6023
6589
|
if (!(error instanceof GraphProviderUnavailableError))
|
|
6024
6590
|
throw error;
|
|
6025
|
-
|
|
6591
|
+
if (checkModels)
|
|
6592
|
+
modelWarning = this.graphProviderWarning(error);
|
|
6026
6593
|
}
|
|
6027
6594
|
const probed = boundGraph;
|
|
6028
|
-
if (
|
|
6029
|
-
const
|
|
6030
|
-
|
|
6031
|
-
|
|
6032
|
-
}));
|
|
6033
|
-
if (!health.healthy)
|
|
6034
|
-
modelWarning = formatGraphHealthFailure(health, 'Open the graph in Studio, correct the model selections, then select it again.');
|
|
6595
|
+
if (checkModels && probed !== undefined) {
|
|
6596
|
+
const config = await loadConfig(this.directory);
|
|
6597
|
+
if (config.providers.length !== 0)
|
|
6598
|
+
modelWarning = await this.operation(undefined, tracked => this.graphModelWarning(probed, config, tracked, session, 'Open the graph in Studio, correct the model selections, then select it again.'));
|
|
6035
6599
|
}
|
|
6036
6600
|
const withWarning = (answer) => modelWarning === undefined ? answer : { ...answer, modelWarning };
|
|
6037
6601
|
const subject = await currentGraphSubject();
|
|
@@ -6056,10 +6620,13 @@ export class AppServer {
|
|
|
6056
6620
|
this.emit('config.changed', { config: await this.analyticsConfigView(saved) });
|
|
6057
6621
|
return withWarning({ config: await this.analyticsConfigView(saved), selected: id, persisted: true });
|
|
6058
6622
|
}
|
|
6059
|
-
async openEditor() {
|
|
6623
|
+
async openEditor(params) {
|
|
6624
|
+
// Validate before reusing a listener as well as before creating one.
|
|
6625
|
+
graphEditorParentOrigins(params.parentOrigin);
|
|
6626
|
+
const parentOrigin = params.parentOrigin;
|
|
6060
6627
|
if (this.editor)
|
|
6061
6628
|
return { url: this.editor.url, reused: true, embeddable: true };
|
|
6062
|
-
this.editorTask ??= startGraphServer(this.directory).then(app => ({ url: app.url, close: app.close }));
|
|
6629
|
+
this.editorTask ??= startGraphServer(this.directory, undefined, { parentOrigin }).then(app => ({ url: app.url, close: app.close }));
|
|
6063
6630
|
try {
|
|
6064
6631
|
const editor = await this.editorTask;
|
|
6065
6632
|
this.editor = editor;
|
|
@@ -6208,7 +6775,9 @@ export class AppServer {
|
|
|
6208
6775
|
if (remember)
|
|
6209
6776
|
this.cloudEnvironmentId = status.state === 'none' ? undefined : status.environmentId ?? this.cloudEnvironmentId;
|
|
6210
6777
|
const { version, ...rest } = status;
|
|
6211
|
-
|
|
6778
|
+
const link = status.environmentId === undefined ? undefined : this.engineLinks.get(status.environmentId);
|
|
6779
|
+
const autoUpdates = remember && link?.capabilities?.includes(CLOUD_BRIDGE_AUTO_UPDATE) === true;
|
|
6780
|
+
return { ...rest, outdated: !autoUpdates && (status.state === 'starting' || status.state === 'running') && version !== undefined && version !== engineVersion };
|
|
6212
6781
|
}
|
|
6213
6782
|
async environmentRemove(params) {
|
|
6214
6783
|
const id = environmentId(params.id);
|
|
@@ -6377,8 +6946,46 @@ export class AppServer {
|
|
|
6377
6946
|
const identity = await this.machineIdentity(env);
|
|
6378
6947
|
if (identity?.capabilities !== undefined && this.engineLinks.get(env) === link)
|
|
6379
6948
|
link.capabilities = identity.capabilities;
|
|
6949
|
+
// A machine that says it cannot ask before product telemetry gets no link. One that could not be asked keeps a
|
|
6950
|
+
// retryable link: no relayed method runs on it until the capability has been proved (assertRemotePolicy).
|
|
6951
|
+
if (identity?.capabilities !== undefined && !identity.capabilities.includes(TELEMETRY_CONSENT_CAPABILITY)) {
|
|
6952
|
+
this.dropEngineLink(env, link);
|
|
6953
|
+
throw new RemoteConsentUnsupportedError();
|
|
6954
|
+
}
|
|
6380
6955
|
return { ok: true, engine: REMOTE_LINK_ENGINE, host: { ...opened.host, ...(identity ?? {}) } };
|
|
6381
6956
|
}
|
|
6957
|
+
/**
|
|
6958
|
+
* Relayed work reaches only a machine that proved it asks before product telemetry and, for coding or policy
|
|
6959
|
+
* calls, that it records policy acceptance. The proof is the capabilities its `whoami` named for this link; a
|
|
6960
|
+
* machine that could not be asked is refused, never assumed capable.
|
|
6961
|
+
*/
|
|
6962
|
+
async assertRemotePolicy(env, method) {
|
|
6963
|
+
const link = this.engineLinks.get(env);
|
|
6964
|
+
let capabilities = link?.capabilities;
|
|
6965
|
+
if (capabilities === undefined) {
|
|
6966
|
+
try {
|
|
6967
|
+
const whoami = await this.relayLink().host(env, 'whoami', {}, Date.now() + REMOTE_HOST_DEADLINE_MS);
|
|
6968
|
+
const named = whoami && typeof whoami === 'object' ? whoami.capabilities : undefined;
|
|
6969
|
+
if (Array.isArray(named)) {
|
|
6970
|
+
capabilities = named.filter((entry) => typeof entry === 'string');
|
|
6971
|
+
if (link !== undefined && this.engineLinks.get(env) === link)
|
|
6972
|
+
link.capabilities = capabilities;
|
|
6973
|
+
}
|
|
6974
|
+
}
|
|
6975
|
+
catch (error) {
|
|
6976
|
+
// A machine the relay does not know is not found, as before; any other failure leaves the capability unproved.
|
|
6977
|
+
if (error instanceof AppServerError && error.code === 'not-found')
|
|
6978
|
+
throw error;
|
|
6979
|
+
}
|
|
6980
|
+
}
|
|
6981
|
+
if (capabilities === undefined)
|
|
6982
|
+
throw new AppServerError('remote', 'Telemetry permission unavailable: that machine could not be asked what it supports. Try again in a moment.');
|
|
6983
|
+
if (!capabilities.includes(TELEMETRY_CONSENT_CAPABILITY))
|
|
6984
|
+
throw new RemoteConsentUnsupportedError();
|
|
6985
|
+
if ((legalMethodRequiresAcceptance(method) || method.startsWith('legal.')) && !capabilities.includes(LEGAL_ACCEPTANCE_CAPABILITY)) {
|
|
6986
|
+
throw new AppServerError('remote', 'Update the paired machine for policy acceptance before coding work.');
|
|
6987
|
+
}
|
|
6988
|
+
}
|
|
6382
6989
|
/** What the machine's `whoami` adds to its host description (grant, capabilities); undefined when it could not be read. */
|
|
6383
6990
|
async machineIdentity(env) {
|
|
6384
6991
|
try {
|
|
@@ -6794,18 +7401,24 @@ export class AppServer {
|
|
|
6794
7401
|
this.modelRelaySaveRetries.add(timer);
|
|
6795
7402
|
}
|
|
6796
7403
|
async remoteEngineRequest(params) {
|
|
7404
|
+
const requestedAt = Date.now();
|
|
6797
7405
|
const workspaceId = typeof params.workspaceId === 'string' ? params.workspaceId : '';
|
|
6798
7406
|
const connectionId = typeof params.connectionId === 'string' ? params.connectionId : '';
|
|
6799
7407
|
const engine = typeof params.engine === 'string' ? params.engine : '';
|
|
6800
7408
|
const method = typeof params.method === 'string' ? params.method : '';
|
|
6801
7409
|
if (!workspaceId || !connectionId || !engine || !method)
|
|
6802
7410
|
throw new AppServerError('invalid-params', 'workspaceId, connectionId, engine, and method are required.');
|
|
7411
|
+
if (method === 'telemetry.setConsent')
|
|
7412
|
+
throw new AppServerError('unknown-method', 'Permission must be changed locally on the execution host.');
|
|
6803
7413
|
const env = environmentId(workspaceId);
|
|
6804
7414
|
this.refuseWhileReconnecting(env);
|
|
7415
|
+
await this.assertRemotePolicy(env, method);
|
|
7416
|
+
const startsTask = method === 'run.start' || method === 'run.resume';
|
|
7417
|
+
const cloudTaskLink = startsTask && env === this.cloudEnvironmentId ? this.engineLinks.get(env) : undefined;
|
|
7418
|
+
const generation = this.accountGeneration;
|
|
6805
7419
|
let inner = params.params !== undefined && typeof params.params === 'object' && !Array.isArray(params.params)
|
|
6806
7420
|
? params.params : undefined;
|
|
6807
7421
|
if (inner?.attachments !== undefined && env === this.cloudEnvironmentId && ['run.start', 'run.resume', 'run.steer'].includes(method)) {
|
|
6808
|
-
const generation = this.accountGeneration;
|
|
6809
7422
|
try {
|
|
6810
7423
|
inner = { ...inner, attachments: await cloudAttachments(inner.attachments) };
|
|
6811
7424
|
}
|
|
@@ -6816,11 +7429,12 @@ export class AppServer {
|
|
|
6816
7429
|
throw new AppServerError('cancelled', 'The Andorra account changed.');
|
|
6817
7430
|
this.refuseWhileReconnecting(env);
|
|
6818
7431
|
}
|
|
6819
|
-
const
|
|
7432
|
+
const capabilities = this.engineLinks.get(env)?.capabilities;
|
|
7433
|
+
const relayMachine = capabilities?.includes(MODEL_RELAY_CAPABILITY) === true;
|
|
6820
7434
|
// A machine whose engine takes relayed providers runs this computer's models: its start carries them by id only.
|
|
6821
7435
|
let relayed = false;
|
|
6822
|
-
if (
|
|
6823
|
-
const enriched = await this.withModelRelay(method, inner ?? {});
|
|
7436
|
+
if (startsTask && relayMachine) {
|
|
7437
|
+
const enriched = await this.withModelRelay(method, inner ?? {}, capabilities?.includes('providers.reasoningProbe') === true);
|
|
6824
7438
|
if (enriched !== undefined) {
|
|
6825
7439
|
relayed = true;
|
|
6826
7440
|
inner = enriched;
|
|
@@ -6830,24 +7444,49 @@ export class AppServer {
|
|
|
6830
7444
|
await this.checkRelayedModel(inner);
|
|
6831
7445
|
const ceiling = RELAY_LONG_METHODS.has(method) ? RELAY_LONG_DEADLINE_MS : RELAY_DEADLINE_MS;
|
|
6832
7446
|
const deadlineMs = typeof params.deadlineMs === 'number' && params.deadlineMs > 0 ? Math.min(Math.round(params.deadlineMs), ceiling) : undefined;
|
|
6833
|
-
const send = (sent) => {
|
|
7447
|
+
const send = (sent, budget = deadlineMs) => {
|
|
6834
7448
|
// The machine bounds the call by deadlineMs and answers with its own error; the slack lets that answer arrive.
|
|
6835
|
-
const deadlineAt = Date.now() + (
|
|
7449
|
+
const deadlineAt = Date.now() + (budget ?? ceiling) + RELAY_TRANSPORT_SLACK_MS;
|
|
6836
7450
|
return this.relayLink().request(env, {
|
|
6837
7451
|
connectionId,
|
|
6838
7452
|
viewerWorkspaceId: env,
|
|
6839
7453
|
engine,
|
|
6840
7454
|
method,
|
|
6841
7455
|
...(sent !== undefined ? { params: sent } : {}),
|
|
6842
|
-
...(
|
|
7456
|
+
...(budget !== undefined ? { deadlineMs: budget } : {}),
|
|
6843
7457
|
}, deadlineAt);
|
|
6844
7458
|
};
|
|
6845
|
-
|
|
7459
|
+
const sendTask = async (sent) => {
|
|
7460
|
+
if (cloudTaskLink?.connectionId !== connectionId)
|
|
7461
|
+
return send(sent);
|
|
7462
|
+
const checkLink = () => {
|
|
7463
|
+
if (generation !== this.accountGeneration)
|
|
7464
|
+
throw new AppServerError('cancelled', 'The Andorra account changed.');
|
|
7465
|
+
if (this.closed || !this.linkIsCurrent(env, cloudTaskLink))
|
|
7466
|
+
throw new AppServerError('cancelled', 'The connection to that machine was closed.');
|
|
7467
|
+
};
|
|
7468
|
+
checkLink();
|
|
7469
|
+
this.refuseWhileReconnecting(env);
|
|
7470
|
+
let result = await send(sent);
|
|
7471
|
+
const callerDeadline = requestedAt + (deadlineMs ?? ceiling);
|
|
7472
|
+
const retryUntil = Math.min(Date.now() + CLOUD_BRIDGE_RETRY_LIMIT_MS, callerDeadline - RELAY_TRANSPORT_SLACK_MS);
|
|
7473
|
+
// Only this answer proves the task was refused before dispatch. An unanswered request could have started work.
|
|
7474
|
+
while (result.error?.code === 'busy' && result.error.message === RESTARTING_MESSAGE && Date.now() < retryUntil) {
|
|
7475
|
+
await new Promise(resolve => setTimeout(resolve, Math.min(CLOUD_BRIDGE_RETRY_MS, Math.max(0, retryUntil - Date.now()))));
|
|
7476
|
+
checkLink();
|
|
7477
|
+
const now = Date.now();
|
|
7478
|
+
if (now >= retryUntil || cloudTaskLink.reconnecting)
|
|
7479
|
+
continue;
|
|
7480
|
+
result = await send(sent, callerDeadline - now - RELAY_TRANSPORT_SLACK_MS);
|
|
7481
|
+
}
|
|
7482
|
+
return result;
|
|
7483
|
+
};
|
|
7484
|
+
let answer = await sendTask(inner);
|
|
6846
7485
|
// A resumed run that ran a graph from this computer needs it again; the machine's record names it.
|
|
6847
7486
|
if (relayed && method === 'run.resume' && answer.error?.message === RELAYED_GRAPH_NEEDS_DESKTOP && inner !== undefined) {
|
|
6848
7487
|
const graph = await this.relayedResumeGraph(env, connectionId, inner.runId, relayOfferedProviders(await loadConfig(this.directory)));
|
|
6849
7488
|
if (graph !== undefined)
|
|
6850
|
-
answer = await
|
|
7489
|
+
answer = await sendTask({ ...inner, relay: { ...inner.relay, graph } });
|
|
6851
7490
|
}
|
|
6852
7491
|
// The machine took a run on this computer's models: from now on that run's model requests are answered here.
|
|
6853
7492
|
if (relayed && !answer.error)
|
|
@@ -6891,7 +7530,7 @@ export class AppServer {
|
|
|
6891
7530
|
* falls back to one of its own. Undefined when this computer has no provider to offer: the request then goes as it
|
|
6892
7531
|
* was, and the machine runs it on its own providers if it has any.
|
|
6893
7532
|
*/
|
|
6894
|
-
async withModelRelay(method, params) {
|
|
7533
|
+
async withModelRelay(method, params, relayReasoning) {
|
|
6895
7534
|
const config = await loadConfig(this.directory);
|
|
6896
7535
|
const providers = relayOfferedProviders(config);
|
|
6897
7536
|
if (!providers.length)
|
|
@@ -6927,7 +7566,7 @@ export class AppServer {
|
|
|
6927
7566
|
// sign-in names the one compatible profile here), so every node names an entry of `relay.providers`. A start that runs
|
|
6928
7567
|
// every node on one model is not bound, as locally: the override replaces the nodes' providers on the machine.
|
|
6929
7568
|
const graph = loaded === undefined || (method === 'run.start' && params.overrideAllNodes === true) ? loaded : this.relayBoundGraph(loaded, providers);
|
|
6930
|
-
next.relay = { providers: await this.relayedProviders(providers), ...(graph === undefined ? {} : { graph }) };
|
|
7569
|
+
next.relay = { providers: await this.relayedProviders(providers, relayReasoning), ...(graph === undefined ? {} : { graph }) };
|
|
6931
7570
|
return next;
|
|
6932
7571
|
}
|
|
6933
7572
|
/**
|
|
@@ -6947,7 +7586,7 @@ export class AppServer {
|
|
|
6947
7586
|
* Each provider as a relay entry, with the effective window of each listed model resolved here within 5 s in all.
|
|
6948
7587
|
* A provider's windows are reused for 5 minutes while its address and models stay the same.
|
|
6949
7588
|
*/
|
|
6950
|
-
async relayedProviders(providers) {
|
|
7589
|
+
async relayedProviders(providers, relayReasoning) {
|
|
6951
7590
|
const controller = new AbortController();
|
|
6952
7591
|
const windows = new Map();
|
|
6953
7592
|
const keyOf = (provider) => JSON.stringify([provider.id, provider.type, provider.baseUrl, relayedModelIds(provider), provider.modelContextWindows ?? null]);
|
|
@@ -6974,11 +7613,15 @@ export class AppServer {
|
|
|
6974
7613
|
controller.abort();
|
|
6975
7614
|
return providers.map(provider => {
|
|
6976
7615
|
const models = provider.models === undefined ? undefined : relayedModelIds(provider).filter(model => provider.models.includes(model));
|
|
7616
|
+
const thinkingLevels = relayReasoning
|
|
7617
|
+
? Object.fromEntries(Object.entries(provider.thinkingLevels ?? {}).filter(([model]) => model === provider.model || models?.includes(model)))
|
|
7618
|
+
: undefined;
|
|
6977
7619
|
const known = Object.fromEntries(Object.entries(windows.get(provider.id) ?? {}).filter(([, window]) => Number.isSafeInteger(window) && window > 0));
|
|
6978
7620
|
return {
|
|
6979
7621
|
id: provider.id, model: provider.model,
|
|
6980
7622
|
...(models === undefined || models.length === 0 ? {} : { models }),
|
|
6981
7623
|
...(Object.keys(known).length === 0 ? {} : { modelContextWindows: known }),
|
|
7624
|
+
...(thinkingLevels && Object.keys(thinkingLevels).length ? { thinkingLevels } : {}),
|
|
6982
7625
|
...(provider.reasoningEffort === undefined ? {} : { reasoningEffort: provider.reasoningEffort }),
|
|
6983
7626
|
};
|
|
6984
7627
|
});
|
|
@@ -7183,6 +7826,16 @@ export class AppServer {
|
|
|
7183
7826
|
const path = typeof params.path === 'string' ? params.path.trim() : '';
|
|
7184
7827
|
if (!path || path.includes('\0'))
|
|
7185
7828
|
throw new AppServerError('invalid-params', 'projects.add requires a folder path.');
|
|
7829
|
+
if (params.create === true) {
|
|
7830
|
+
// A new project: the folder is made first, then registered like any other.
|
|
7831
|
+
if (!isAbsolute(path))
|
|
7832
|
+
throw new AppServerError('invalid-params', 'A new project folder needs an absolute path.');
|
|
7833
|
+
const existing = await stat(path).catch(() => undefined);
|
|
7834
|
+
if (existing !== undefined && !existing.isDirectory())
|
|
7835
|
+
throw new AppServerError('invalid-params', `${path} is a file, not a folder.`);
|
|
7836
|
+
if (existing === undefined)
|
|
7837
|
+
await mkdir(path, { recursive: true }).catch((error) => { throw new AppServerError('storage', `Couldn't create ${path}: ${message(error)}`); });
|
|
7838
|
+
}
|
|
7186
7839
|
const realPath = await realpath(path).catch(() => undefined);
|
|
7187
7840
|
if (!realPath || !(await stat(realPath).catch(() => undefined))?.isDirectory())
|
|
7188
7841
|
throw new AppServerError('not-found', `No folder exists at ${path}.`);
|
|
@@ -7396,8 +8049,11 @@ export class AppServer {
|
|
|
7396
8049
|
this.emitSessionSkills(sessionId, skills);
|
|
7397
8050
|
return skills;
|
|
7398
8051
|
}
|
|
8052
|
+
pullRequestForClient(pullRequest) {
|
|
8053
|
+
return pullRequest ? { ...pullRequest, autoArchive: false } : null;
|
|
8054
|
+
}
|
|
7399
8055
|
emitPullRequest(sessionId, pullRequest) {
|
|
7400
|
-
this.emit('session.pullRequest.updated', { sessionId, pullRequest:
|
|
8056
|
+
this.emit('session.pullRequest.updated', { sessionId, pullRequest: this.pullRequestForClient(pullRequest) });
|
|
7401
8057
|
// An attach, a finish or a dismiss changes the watched set: the GitHub App subscriptions follow it.
|
|
7402
8058
|
this.githubEvents.nudge();
|
|
7403
8059
|
const waiter = this.reviewWaiters.get(sessionId);
|
|
@@ -7411,9 +8067,6 @@ export class AppServer {
|
|
|
7411
8067
|
const ended = this.watchedLoopEnded(sessionId, pullRequest);
|
|
7412
8068
|
if (ended)
|
|
7413
8069
|
waiter(ended);
|
|
7414
|
-
// A wait goes on while Auto-fix or a review loop is on: it answers off only when neither is.
|
|
7415
|
-
else if (!pullRequest.autoFix && !chatReviewLoopActive(pullRequest))
|
|
7416
|
-
waiter({ kind: 'off', pullRequest });
|
|
7417
8070
|
}
|
|
7418
8071
|
}
|
|
7419
8072
|
/**
|
|
@@ -7470,12 +8123,14 @@ export class AppServer {
|
|
|
7470
8123
|
return await new Promise(resolve => {
|
|
7471
8124
|
let settled = false;
|
|
7472
8125
|
let signalTimer;
|
|
8126
|
+
const classify = new AbortController();
|
|
7473
8127
|
// The run that waits: the review loop's round counts it as held while it waits (`review.waiting`).
|
|
7474
8128
|
const wait = { ...(this.run?.sessionId === sessionId ? { runId: this.run.runId } : {}), since: new Date().toISOString() };
|
|
7475
8129
|
const finish = (ended) => {
|
|
7476
8130
|
if (settled)
|
|
7477
8131
|
return false;
|
|
7478
8132
|
settled = true;
|
|
8133
|
+
classify.abort();
|
|
7479
8134
|
clearTimeout(timeout);
|
|
7480
8135
|
clearTimeout(signalTimer);
|
|
7481
8136
|
clearInterval(ticks);
|
|
@@ -7497,7 +8152,7 @@ export class AppServer {
|
|
|
7497
8152
|
// then as often as each read asks (sooner while a quiet head waits out the delay before a bump).
|
|
7498
8153
|
const watch = {};
|
|
7499
8154
|
const fromSignals = () => {
|
|
7500
|
-
void this.reviewWaitFromSignals(sessionId, finish, watch,
|
|
8155
|
+
void this.reviewWaitFromSignals(sessionId, finish, watch, classify.signal, options)
|
|
7501
8156
|
.catch(error => { this.log('warn', `Could not read Codex's review signals for session ${sessionId}: ${message(error)}`); return this.reviewSignalMs; })
|
|
7502
8157
|
.then(delay => {
|
|
7503
8158
|
if (settled)
|
|
@@ -7528,52 +8183,102 @@ export class AppServer {
|
|
|
7528
8183
|
fromSignals();
|
|
7529
8184
|
});
|
|
7530
8185
|
}
|
|
7531
|
-
/**
|
|
7532
|
-
|
|
7533
|
-
*
|
|
7534
|
-
* A sign-off on the head commit ends the wait as approved, unless a review comment is still to be handed
|
|
7535
|
-
* over: comments come first. Where Codex shows nothing at all for the head (no eyes, no review, no comment,
|
|
7536
|
-
* nobody asked yet), the next read comes after the bump delay, and if that one is as quiet the wait posts
|
|
7537
|
-
* "@codex review", once per head and only in a repository Codex is known to review.
|
|
7538
|
-
*/
|
|
7539
|
-
async reviewWaitFromSignals(sessionId, deliver, watch, settled, approveBump) {
|
|
8186
|
+
/** Polls GitHub only while the agent has an explicit wait. The record stores activity already reported. */
|
|
8187
|
+
async reviewWaitFromSignals(sessionId, deliver, watch, signal, options) {
|
|
7540
8188
|
const every = this.reviewSignalMs;
|
|
7541
8189
|
const current = await readPullRequest(this.directory, sessionId);
|
|
7542
|
-
|
|
7543
|
-
if (!current || isFinishedPullRequest(current.state) || !current.autoFix)
|
|
8190
|
+
if (!current || isFinishedPullRequest(current.state) || signal.aborted)
|
|
7544
8191
|
return every;
|
|
7545
8192
|
const gh = ghFor(this.gh, current);
|
|
7546
|
-
const seen = await
|
|
7547
|
-
|
|
8193
|
+
const [found, seen] = await Promise.all([
|
|
8194
|
+
newReviewComments(gh, current, { includeDetails: true }).catch(error => {
|
|
8195
|
+
this.log('warn', 'Could not read review comments for ' + current.url + ': ' + message(error));
|
|
8196
|
+
return undefined;
|
|
8197
|
+
}),
|
|
8198
|
+
readReviewSignals(gh, current).catch(error => {
|
|
8199
|
+
this.log('warn', 'Could not read reactions and review signals for ' + current.url + ': ' + message(error));
|
|
8200
|
+
return undefined;
|
|
8201
|
+
}),
|
|
8202
|
+
]);
|
|
8203
|
+
if (signal.aborted)
|
|
7548
8204
|
return every;
|
|
7549
|
-
|
|
7550
|
-
|
|
7551
|
-
delete watch.quiet;
|
|
7552
|
-
if (current.pendingFix !== undefined)
|
|
7553
|
-
return every;
|
|
7554
|
-
// An Andorra review loop in progress decides when this task's review is done: Codex's sign-off does not end the wait.
|
|
7555
|
-
if (chatReviewLoopActive(current))
|
|
7556
|
-
return every;
|
|
7557
|
-
const found = await newReviewComments(gh, current);
|
|
7558
|
-
if (found.threads > 0 || found.comments > 0) {
|
|
7559
|
-
void this.pullRequestWatcher.readNow(sessionId);
|
|
7560
|
-
return every;
|
|
7561
|
-
}
|
|
7562
|
-
if (!deliver({ kind: 'approved', pullRequest: current, ...(head === undefined ? {} : { headSha: head }) }) || head === undefined)
|
|
7563
|
-
return every;
|
|
7564
|
-
// The approval reached the agent: the record says so, or the watcher would hand the same sign-off again.
|
|
7565
|
-
const recorded = await withPullRequest(this.directory, sessionId, async () => {
|
|
7566
|
-
const live = await readPullRequest(this.directory, sessionId);
|
|
7567
|
-
if (!live || live.url !== current.url || isFinishedPullRequest(live.state) || live.approvalHandled === head)
|
|
7568
|
-
return undefined;
|
|
7569
|
-
const next = { ...live, approvalHandled: head, updatedAt: new Date().toISOString() };
|
|
7570
|
-
await writePullRequest(this.directory, sessionId, next);
|
|
7571
|
-
return next;
|
|
7572
|
-
}).catch(error => { this.log('warn', `Could not record the approval delivered to session ${sessionId}: ${message(error)}`); return undefined; });
|
|
7573
|
-
if (recorded !== undefined)
|
|
7574
|
-
this.emitPullRequest(sessionId, recorded);
|
|
8205
|
+
if (seen?.state === 'closed' || seen?.state === 'merged') {
|
|
8206
|
+
await this.recordPullRequestChange(sessionId, current.url, { state: seen.state, mergeWhenReady: false });
|
|
7575
8207
|
return every;
|
|
7576
8208
|
}
|
|
8209
|
+
const candidates = found?.candidates ?? [];
|
|
8210
|
+
// Bound Jev traffic when a batch contains many inline comments. The remaining comments are reported unclassified.
|
|
8211
|
+
const labels = await Promise.all(candidates.slice(0, 4).map(async (comment) => {
|
|
8212
|
+
if (!comment.body.trim())
|
|
8213
|
+
return undefined;
|
|
8214
|
+
return options.classifyComment?.(comment.body, signal).catch(() => undefined);
|
|
8215
|
+
}));
|
|
8216
|
+
if (signal.aborted)
|
|
8217
|
+
return every;
|
|
8218
|
+
const ended = await withPullRequest(this.directory, sessionId, async () => {
|
|
8219
|
+
const live = await readPullRequest(this.directory, sessionId);
|
|
8220
|
+
if (!live || live.url !== current.url || isFinishedPullRequest(live.state) || signal.aborted)
|
|
8221
|
+
return true;
|
|
8222
|
+
const reportedAt = Date.parse(live.handledThrough ?? '');
|
|
8223
|
+
const reportedIds = new Set(live.handledCommentIds);
|
|
8224
|
+
const comments = [];
|
|
8225
|
+
for (const [index, comment] of candidates.entries()) {
|
|
8226
|
+
const at = Date.parse(comment.createdAt);
|
|
8227
|
+
if (at < reportedAt || (at === reportedAt && (live.handledCommentIds === undefined || reportedIds.has(comment.id))))
|
|
8228
|
+
continue;
|
|
8229
|
+
const kind = labels[index] ?? 'unclassified';
|
|
8230
|
+
if (kind !== 'noise')
|
|
8231
|
+
comments.push({
|
|
8232
|
+
kind, author: comment.author, source: comment.source,
|
|
8233
|
+
...(comment.url === undefined ? {} : { url: comment.url }),
|
|
8234
|
+
...(comment.threadId === undefined ? {} : { threadId: comment.threadId }),
|
|
8235
|
+
});
|
|
8236
|
+
}
|
|
8237
|
+
const reactions = [];
|
|
8238
|
+
if (seen?.reactions !== undefined) {
|
|
8239
|
+
const before = new Set(live.reviewReactions?.map(reaction => reaction.id));
|
|
8240
|
+
const after = new Set(seen.reactions.map(reaction => reaction.id));
|
|
8241
|
+
for (const reaction of seen.reactions) {
|
|
8242
|
+
if (!before.has(reaction.id) && (live.reviewReactions !== undefined || Date.parse(reaction.createdAt) > Date.parse(live.attachedAt)))
|
|
8243
|
+
reactions.push({ ...reaction, kind: 'added' });
|
|
8244
|
+
}
|
|
8245
|
+
for (const reaction of live.reviewReactions ?? []) {
|
|
8246
|
+
if (!after.has(reaction.id))
|
|
8247
|
+
reactions.push({ ...reaction, kind: 'removed' });
|
|
8248
|
+
}
|
|
8249
|
+
}
|
|
8250
|
+
const head = seen?.headSha;
|
|
8251
|
+
const approved = found !== undefined && seen?.approved === true && head !== undefined && live.approvalHandled !== head && !chatReviewLoopActive(live);
|
|
8252
|
+
const activity = comments.length > 0
|
|
8253
|
+
? { kind: 'activity', pullRequest: live, comments, reactions }
|
|
8254
|
+
: approved
|
|
8255
|
+
? { kind: 'approved', pullRequest: live, headSha: head, reactions }
|
|
8256
|
+
: reactions.length > 0 ? { kind: 'activity', pullRequest: live, comments, reactions } : undefined;
|
|
8257
|
+
if (activity && !deliver(activity))
|
|
8258
|
+
return true;
|
|
8259
|
+
const next = { ...live };
|
|
8260
|
+
if (found?.newest !== undefined && (!Number.isFinite(reportedAt) || Date.parse(found.newest) >= reportedAt)) {
|
|
8261
|
+
if (Date.parse(found.newest) !== reportedAt)
|
|
8262
|
+
reportedIds.clear();
|
|
8263
|
+
for (const id of found.newestIds ?? [])
|
|
8264
|
+
reportedIds.add(id);
|
|
8265
|
+
next.handledThrough = found.newest;
|
|
8266
|
+
next.handledCommentIds = [...reportedIds];
|
|
8267
|
+
}
|
|
8268
|
+
if (seen?.reactions !== undefined && (live.reviewReactions === undefined || reactions.length > 0))
|
|
8269
|
+
next.reviewReactions = seen.reactions;
|
|
8270
|
+
if (activity?.kind === 'approved')
|
|
8271
|
+
next.approvalHandled = head;
|
|
8272
|
+
if (next.handledThrough !== live.handledThrough || next.handledCommentIds?.length !== live.handledCommentIds?.length
|
|
8273
|
+
|| next.reviewReactions !== live.reviewReactions || next.approvalHandled !== live.approvalHandled) {
|
|
8274
|
+
await writePullRequest(this.directory, sessionId, { ...next, updatedAt: new Date().toISOString() });
|
|
8275
|
+
}
|
|
8276
|
+
return activity !== undefined;
|
|
8277
|
+
});
|
|
8278
|
+
if (ended || signal.aborted || !seen || seen.approved)
|
|
8279
|
+
return every;
|
|
8280
|
+
const head = seen.headSha;
|
|
8281
|
+
const { approveBump } = options;
|
|
7577
8282
|
if (!approveBump || head === undefined || !seen.open || seen.reviewing || seen.reviewed || seen.asked || current.reviewBumped === head || watch.skipped === head) {
|
|
7578
8283
|
delete watch.quiet;
|
|
7579
8284
|
return every;
|
|
@@ -7598,12 +8303,12 @@ export class AppServer {
|
|
|
7598
8303
|
watch.skipped = head;
|
|
7599
8304
|
return every;
|
|
7600
8305
|
}
|
|
7601
|
-
if (
|
|
8306
|
+
if (signal.aborted)
|
|
7602
8307
|
return every;
|
|
7603
8308
|
// Recorded before it is posted: a head is asked for once, even when the post's outcome is unknown.
|
|
7604
8309
|
const claimed = await withPullRequest(this.directory, sessionId, async () => {
|
|
7605
8310
|
const latest = await readPullRequest(this.directory, sessionId);
|
|
7606
|
-
if (!latest || latest.url !== current.url || isFinishedPullRequest(latest.state) ||
|
|
8311
|
+
if (signal.aborted || !latest || latest.url !== current.url || isFinishedPullRequest(latest.state) || latest.reviewBumped === head)
|
|
7607
8312
|
return false;
|
|
7608
8313
|
await writePullRequest(this.directory, sessionId, { ...latest, reviewBumped: head, updatedAt: new Date().toISOString() });
|
|
7609
8314
|
return true;
|
|
@@ -7621,8 +8326,7 @@ export class AppServer {
|
|
|
7621
8326
|
}
|
|
7622
8327
|
/**
|
|
7623
8328
|
* One look at the record for a wait, in whichever engine process it runs: how the PR or the review loop ended, the
|
|
7624
|
-
* review loop's next round (
|
|
7625
|
-
* comments, and the marker that tells the lease holder this run waits.
|
|
8329
|
+
* review loop's next round (including one posted by another engine), and the marker that this run is waiting.
|
|
7626
8330
|
*/
|
|
7627
8331
|
async reviewWaitFromRecord(sessionId, deliver) {
|
|
7628
8332
|
const wait = this.reviewWaitRuns.get(sessionId);
|
|
@@ -7643,10 +8347,6 @@ export class AppServer {
|
|
|
7643
8347
|
return undefined;
|
|
7644
8348
|
}
|
|
7645
8349
|
const looping = chatReviewLoopActive(current);
|
|
7646
|
-
if (!current.autoFix && !looping) {
|
|
7647
|
-
deliver({ kind: 'off', pullRequest: current });
|
|
7648
|
-
return undefined;
|
|
7649
|
-
}
|
|
7650
8350
|
const at = new Date().toISOString();
|
|
7651
8351
|
let next = current;
|
|
7652
8352
|
if (looping && wait?.runId !== undefined) {
|
|
@@ -7665,35 +8365,6 @@ export class AppServer {
|
|
|
7665
8365
|
marked = true;
|
|
7666
8366
|
}
|
|
7667
8367
|
}
|
|
7668
|
-
const pending = current.pendingFix;
|
|
7669
|
-
// A queued approval is checked against GitHub before this wait hands it over: a head pushed since it was
|
|
7670
|
-
// armed is not the one Codex signed off on, and an older commit's sign-off must not be told to the agent
|
|
7671
|
-
// as covering its newest push. A read that fails or is ambiguous leaves the wake for the next pass.
|
|
7672
|
-
if (pending?.approval !== undefined && pending.through === undefined && pending.head === undefined && !this.timers.isHeld(pending.wakeId)) {
|
|
7673
|
-
const seen = await viewPullRequest(this.gh, current.url, current.ghUser).catch(error => { this.log('warn', `Could not confirm the approval wake of session ${sessionId}: ${message(error)}`); return undefined; });
|
|
7674
|
-
if (seen === undefined || isFinishedPullRequest(seen.state))
|
|
7675
|
-
return undefined;
|
|
7676
|
-
if (seen.headSha !== undefined && seen.headSha !== pending.approval) {
|
|
7677
|
-
const retired = { ...withoutPendingFix(current), updatedAt: new Date().toISOString() };
|
|
7678
|
-
await writePullRequest(this.directory, sessionId, retired);
|
|
7679
|
-
return retired;
|
|
7680
|
-
}
|
|
7681
|
-
}
|
|
7682
|
-
const prompt = !current.autoFix || pending === undefined || this.timers.isHeld(pending.wakeId) ? undefined : pending.prompt ?? this.timers.get(pending.wakeId)?.prompt;
|
|
7683
|
-
// A queued approval is delivered as the approval answer, with the head it applies to.
|
|
7684
|
-
if (pending !== undefined && pending.approval !== undefined && !this.timers.isHeld(pending.wakeId)
|
|
7685
|
-
&& deliver({ kind: 'approved', pullRequest: current, headSha: pending.approval })) {
|
|
7686
|
-
if (this.autoFixWakes.has(pending.wakeId))
|
|
7687
|
-
this.cancelAutoFixWake(sessionId, pending.wakeId);
|
|
7688
|
-
next = { ...handedOver(next, pending), updatedAt: at };
|
|
7689
|
-
marked = false;
|
|
7690
|
-
}
|
|
7691
|
-
else if (pending !== undefined && prompt !== undefined && deliver({ kind: 'comments', prompt })) {
|
|
7692
|
-
if (this.autoFixWakes.has(pending.wakeId))
|
|
7693
|
-
this.cancelAutoFixWake(sessionId, pending.wakeId);
|
|
7694
|
-
next = { ...handedOver(next, pending), updatedAt: at };
|
|
7695
|
-
marked = false;
|
|
7696
|
-
}
|
|
7697
8368
|
if (next === current)
|
|
7698
8369
|
return undefined;
|
|
7699
8370
|
await writePullRequest(this.directory, sessionId, next);
|
|
@@ -7704,16 +8375,6 @@ export class AppServer {
|
|
|
7704
8375
|
if (marked)
|
|
7705
8376
|
this.reviewLoop.waitStarted(sessionId);
|
|
7706
8377
|
}
|
|
7707
|
-
async recordAutoFixDelivered(sessionId, wakeId) {
|
|
7708
|
-
try {
|
|
7709
|
-
const pullRequest = await markAutoFixDelivered(this.directory, sessionId, wakeId);
|
|
7710
|
-
if (pullRequest)
|
|
7711
|
-
this.emitPullRequest(sessionId, pullRequest);
|
|
7712
|
-
}
|
|
7713
|
-
catch (error) {
|
|
7714
|
-
this.log('warn', `Could not record the Auto-fix delivery for session ${sessionId}: ${message(error)}`);
|
|
7715
|
-
}
|
|
7716
|
-
}
|
|
7717
8378
|
emitSessionChanges(changes) {
|
|
7718
8379
|
this.emit('session.changes.updated', { sessionId: changes.sessionId, revision: changes.revision, changes: changes.changes });
|
|
7719
8380
|
}
|
|
@@ -7731,10 +8392,10 @@ export class AppServer {
|
|
|
7731
8392
|
let reviewed;
|
|
7732
8393
|
const attached = await withPullRequest(this.directory, sessionId, async () => {
|
|
7733
8394
|
const current = await readPullRequest(this.directory, sessionId);
|
|
7734
|
-
// Another PR replaces this task's: a loop running on the old one goes with it.
|
|
8395
|
+
// Another PR replaces this task's: a loop running on the old one goes with it, and the old one is remembered.
|
|
7735
8396
|
if (current && current.url !== ref.url && reviewLoopActive(current))
|
|
7736
8397
|
replaced = current.review;
|
|
7737
|
-
let next = current?.url === ref.url ? current : newPullRequest(ref);
|
|
8398
|
+
let next = withSupersededPullRequest(current?.url === ref.url ? current : newPullRequest(ref), current);
|
|
7738
8399
|
if (next !== current) {
|
|
7739
8400
|
const read = await readPullRequestAsAnyAccount(this.gh, ref.url);
|
|
7740
8401
|
if (read.seen)
|
|
@@ -7746,8 +8407,8 @@ export class AppServer {
|
|
|
7746
8407
|
}
|
|
7747
8408
|
if (carry !== undefined)
|
|
7748
8409
|
next = { ...next, carry: structuredClone(carry) };
|
|
7749
|
-
//
|
|
7750
|
-
if (origin !== undefined && (settings.
|
|
8410
|
+
// Andorra review wakes the node that switched it on.
|
|
8411
|
+
if (origin !== undefined && (settings.review === true || next.origin === undefined))
|
|
7751
8412
|
next = { ...next, origin: { runId: origin.runId, nodeId: origin.nodeId } };
|
|
7752
8413
|
// A refused switch-on changes nothing: its checks, and the settings' own, run before any gh write.
|
|
7753
8414
|
if (Object.keys(reviewSettings).length) {
|
|
@@ -7814,7 +8475,7 @@ export class AppServer {
|
|
|
7814
8475
|
coverage: pullRequest => this.reviewCoverage(sessionId, pullRequest),
|
|
7815
8476
|
readNow: () => this.pullRequestWatcher.readNow(sessionId),
|
|
7816
8477
|
head: async () => { await this.pullRequestWatcher.readNow(sessionId).catch(() => { }); return this.pullRequestWatcher.headSha(sessionId); },
|
|
7817
|
-
writes: () => this.
|
|
8478
|
+
writes: () => this.reviewCommentWrites(sessionId),
|
|
7818
8479
|
steers,
|
|
7819
8480
|
});
|
|
7820
8481
|
}
|
|
@@ -7919,13 +8580,9 @@ export class AppServer {
|
|
|
7919
8580
|
}
|
|
7920
8581
|
if (carry !== undefined)
|
|
7921
8582
|
next = { ...next, carry: structuredClone(carry) };
|
|
7922
|
-
//
|
|
7923
|
-
if (origin !== undefined && (settings.
|
|
8583
|
+
// Andorra review wakes the node that switched it on.
|
|
8584
|
+
if (origin !== undefined && (settings.review === true))
|
|
7924
8585
|
next = { ...next, origin: { runId: origin.runId, nodeId: origin.nodeId } };
|
|
7925
|
-
if (!next.autoFix && next.pendingFix) {
|
|
7926
|
-
this.cancelAutoFixWake(sessionId, next.pendingFix.wakeId);
|
|
7927
|
-
next = withoutPendingFix(next);
|
|
7928
|
-
}
|
|
7929
8586
|
await writePullRequest(this.directory, sessionId, next);
|
|
7930
8587
|
return next;
|
|
7931
8588
|
});
|
|
@@ -7945,8 +8602,6 @@ export class AppServer {
|
|
|
7945
8602
|
if (current.url !== agentChecked)
|
|
7946
8603
|
throw new Error(`This task's pull request changed to ${current.url} while the dismiss was being checked. Nothing was changed.`);
|
|
7947
8604
|
}
|
|
7948
|
-
if (current?.pendingFix)
|
|
7949
|
-
this.cancelAutoFixWake(sessionId, current.pendingFix.wakeId);
|
|
7950
8605
|
await removePullRequest(this.directory, sessionId);
|
|
7951
8606
|
return current;
|
|
7952
8607
|
});
|
|
@@ -8052,7 +8707,7 @@ export class AppServer {
|
|
|
8052
8707
|
pullRequests,
|
|
8053
8708
|
};
|
|
8054
8709
|
}
|
|
8055
|
-
/** Settings → GitHub →
|
|
8710
|
+
/** Settings → GitHub → Agent replies on pull requests. */
|
|
8056
8711
|
async githubSetAgentWrites(params) {
|
|
8057
8712
|
const value = params.value;
|
|
8058
8713
|
if (typeof value !== 'string' || !GITHUB_AGENT_WRITES.includes(value))
|
|
@@ -8064,7 +8719,7 @@ export class AppServer {
|
|
|
8064
8719
|
return { agentWrites };
|
|
8065
8720
|
}
|
|
8066
8721
|
/**
|
|
8067
|
-
* Who an agent write on this session's PR goes to first, decided one way for the tool and
|
|
8722
|
+
* Who an agent write on this session's PR goes to first, decided one way for the tool and review findings:
|
|
8068
8723
|
* the setting, and the PR's coverage as the event source (or, in another process, the lease holder) last
|
|
8069
8724
|
* learned it. Events switched off here, or a PR the source has not looked at yet, are not covered.
|
|
8070
8725
|
*/
|
|
@@ -8121,8 +8776,8 @@ export class AppServer {
|
|
|
8121
8776
|
}
|
|
8122
8777
|
return this.githubBot;
|
|
8123
8778
|
}
|
|
8124
|
-
/** For
|
|
8125
|
-
async
|
|
8779
|
+
/** For review findings: whether this session's replies post as the bot (the tool's own rule), and the bot's name. */
|
|
8780
|
+
async reviewCommentWrites(sessionId) {
|
|
8126
8781
|
const pullRequest = await readPullRequest(this.directory, sessionId);
|
|
8127
8782
|
// The gh form names the bot only for its sentence on mentions: the name already known, never a read for it.
|
|
8128
8783
|
const known = this.githubBot === undefined ? {} : { bot: this.githubBot };
|
|
@@ -8376,9 +9031,7 @@ export class AppServer {
|
|
|
8376
9031
|
const current = await readPullRequest(this.directory, sessionId);
|
|
8377
9032
|
if (current?.url !== url)
|
|
8378
9033
|
return undefined;
|
|
8379
|
-
const next =
|
|
8380
|
-
if (next.pendingFix === undefined && current.pendingFix !== undefined)
|
|
8381
|
-
this.cancelAutoFixWake(sessionId, current.pendingFix.wakeId);
|
|
9034
|
+
const next = { ...current, ...change, updatedAt: new Date().toISOString() };
|
|
8382
9035
|
await writePullRequest(this.directory, sessionId, next);
|
|
8383
9036
|
return next;
|
|
8384
9037
|
}).catch(error => { this.log('warn', `Could not record the change to ${url}: ${message(error)}`); return undefined; });
|
|
@@ -8394,10 +9047,10 @@ export class AppServer {
|
|
|
8394
9047
|
return { ok: false, error: answer.error };
|
|
8395
9048
|
const read = await this.pullRequestReader.readMerge(sessionId, pullRequest, { force: true });
|
|
8396
9049
|
const stored = await readPullRequest(this.directory, sessionId);
|
|
8397
|
-
return { ok: true, ...answer.value, ...read, ...(stored?.url === pullRequest.url ? { pullRequest:
|
|
9050
|
+
return { ok: true, ...answer.value, ...read, ...(stored?.url === pullRequest.url ? { pullRequest: this.pullRequestForClient(stored) } : {}) };
|
|
8398
9051
|
}
|
|
8399
9052
|
/**
|
|
8400
|
-
* Merges the task's PR
|
|
9053
|
+
* Merges the task's PR or adds it to the merge queue. A direct merge uses the method and
|
|
8401
9054
|
* commit message the person chose, at the head commit they read. Deleting the head branch afterwards
|
|
8402
9055
|
* is said separately: the merge has happened even when that fails.
|
|
8403
9056
|
*/
|
|
@@ -8405,8 +9058,8 @@ export class AppServer {
|
|
|
8405
9058
|
const sessionId = identifier(params.id, 'id');
|
|
8406
9059
|
const input = writeParams(() => {
|
|
8407
9060
|
const when = params.when ?? 'now';
|
|
8408
|
-
if (when !== 'now' && when !== '
|
|
8409
|
-
throw new Error('when must be now
|
|
9061
|
+
if (when !== 'now' && when !== 'queue')
|
|
9062
|
+
throw new Error('when must be now or queue');
|
|
8410
9063
|
if (params.deleteBranch !== undefined && typeof params.deleteBranch !== 'boolean')
|
|
8411
9064
|
throw new Error('deleteBranch must be true or false');
|
|
8412
9065
|
if (params.bypass !== undefined && typeof params.bypass !== 'boolean')
|
|
@@ -8454,12 +9107,6 @@ export class AppServer {
|
|
|
8454
9107
|
throw new PullRequestRefusal(`GitHub holds this pull request back (${state.mergeState}). Read what holds it in the panel.`);
|
|
8455
9108
|
}
|
|
8456
9109
|
const commit = { method: input.method, headSha: input.headSha, ...(input.title === undefined ? {} : { title: input.title }), ...(input.body === undefined ? {} : { body: input.body }) };
|
|
8457
|
-
if (input.when === 'ready') {
|
|
8458
|
-
if (!state.autoMergeAllowed)
|
|
8459
|
-
throw new PullRequestRefusal('This repository does not allow auto-merge, so the pull request cannot merge itself when ready.');
|
|
8460
|
-
await enableAutoMerge(gh, state.pullRequestId, commit);
|
|
8461
|
-
return { autoMerge: true };
|
|
8462
|
-
}
|
|
8463
9110
|
const merged = await mergePullRequest(gh, state.pullRequestId, commit);
|
|
8464
9111
|
if (!input.deleteBranch || state.deletesBranch)
|
|
8465
9112
|
return { merged: true, ...merged };
|
|
@@ -8473,8 +9120,8 @@ export class AppServer {
|
|
|
8473
9120
|
return { merged: true, ...merged, branchError: classifyWriteError(error).message };
|
|
8474
9121
|
}
|
|
8475
9122
|
});
|
|
8476
|
-
if (answer.ok && answer.value.
|
|
8477
|
-
await this.recordPullRequestChange(sessionId, pullRequest.url,
|
|
9123
|
+
if (answer.ok && answer.value.merged === true)
|
|
9124
|
+
await this.recordPullRequestChange(sessionId, pullRequest.url, { state: 'merged', mergeWhenReady: false });
|
|
8478
9125
|
return this.afterMergeWrite(sessionId, pullRequest, answer);
|
|
8479
9126
|
}
|
|
8480
9127
|
/** Brings the PR's branch up to date with its base on GitHub (GitHub's "Update branch"), by a merge commit or a rebase. */
|
|
@@ -8583,9 +9230,9 @@ export class AppServer {
|
|
|
8583
9230
|
// A pull request the task picked up meanwhile (its agent opened one) is kept, not replaced.
|
|
8584
9231
|
const meanwhile = await readPullRequest(this.directory, sessionId);
|
|
8585
9232
|
if (meanwhile !== undefined && meanwhile.url !== ref.url)
|
|
8586
|
-
return { ok: true, url: opened.url, pushed: opened.pushed, pullRequest:
|
|
9233
|
+
return { ok: true, url: opened.url, pushed: opened.pushed, pullRequest: this.pullRequestForClient(meanwhile) };
|
|
8587
9234
|
const attached = await this.attachPullRequest(sessionId, ref);
|
|
8588
|
-
return { ok: true, url: opened.url, pushed: opened.pushed, ...(opened.attached ? { attached: true } : {}), pullRequest:
|
|
9235
|
+
return { ok: true, url: opened.url, pushed: opened.pushed, ...(opened.attached ? { attached: true } : {}), pullRequest: this.pullRequestForClient(attached) };
|
|
8589
9236
|
}
|
|
8590
9237
|
/** Where a comment the tab may change sits in the review read: a timeline comment, a review's text, or a comment in a thread. */
|
|
8591
9238
|
static commentIn(state, commentId) {
|
|
@@ -8891,7 +9538,7 @@ export class AppServer {
|
|
|
8891
9538
|
await this.recordPullRequestChange(sessionId, pullRequest.url, { state: input.open ? (pullRequest.state === 'draft' ? 'draft' : 'open') : 'closed' });
|
|
8892
9539
|
const after = await this.afterReviewWrite(sessionId, pullRequest, answer);
|
|
8893
9540
|
const stored = await readPullRequest(this.directory, sessionId);
|
|
8894
|
-
return stored?.url === pullRequest.url ? { ...after, pullRequest:
|
|
9541
|
+
return stored?.url === pullRequest.url ? { ...after, pullRequest: this.pullRequestForClient(stored) } : after;
|
|
8895
9542
|
}
|
|
8896
9543
|
/** Takes the PR out of its base's merge queue. */
|
|
8897
9544
|
async dequeueSessionPullRequest(params) {
|
|
@@ -8919,7 +9566,7 @@ export class AppServer {
|
|
|
8919
9566
|
const current = await readPullRequest(this.directory, sessionId);
|
|
8920
9567
|
if (current !== undefined && current.url !== ref.url)
|
|
8921
9568
|
return { ok: false, error: { kind: 'refused', message: 'This task already has a pull request.' } };
|
|
8922
|
-
return { ok: true, pullRequest:
|
|
9569
|
+
return { ok: true, pullRequest: this.pullRequestForClient(await this.attachPullRequest(sessionId, ref)) };
|
|
8923
9570
|
}
|
|
8924
9571
|
reviewRequestsRead = { failures: 0 };
|
|
8925
9572
|
/**
|
|
@@ -9000,16 +9647,9 @@ export class AppServer {
|
|
|
9000
9647
|
if (written)
|
|
9001
9648
|
this.emitPullRequest(sessionId, written);
|
|
9002
9649
|
}
|
|
9003
|
-
|
|
9004
|
-
this.autoFixWakes.delete(wakeId);
|
|
9005
|
-
if (!this.timers.cancel(wakeId))
|
|
9006
|
-
return;
|
|
9007
|
-
void clearWakeClaim(this.directory, sessionId, wakeId).catch(() => { });
|
|
9008
|
-
this.emitTimers(sessionId);
|
|
9009
|
-
}
|
|
9010
|
-
pullRequestControl(sessionId, carry) {
|
|
9650
|
+
pullRequestControl(sessionId, carry, classifyComment) {
|
|
9011
9651
|
return {
|
|
9012
|
-
status: () => readPullRequest(this.directory, sessionId),
|
|
9652
|
+
status: async () => this.pullRequestForClient(await readPullRequest(this.directory, sessionId)) ?? undefined,
|
|
9013
9653
|
attach: (url, settings, origin) => {
|
|
9014
9654
|
const ref = parsePullRequestUrl(url);
|
|
9015
9655
|
if (!ref)
|
|
@@ -9017,14 +9657,21 @@ export class AppServer {
|
|
|
9017
9657
|
return this.attachPullRequest(sessionId, ref, settings, carry, origin);
|
|
9018
9658
|
},
|
|
9019
9659
|
update: (settings, origin) => this.updatePullRequest(sessionId, settings, carry, origin),
|
|
9020
|
-
awaitReview: (signal, timeoutMs, origin, options) =>
|
|
9660
|
+
awaitReview: (signal, timeoutMs, origin, options) => {
|
|
9661
|
+
const invocationId = options?.invocationId ?? randomUUID();
|
|
9662
|
+
return this.awaitReview(sessionId, signal, timeoutMs, origin, {
|
|
9663
|
+
...options, ...(classifyComment === undefined ? {} : {
|
|
9664
|
+
classifyComment: (body, classifySignal) => classifyComment(body, origin, invocationId, classifySignal),
|
|
9665
|
+
}),
|
|
9666
|
+
});
|
|
9667
|
+
},
|
|
9021
9668
|
dismiss: () => this.dismissPullRequestForAgent(sessionId),
|
|
9022
9669
|
write: (write, options) => this.agentPullRequestWrite(sessionId, write, options),
|
|
9023
9670
|
};
|
|
9024
9671
|
}
|
|
9025
9672
|
/**
|
|
9026
9673
|
* The Andorra review loop's fixer wake: straight into a run of the session waiting in await_review here (which then holds
|
|
9027
|
-
* the round), or as the next turn
|
|
9674
|
+
* the round), or as the next turn at the node that took the PR.
|
|
9028
9675
|
*/
|
|
9029
9676
|
wakeForReview(sessionId, prompt, pullRequest) {
|
|
9030
9677
|
const waiter = this.reviewWaiters.get(sessionId);
|
|
@@ -9044,20 +9691,6 @@ export class AppServer {
|
|
|
9044
9691
|
void clearWakeClaim(this.directory, sessionId, wakeId).catch(() => { });
|
|
9045
9692
|
this.emitTimers(sessionId);
|
|
9046
9693
|
}
|
|
9047
|
-
wakeForPullRequest(sessionId, prompt, carry, origin) {
|
|
9048
|
-
const waiter = this.reviewWaiters.get(sessionId);
|
|
9049
|
-
if (waiter) {
|
|
9050
|
-
const id = `review-${randomUUID()}`;
|
|
9051
|
-
waiter({ kind: 'comments', prompt });
|
|
9052
|
-
void this.recordAutoFixDelivered(sessionId, id);
|
|
9053
|
-
return id;
|
|
9054
|
-
}
|
|
9055
|
-
const timer = this.timers.arm(1, prompt, sessionId, carry, origin);
|
|
9056
|
-
this.autoFixWakes.add(timer.id);
|
|
9057
|
-
this.emitTimers(sessionId);
|
|
9058
|
-
this.armTimerCheck();
|
|
9059
|
-
return timer.id;
|
|
9060
|
-
}
|
|
9061
9694
|
emitTimers(sessionId) {
|
|
9062
9695
|
this.emit('timers.updated', { sessionId, timers: this.timersFor(sessionId) });
|
|
9063
9696
|
}
|
|
@@ -9100,7 +9733,6 @@ export class AppServer {
|
|
|
9100
9733
|
if (this.reviewWakes.delete(timer.id) && timer.owner !== undefined) {
|
|
9101
9734
|
void this.reviewLoop.wakeSpent(timer.owner, timer.id, reason).catch(error => this.log('warn', `Could not end the Andorra review loop of session ${timer.owner}: ${message(error)}`));
|
|
9102
9735
|
}
|
|
9103
|
-
this.autoFixWakes.delete(timer.id);
|
|
9104
9736
|
this.fixWakes.delete(timer.id);
|
|
9105
9737
|
this.mentionWakes.delete(timer.id);
|
|
9106
9738
|
this.log('info', `Self-wake ${timer.id} was not delivered: ${reason}`);
|
|
@@ -9112,7 +9744,7 @@ export class AppServer {
|
|
|
9112
9744
|
this.emitTimers(sessionId);
|
|
9113
9745
|
}
|
|
9114
9746
|
nodeReminder(timer) {
|
|
9115
|
-
return timer.origin !== undefined && !this.
|
|
9747
|
+
return timer.origin !== undefined && !this.reviewWakes.has(timer.id);
|
|
9116
9748
|
}
|
|
9117
9749
|
spendAttemptWakes(sessionId, attempts, reason, spent = () => true) {
|
|
9118
9750
|
for (const timer of this.timers.list(sessionId)) {
|
|
@@ -9154,7 +9786,7 @@ export class AppServer {
|
|
|
9154
9786
|
break;
|
|
9155
9787
|
let value;
|
|
9156
9788
|
try {
|
|
9157
|
-
value =
|
|
9789
|
+
value = await readTelemetryRunRecord(this.directory, runRecordPath(this.directory, cursor, 'json'), { signals: this.telemetry.signals });
|
|
9158
9790
|
}
|
|
9159
9791
|
catch {
|
|
9160
9792
|
break;
|
|
@@ -9165,7 +9797,7 @@ export class AppServer {
|
|
|
9165
9797
|
}
|
|
9166
9798
|
if (!chain.includes(origin.runId))
|
|
9167
9799
|
return { spent: 'a newer turn in this session replaced the attempt that set it' };
|
|
9168
|
-
newestRecord ??=
|
|
9800
|
+
newestRecord ??= await readTelemetryRunRecord(this.directory, runRecordPath(this.directory, newest, 'json'), { signals: this.telemetry.signals });
|
|
9169
9801
|
const status = typeof newestRecord.status === 'string' ? newestRecord.status : undefined;
|
|
9170
9802
|
if (status === 'succeeded')
|
|
9171
9803
|
return { spent: 'the attempt that set it has finished' };
|
|
@@ -9173,7 +9805,7 @@ export class AppServer {
|
|
|
9173
9805
|
return { spent: 'the attempt that set it was stopped' };
|
|
9174
9806
|
if (status === 'running' && typeof newestRecord.pid === 'number' && isPidAlive(newestRecord.pid))
|
|
9175
9807
|
return { wait: 'its attempt is still running in another engine' };
|
|
9176
|
-
const armedAt = this.
|
|
9808
|
+
const armedAt = this.reviewWakes.has(timer.id) ? Number.NEGATIVE_INFINITY : timer.fireAt - timer.seconds * 1_000;
|
|
9177
9809
|
for (const attempt of chain) {
|
|
9178
9810
|
const journal = await readFile(runRecordPath(this.directory, attempt, 'jsonl'), 'utf8').catch(() => '');
|
|
9179
9811
|
for (const line of journal.split('\n')) {
|
|
@@ -9229,31 +9861,6 @@ export class AppServer {
|
|
|
9229
9861
|
this.emitTimers(sessionId);
|
|
9230
9862
|
continue;
|
|
9231
9863
|
}
|
|
9232
|
-
if (this.autoFixWakes.has(timer.id)) {
|
|
9233
|
-
let confirmed;
|
|
9234
|
-
try {
|
|
9235
|
-
confirmed = await confirmAutoFixWake(this.directory, this.gh, sessionId, timer.id);
|
|
9236
|
-
}
|
|
9237
|
-
catch (error) {
|
|
9238
|
-
if (this.timers.get(timer.id) !== undefined)
|
|
9239
|
-
this.timers.restore(timer, AUTO_FIX_CONFIRM_RETRY_MS);
|
|
9240
|
-
nextCheckIn = WAKE_RETRY_MS;
|
|
9241
|
-
this.log('warn', `Auto-fix wake ${timer.id} waits: GitHub could not confirm the pull request is still open (${message(error)})`);
|
|
9242
|
-
continue;
|
|
9243
|
-
}
|
|
9244
|
-
if (confirmed.pullRequest)
|
|
9245
|
-
this.emitPullRequest(sessionId, confirmed.pullRequest);
|
|
9246
|
-
if (!confirmed.deliver) {
|
|
9247
|
-
this.autoFixWakes.delete(timer.id);
|
|
9248
|
-
this.timers.settle(timer.id);
|
|
9249
|
-
void clearWakeClaim(this.directory, sessionId, timer.id).catch(() => { });
|
|
9250
|
-
this.emitTimers(sessionId);
|
|
9251
|
-
this.log('info', confirmed.pullRequest
|
|
9252
|
-
? `Dropped Auto-fix wake ${timer.id}: ${confirmed.pullRequest.url} is ${confirmed.pullRequest.state}, so Auto-fix is off`
|
|
9253
|
-
: `Dropped Auto-fix wake ${timer.id}: session ${sessionId} no longer asks for it`);
|
|
9254
|
-
continue;
|
|
9255
|
-
}
|
|
9256
|
-
}
|
|
9257
9864
|
const reviewWake = this.reviewWakes.has(timer.id);
|
|
9258
9865
|
if (reviewWake) {
|
|
9259
9866
|
let deliver;
|
|
@@ -9262,7 +9869,7 @@ export class AppServer {
|
|
|
9262
9869
|
}
|
|
9263
9870
|
catch (error) {
|
|
9264
9871
|
if (this.timers.get(timer.id) !== undefined)
|
|
9265
|
-
this.timers.restore(timer,
|
|
9872
|
+
this.timers.restore(timer, REVIEW_CONFIRM_RETRY_MS);
|
|
9266
9873
|
nextCheckIn = WAKE_RETRY_MS;
|
|
9267
9874
|
this.log('warn', `Andorra review wake ${timer.id} waits: GitHub could not confirm the pull request is still open (${message(error)})`);
|
|
9268
9875
|
continue;
|
|
@@ -9276,10 +9883,7 @@ export class AppServer {
|
|
|
9276
9883
|
continue;
|
|
9277
9884
|
}
|
|
9278
9885
|
}
|
|
9279
|
-
const
|
|
9280
|
-
// The review loop's wake is routed like Auto-fix's: to the node that took the PR, and kept when that node is done.
|
|
9281
|
-
const routed = autoFix || reviewWake;
|
|
9282
|
-
const wakeKind = autoFix ? 'auto-fix' : reviewWake ? 'andorra-review' : this.fixWakes.has(timer.id) ? 'fix-checks' : this.mentionWakes.has(timer.id) ? 'mention' : 'timer';
|
|
9886
|
+
const wakeKind = reviewWake ? 'andorra-review' : this.fixWakes.has(timer.id) ? 'fix-checks' : this.mentionWakes.has(timer.id) ? 'mention' : 'timer';
|
|
9283
9887
|
let resume;
|
|
9284
9888
|
let startNode;
|
|
9285
9889
|
if (timer.origin !== undefined) {
|
|
@@ -9296,7 +9900,7 @@ export class AppServer {
|
|
|
9296
9900
|
this.log('info', `Self-wake ${timer.id} waits: ${plan.wait}`);
|
|
9297
9901
|
continue;
|
|
9298
9902
|
}
|
|
9299
|
-
if ('spent' in plan && !
|
|
9903
|
+
if ('spent' in plan && !reviewWake) {
|
|
9300
9904
|
this.spendWake(timer, plan.spent);
|
|
9301
9905
|
continue;
|
|
9302
9906
|
}
|
|
@@ -9314,12 +9918,12 @@ export class AppServer {
|
|
|
9314
9918
|
if (resume !== undefined) {
|
|
9315
9919
|
try {
|
|
9316
9920
|
started = await this.resumeRun({ runId: resume, direction: timer.prompt,
|
|
9317
|
-
...(carry?.panelBrowserRelay === true ? { panelBrowserRelay: true } : {}) }, { wake:
|
|
9921
|
+
...(carry?.panelBrowserRelay === true ? { panelBrowserRelay: true } : {}) }, { wake: reviewWake ? wakeKind : 'timer', wakeNode: timer.origin.nodeId, freshAllowance: true });
|
|
9318
9922
|
}
|
|
9319
9923
|
catch (error) {
|
|
9320
|
-
if (!
|
|
9924
|
+
if (!reviewWake || !isFinalWakeRefusal(error))
|
|
9321
9925
|
throw error;
|
|
9322
|
-
this.log('info',
|
|
9926
|
+
this.log('info', `Andorra review wake ${timer.id} starts at node ${timer.origin.nodeId}: ${resume} could not be continued (${message(error)})`);
|
|
9323
9927
|
resume = undefined;
|
|
9324
9928
|
startNode = timer.origin.nodeId;
|
|
9325
9929
|
}
|
|
@@ -9335,6 +9939,7 @@ export class AppServer {
|
|
|
9335
9939
|
...(carry?.model === undefined ? {} : { model: carry.model }),
|
|
9336
9940
|
...(carry?.reasoningEffort === undefined ? {} : { reasoningEffort: carry.reasoningEffort }),
|
|
9337
9941
|
...(carry?.overrideAllNodes === undefined ? {} : { overrideAllNodes: carry.overrideAllNodes }),
|
|
9942
|
+
...(carry?.autoModel === true ? { autoModel: true } : {}),
|
|
9338
9943
|
...(carry?.panelBrowserRelay === undefined ? {} : { panelBrowserRelay: carry.panelBrowserRelay }),
|
|
9339
9944
|
...(carry?.input === undefined ? {} : { input: carry.input }),
|
|
9340
9945
|
...(carry?.state === undefined ? {} : { state: carry.state }) }, { sameSession: sessionId, wake: wakeKind, ...(startNode === undefined ? {} : { startNode }) });
|
|
@@ -9347,13 +9952,8 @@ export class AppServer {
|
|
|
9347
9952
|
}
|
|
9348
9953
|
this.timers.settle(timer.id);
|
|
9349
9954
|
this.reviewWakes.delete(timer.id);
|
|
9350
|
-
this.autoFixWakes.delete(timer.id);
|
|
9351
9955
|
this.fixWakes.delete(timer.id);
|
|
9352
9956
|
this.mentionWakes.delete(timer.id);
|
|
9353
|
-
void markAutoFixDelivered(this.directory, sessionId, timer.id)
|
|
9354
|
-
.then(pullRequest => { if (pullRequest)
|
|
9355
|
-
this.emitPullRequest(sessionId, pullRequest); })
|
|
9356
|
-
.catch(error => this.log('warn', `Could not record the Auto-fix delivery for session ${sessionId}: ${message(error)}`));
|
|
9357
9957
|
void clearWakeClaim(this.directory, sessionId, timer.id).catch(() => { });
|
|
9358
9958
|
}
|
|
9359
9959
|
catch (error) {
|
|
@@ -9392,7 +9992,7 @@ export class AppServer {
|
|
|
9392
9992
|
void (async () => {
|
|
9393
9993
|
try {
|
|
9394
9994
|
const settled = await reconcileInterruptedRuns(this.directory, new Set(dead.map(owner => owner.runId)), { includePending: true });
|
|
9395
|
-
await reportInterruptedRuns({ home: this.directory, surface: configuredSurface('desktop') }, settled.interrupted);
|
|
9995
|
+
await reportInterruptedRuns({ home: this.directory, signals: this.telemetry.signals, surface: configuredSurface('desktop') }, settled.interrupted);
|
|
9396
9996
|
}
|
|
9397
9997
|
catch (recovery) {
|
|
9398
9998
|
this.log('warn', `Could not reconcile runs from a stopped engine: ${message(recovery)}`);
|
|
@@ -9420,11 +10020,19 @@ export class AppServer {
|
|
|
9420
10020
|
if (this.closed)
|
|
9421
10021
|
return;
|
|
9422
10022
|
this.closed = true;
|
|
10023
|
+
this.telemetry.close();
|
|
10024
|
+
for (const startup of this.antigravityStartups)
|
|
10025
|
+
startup.abort();
|
|
10026
|
+
const antigravitySessions = [...this.antigravitySessions.values()];
|
|
10027
|
+
this.antigravitySessions.clear();
|
|
10028
|
+
await Promise.allSettled(antigravitySessions.map(entry => {
|
|
10029
|
+
entry.clearPermissions();
|
|
10030
|
+
return entry.session.close();
|
|
10031
|
+
}));
|
|
9423
10032
|
await this.codexAuth.close().catch(() => { });
|
|
9424
10033
|
await this.anthropicAuth.close().catch(() => { });
|
|
9425
10034
|
await this.claudeSignIn.close().catch(() => { });
|
|
9426
10035
|
await this.grokSignIn.close().catch(() => { });
|
|
9427
|
-
await this.googleSignIn.close().catch(() => { });
|
|
9428
10036
|
await this.openCodeSignIn.close().catch(() => { });
|
|
9429
10037
|
await sharedOpenCodeServer().close().catch(() => { });
|
|
9430
10038
|
if (this.automationCheck)
|
|
@@ -9473,7 +10081,7 @@ export class AppServer {
|
|
|
9473
10081
|
this.stopBackgroundWatch();
|
|
9474
10082
|
await Promise.allSettled([disposePooledPowerShell(), disposeAllQaProcesses(), disposeAllQaPtys()]);
|
|
9475
10083
|
await this.telemetrySettle;
|
|
9476
|
-
await drainTelemetry({ home: this.directory, surface: configuredSurface('desktop') });
|
|
10084
|
+
await drainTelemetry({ home: this.directory, signals: this.telemetry.signals, surface: configuredSurface('desktop') });
|
|
9477
10085
|
this.emitsStopped = true;
|
|
9478
10086
|
this.stopGraphVisibilityWatch();
|
|
9479
10087
|
this.terminals.shutdown();
|
|
@@ -9515,7 +10123,7 @@ export async function runAppServer(options = {}) {
|
|
|
9515
10123
|
const error = options.error ?? process.stderr;
|
|
9516
10124
|
try {
|
|
9517
10125
|
const recovered = await reconcileInterruptedRuns(options.directory ?? configDirectory(), undefined, { includePending: true });
|
|
9518
|
-
await reportInterruptedRuns({ home: options.directory ?? configDirectory(), surface: configuredSurface('desktop') }, recovered.interrupted);
|
|
10126
|
+
await reportInterruptedRuns({ home: options.directory ?? configDirectory(), signals: server.telemetry.signals, surface: configuredSurface('desktop') }, recovered.interrupted);
|
|
9519
10127
|
if (recovered.runs.length || recovered.markers)
|
|
9520
10128
|
error.write(`[app-server] marked ${recovered.runs.length} interrupted run(s) and ${recovered.markers} session marker(s) from a stopped engine\n`);
|
|
9521
10129
|
server.watchForeignEngineShutdown(recovered.live);
|