@andorra-labs/code 0.1.17 → 0.1.18

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.
Files changed (94) hide show
  1. package/dist/src/agent-execution.js +97 -11
  2. package/dist/src/andorra/errors.js +3 -0
  3. package/dist/src/app-server/protocol.d.ts +13 -2
  4. package/dist/src/app-server/protocol.js +1 -1
  5. package/dist/src/app-server/workspace.d.ts +19 -0
  6. package/dist/src/app-server/workspace.js +155 -4
  7. package/dist/src/app-server.d.ts +32 -1
  8. package/dist/src/app-server.js +622 -74
  9. package/dist/src/attachments.d.ts +10 -0
  10. package/dist/src/attachments.js +102 -7
  11. package/dist/src/automation-tool.js +2 -1
  12. package/dist/src/bridge/command.js +12 -0
  13. package/dist/src/bridge/control.d.ts +3 -1
  14. package/dist/src/bridge/control.js +7 -2
  15. package/dist/src/bridge/github.d.ts +108 -0
  16. package/dist/src/bridge/github.js +378 -0
  17. package/dist/src/bridge/host-ops.d.ts +1 -1
  18. package/dist/src/bridge/host-ops.js +11 -1
  19. package/dist/src/bridge/host.js +7 -4
  20. package/dist/src/bug-report-attachments.d.ts +48 -0
  21. package/dist/src/bug-report-attachments.js +327 -0
  22. package/dist/src/bug-report.d.ts +23 -3
  23. package/dist/src/bug-report.js +72 -9
  24. package/dist/src/cli.d.ts +1 -3
  25. package/dist/src/cli.js +10 -4
  26. package/dist/src/codex-provider.js +1 -1
  27. package/dist/src/coding-tools.js +9 -2
  28. package/dist/src/commands.d.ts +1 -1
  29. package/dist/src/commands.js +2 -1
  30. package/dist/src/completion.js +8 -4
  31. package/dist/src/config.js +3 -1
  32. package/dist/src/context-budget.js +15 -2
  33. package/dist/src/decision/DecisionEngine.d.ts +2 -0
  34. package/dist/src/decision/DecisionManager.d.ts +11 -0
  35. package/dist/src/decision/DecisionManager.js +36 -0
  36. package/dist/src/decision/applyTaskKind.d.ts +8 -0
  37. package/dist/src/decision/applyTaskKind.js +53 -0
  38. package/dist/src/decision/hostedPolicy.js +2 -1
  39. package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +2 -0
  40. package/dist/src/decision/providers/AndorraDecisionProvider.js +12 -0
  41. package/dist/src/decision/taskKind.d.ts +52 -0
  42. package/dist/src/decision/taskKind.js +76 -0
  43. package/dist/src/decision/types.d.ts +1 -1
  44. package/dist/src/default-graph.js +1 -1
  45. package/dist/src/efficiency.d.ts +5 -0
  46. package/dist/src/efficiency.js +5 -1
  47. package/dist/src/effort-routing.d.ts +27 -0
  48. package/dist/src/effort-routing.js +34 -0
  49. package/dist/src/evidence.d.ts +110 -0
  50. package/dist/src/evidence.js +195 -0
  51. package/dist/src/github-app/client.d.ts +19 -0
  52. package/dist/src/github-app/client.js +21 -1
  53. package/dist/src/github-names.d.ts +7 -0
  54. package/dist/src/github-names.js +7 -0
  55. package/dist/src/graph-preview.d.ts +2 -0
  56. package/dist/src/graph-preview.js +1 -0
  57. package/dist/src/graph-runner.js +1 -1
  58. package/dist/src/graph-server.js +4 -2
  59. package/dist/src/graph-ui/app.js +30 -0
  60. package/dist/src/graphs.d.ts +6 -0
  61. package/dist/src/graphs.js +7 -2
  62. package/dist/src/hardened-runtime.js +32 -21
  63. package/dist/src/model-health-cache.js +1 -1
  64. package/dist/src/model-override.d.ts +2 -1
  65. package/dist/src/model-override.js +9 -0
  66. package/dist/src/model-tiers.d.ts +3 -0
  67. package/dist/src/model-tiers.js +3 -3
  68. package/dist/src/provider-engine.d.ts +13 -1
  69. package/dist/src/provider-engine.js +74 -0
  70. package/dist/src/providers.d.ts +5 -0
  71. package/dist/src/providers.js +34 -8
  72. package/dist/src/pull-requests.d.ts +11 -1
  73. package/dist/src/pull-requests.js +53 -2
  74. package/dist/src/react-runtime.js +98 -15
  75. package/dist/src/remote/engine-pool.js +5 -5
  76. package/dist/src/runtime.d.ts +29 -1
  77. package/dist/src/runtime.js +8 -0
  78. package/dist/src/sessions.d.ts +24 -0
  79. package/dist/src/sessions.js +55 -2
  80. package/dist/src/skills/bundled/bug-report/SKILL.md +51 -7
  81. package/dist/src/skills/bundled/provenance.json +1 -1
  82. package/dist/src/task-checkout.d.ts +141 -0
  83. package/dist/src/task-checkout.js +558 -0
  84. package/dist/src/test-edit-guard.d.ts +30 -0
  85. package/dist/src/test-edit-guard.js +167 -2
  86. package/dist/src/thinking-level-detect.d.ts +11 -0
  87. package/dist/src/thinking-level-detect.js +47 -0
  88. package/dist/src/thinking-levels.d.ts +30 -0
  89. package/dist/src/thinking-levels.js +124 -0
  90. package/dist/src/timers.d.ts +1 -0
  91. package/dist/src/tool-catalog.js +1 -1
  92. package/dist/src/transcript.js +1 -1
  93. package/dist/src/types.d.ts +34 -0
  94. package/package.json +1 -1
@@ -30,11 +30,13 @@ import { anthropicAccountHome } from './anthropic-credentials.js';
30
30
  import { codexAccountHome } from './codex-rpc.js';
31
31
  import { configuredModelSnapshot, discoverModelMetadata, resolveModelContext, resolveModelContextWindows } from './model-metadata.js';
32
32
  import { liveModelTarget } from './live-model.js';
33
- import { graphLeavesNodesToSession, graphMcpServers, isDeletedGraph, isReservedGraphId, listGraphs, loadGraph, maxNodeVisitsOf, withoutDeletedGraphs } from './graphs.js';
33
+ import { graphLeavesNodesToSession, graphMcpServers, isDeletedGraph, isNodeReasoningEffort, isReservedGraphId, listGraphs, loadGraph, maxNodeVisitsOf, withoutDeletedGraphs } from './graphs.js';
34
34
  import { exportAgentDefinition, readAgentDefinition } from './agent-definitions.js';
35
35
  import { blockingHealthFailures, checkGraphModelHealth, formatGraphHealthFailure, resumeModelNodes } from './graph-health.js';
36
36
  import { bindPortableGraphProviders, GraphProviderUnavailableError } from './graph-provider-portability.js';
37
37
  import { applyModelOverride, applyNodeModelOverrides } from './model-override.js';
38
+ import { autoLevels, enabledLevels, nearestEnabled, withDetectedLevels, withDisabledLevels } from './thinking-levels.js';
39
+ import { detectProviderLevels } from './thinking-level-detect.js';
38
40
  import { freeTierGraphViolation, notePremiumGraphAccount, readGraphQuota } from './graph-quota.js';
39
41
  import { RETIRED_ANDORRA_SELECTION, SOFTWARE_ENGINEER_HARNESS, createMembershipClient, currentGraphSelection, getGraphMembership, getMembership, loadAccessibleGraph, membershipPlanLabel, relayedGraph } from './membership.js';
40
42
  import { loadProfile, saveProfile, ProfileAccountError, ProfileTextError } from './profile.js';
@@ -45,7 +47,9 @@ import { configuredGraphSelection, currentGraphSubject, identityStillHolds } fro
45
47
  import { announceGraphVisibilityChange, graphVisibilityFor, importGraphVisibility, onGraphVisibilityChange, relinkGraphVisibility, setGraphVisibility } from './graph-visibility.js';
46
48
  import { graphStorageAccess } from './graph-account.js';
47
49
  import { GraphAccessSync } from './graph-sync.js';
48
- import { canExtendLineage, displayHistory, hiddenSession, lineagePoints, lineageThrough, SessionStore, projectIdentity, removeSessionSnapshot, savedSessionFields, sessionName, validSavedSession } from './sessions.js';
50
+ import { checkoutState, discardPreparedWorktree, forgetPrepared, inPlaceCheckout, inspectWorktreeRemoval, locateTaskWorktree, prepareTaskWorktree, recreateTaskWorktree, removeTaskWorktree, takePrepared, taskStartPoints, TaskCheckoutError, worktreeInstructions } from './task-checkout.js';
51
+ import { cleanRecorded, COMMAND_LIMIT, outputTail, readRevision, resolveEvidence } from './evidence.js';
52
+ import { reviewAfterTurn, canExtendLineage, displayHistory, hiddenSession, lineagePoints, lineageThrough, SessionStore, projectIdentity, removeSessionSnapshot, savedSessionFields, sessionName, validSavedSession } from './sessions.js';
49
53
  import { folderChangeBusy, folderChangeHeld, reserveFolderChange } from './project-reservation.js';
50
54
  import { writePendingAgentInteraction, removePendingAgentInteraction } from './session-monitor.js';
51
55
  import { summarizeSessionPrompt, titleRequestSupported } from './session-summary.js';
@@ -60,7 +64,7 @@ import { actionsJobOf, fixChecksPrompt, jobId } from './pull-request-logs.js';
60
64
  import { issueNamedIn, readRepositoryIssues, readReviewRequests } from './github-inbox.js';
61
65
  import { changeReviewers, commentBody, draftComments, failedRunIds, githubLogin, nodeId, replyToThread, rerunFailedJobs, reviewerEntries, reviewerLogins, reviewEvent, reviewPath, runIds, setFileViewed, setThreadResolved, submitReview, teamSlugs, } from './pull-request-review.js';
62
66
  import { chatReviewLoopActive, parseReviewModel, reviewLoopActive, reviewLoopSettings, REVIEW_SETTING_KEYS } from './pull-requests.js';
63
- import { confirmAutoFixWake, handedOver, isFinishedPullRequest, settleFinishedPullRequest, withChecks, markAutoFixDelivered, withoutPendingFix, 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, writePullRequest } from './pull-requests.js';
67
+ import { confirmAutoFixWake, handedOver, isFinishedPullRequest, settleFinishedPullRequest, withChecks, markAutoFixDelivered, withoutPendingFix, 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, viewPullRequest, withPullRequest, writePullRequest } from './pull-requests.js';
64
68
  import { AutomationStore } from './automations.js';
65
69
  import { executeAutomation } from './automation-runner.js';
66
70
  import { automationService, automationServiceRunning, reconcileAutomationService } from './automation-service.js';
@@ -68,6 +72,7 @@ import { runGraph, stopReasonPhrase, timerReminderText, wakeMessageText } from '
68
72
  import { configuredSurface, createRunHandle, drainTelemetry, graphShape, reportGitHubWatch, reportInterruptedRuns, reportRunFinished, reportRunStarted, reportSessionStarted } from './telemetry/surface.js';
69
73
  import { telemetryGate } from './telemetry/gate.js';
70
74
  import { accountApiTarget, defaultGitHubAppClient, GitHubAppError } from './github-app/client.js';
75
+ import { GITHUB_ACCOUNT, GITHUB_REPO } from './github-names.js';
71
76
  import { GitHubEventSource } from './github-app/event-source.js';
72
77
  import { MentionTriggers } from './github-app/triggers.js';
73
78
  import { applyReviewSettings, coverageAllowsReview, coverageRefusal, ReviewLoopController } from './github-app/review-loop.js';
@@ -85,7 +90,7 @@ import { ArtifactStore } from './artifacts.js';
85
90
  import { coverUnsavedToolCalls, mergeRunProgress, replayRunJournal, toolBoundaryOpen } from './run-progress.js';
86
91
  import { compactHistory, compactedContextEstimate } from './commands.js';
87
92
  import { readFavicon } from './favicons.js';
88
- import { attachmentReferenceBlock, loadResolvedImages, parsePendingAttachments, pruneAttachments, readSpooledImage, readSpooledText, relinkAttachmentPath, resolveAttachments, attachmentReadRoots } from './attachments.js';
93
+ import { attachmentReferenceBlock, cloudAttachments, loadResolvedImages, parsePendingAttachments, pruneAttachments, readSpooledImage, readSpooledText, relinkAttachmentPath, resolveAttachments, attachmentReadRoots } from './attachments.js';
89
94
  import { extensionSnapshot, effectiveExtensionConfig, listBundles, installBundle, removeBundle, removeBundleTransactional, setBundleEnabled, listSkillResources, readSkillResource, writeSkillResource, resolveSkillInvocations } from './extensions.js';
90
95
  import { isBuiltinSlashCommand } from './skill-commands.js';
91
96
  import { applyGoalCommand, isGoalCommand, metSessionGoal } from './session-goal.js';
@@ -112,7 +117,7 @@ import { createBrowserIncognitoTool, createBrowserPanelTool, createPanelBrowserH
112
117
  import { createBrowserExtensionsTool, EXTENSIONS_OPERATION, relayExtensionSteps, validateExtensionStep } from './browser-extensions-tool.js';
113
118
  import { resolveCapsolverKey } from './capsolver.js';
114
119
  import { resolveWebSearchProvider } from './web-search.js';
115
- import { checkoutBranch, gitDiff, gitStatus, listBranches, listExtensions, listRuns, readRun, readSessionTrajectory, runRecordFile, sessionTrajectoryFile, gitLinkBase, listWorkspaceFiles, readTree, readWorkspaceFile, searchOptions, searchWorkspace, summarizeMcpServer, workspaceRoot, writeTarget } from './app-server/workspace.js';
120
+ import { checkoutBranch, gitDiff, gitStatus, listBranches, listExtensions, listRuns, readRun, readSessionTrajectory, runRecordFile, sessionTrajectoryFile, gitLinkBase, listWorkspaceFiles, readTree, readWorkspaceFile, readWorkspaceImage, searchOptions, searchWorkspace, summarizeMcpServer, workspaceRoot, writeTarget } from './app-server/workspace.js';
116
121
  import { andorraGetToolPath } from '../vendor/engine/runtime/coding-agent/utils/tools-manager.js';
117
122
  /** Where ripgrep is, looked up once a minute: the lookup can run `rg --version`, which should not happen per keystroke. */
118
123
  let ripgrepLookup;
@@ -344,6 +349,10 @@ function managedAuthView(type, view, includeUrl) {
344
349
  }
345
350
  return result;
346
351
  }
352
+ /** When a first automatic title never lands (refused run, failed or cut-short request), each retry waits this long; the last one is the last try. */
353
+ const TITLE_RETRY_DELAYS_MS = [60_000, 180_000];
354
+ /** How often a retry may find its session busy and step back without spending one of the attempts above. */
355
+ const MAX_TITLE_RETRY_DEFERRALS = 10;
347
356
  function profileSubject(params) {
348
357
  const subject = params.subject;
349
358
  if (subject === undefined)
@@ -493,6 +502,7 @@ function providerView(provider, providers) {
493
502
  ...(provider.textOnlyModels === undefined ? {} : { textOnlyModels: [...provider.textOnlyModels] }),
494
503
  ...(provider.contextWindow === undefined ? {} : { contextWindow: provider.contextWindow }),
495
504
  ...(provider.reasoningEffort === undefined ? {} : { reasoningEffort: provider.reasoningEffort }),
505
+ ...(provider.thinkingLevels === undefined ? {} : { thinkingLevels: structuredClone(provider.thinkingLevels) }),
496
506
  ...(provider.requestTimeoutMs === undefined ? {} : { requestTimeoutMs: provider.requestTimeoutMs }),
497
507
  ...(provider.streamIdleTimeoutMs === undefined ? {} : { streamIdleTimeoutMs: provider.streamIdleTimeoutMs }),
498
508
  ...(providers === undefined ? {} : { label: providerLabel(provider, providers) }),
@@ -651,6 +661,9 @@ export function mergeProviderSecrets(stored, incoming) {
651
661
  if (previousEntry?.modelContextWindows !== undefined)
652
662
  provider.modelContextWindows = previousEntry.modelContextWindows;
653
663
  }
664
+ // Thinking levels are set through their own requests, so a provider list saved by a client never drops them.
665
+ if (previousEntry?.thinkingLevels !== undefined && typeof provider.type === 'string' && supportsReasoningEffort(provider.type))
666
+ provider.thinkingLevels = structuredClone(previousEntry.thinkingLevels);
654
667
  // The engine keeps an Andorra entry's display names from the router; a client never sets them.
655
668
  if (provider.type === 'andorra' && previousEntry?.type === 'andorra' && previousEntry.modelNames !== undefined)
656
669
  provider.modelNames = { ...previousEntry.modelNames };
@@ -730,6 +743,44 @@ const AUTO_FIX_CONFIRM_RETRY_MS = 60_000;
730
743
  function pullRequestForClients(pullRequest) {
731
744
  return pullRequest ? { ...pullRequest, autoArchive: false } : null;
732
745
  }
746
+ /** How many commands a turn's evidence keeps a record of: the newest are the ones outcomes cite. */
747
+ const MAX_TURN_OBSERVATIONS = 200;
748
+ /** Notes when the agent edits files, so evidence can say a check was followed by edits. */
749
+ function notingEdits(recorder, edits) {
750
+ // Only writes the recorder takes (inside the workspace) count, and only once they land.
751
+ return {
752
+ beforeWrite: async (targets) => {
753
+ const recording = await recorder.beforeWrite(targets);
754
+ if (recording === undefined)
755
+ return recording;
756
+ return { begin: () => recording.begin(), abort: () => recording.abort(), commit: async () => { edits.push(new Date().toISOString()); await recording.commit(); } };
757
+ },
758
+ };
759
+ }
760
+ /** The prepared worktree a run.start names (`checkout: { prepared }`), or undefined for a task in its project folder. */
761
+ function preparedCheckoutKey(value) {
762
+ if (value === undefined || value === null)
763
+ return undefined;
764
+ if (typeof value !== 'object' || Array.isArray(value))
765
+ throw new AppServerError('invalid-params', 'checkout must be an object');
766
+ const entry = value;
767
+ if (entry.inPlace === true && entry.prepared === undefined)
768
+ return undefined;
769
+ if (typeof entry.prepared !== 'string' || !/^[A-Za-z0-9_-]{8,64}$/.test(entry.prepared))
770
+ throw new AppServerError('invalid-params', 'checkout.prepared must be the key of a prepared worktree');
771
+ return entry.prepared;
772
+ }
773
+ /** The folder a task's Git work happens in; refused when its worktree was removed, rather than using the lead's checkout. */
774
+ function sessionGitRoot(record) {
775
+ if (record.checkout?.kind === 'worktree' && record.checkout.removedAt !== undefined) {
776
+ throw new AppServerError('checkout-missing', 'This task’s worktree was removed. Recreate it from the task, then try again.');
777
+ }
778
+ return sessionWorkRoot(record);
779
+ }
780
+ /** The folder a task works in: its own worktree while it stands, else its project folder. */
781
+ function sessionWorkRoot(record) {
782
+ return record.checkout?.kind === 'worktree' && record.checkout.removedAt === undefined ? record.checkout.path : record.workspace;
783
+ }
733
784
  function sessionSummary(record) {
734
785
  const finished = record.history?.length
735
786
  ? record.history[record.history.length - 1].completion?.status ?? 'succeeded'
@@ -741,6 +792,8 @@ function sessionSummary(record) {
741
792
  ...(record.archived === undefined ? {} : { archived: record.archived }),
742
793
  ...(record.pinned === true ? { pinned: true } : {}),
743
794
  ...(record.jevEnabled === undefined ? {} : { jevEnabled: record.jevEnabled }),
795
+ ...(record.checkout === undefined ? {} : { checkout: record.checkout }),
796
+ ...(record.review === undefined ? {} : { review: record.review }),
744
797
  ...(record.history?.length ? { lastTask: record.history[record.history.length - 1].direction ?? record.history[record.history.length - 1].task } : {}),
745
798
  ...(finished === undefined ? {} : { lastTurnStatus: finished }),
746
799
  usage: { inputTokens: record.usage.inputTokens, outputTokens: record.usage.outputTokens, requests: record.usage.requests, ...(record.usage.cacheRead === undefined ? {} : { cacheRead: record.usage.cacheRead }), ...(record.usage.cacheWrite === undefined ? {} : { cacheWrite: record.usage.cacheWrite }),
@@ -784,7 +837,9 @@ const REVIEW_WAIT_RECORD_TICKS = 5;
784
837
  export function isFinalWakeRefusal(error) {
785
838
  return error instanceof AppServerError
786
839
  && (error.code === 'invalid-params' || error.code === 'not-found' || error.code === 'remote'
787
- || error.code === 'unknown-method' || error.code === 'auth' || error.code === 'nothing-to-continue');
840
+ || error.code === 'unknown-method' || error.code === 'auth' || error.code === 'nothing-to-continue'
841
+ // A task whose worktree is gone cannot wake until the lead recovers it; retrying every few seconds helps nothing.
842
+ || error.code === 'checkout-missing');
788
843
  }
789
844
  const keptPullRequestMessage = (pullRequest) => `${pullRequest.url} is ${pullRequest.state}, so it stays on this task: it is how the user sees what became of the work. Nothing was changed, and there is nothing to clean up here. Only the user removes a ${pullRequest.state} pull request, with Dismiss in its menu.`;
790
845
  function outcomeCompletion(status, reason, limits) {
@@ -846,8 +901,9 @@ function readNodeModelOverrides(value) {
846
901
  const model = entry.model;
847
902
  if (typeof provider !== 'string' || !provider || typeof model !== 'string' || !model)
848
903
  continue;
904
+ const level = entry.reasoningEffort;
849
905
  read ??= {};
850
- read[id] = { provider, model };
906
+ read[id] = { provider, model, ...(isNodeReasoningEffort(level) ? { reasoningEffort: level } : {}) };
851
907
  }
852
908
  return read;
853
909
  }
@@ -1071,7 +1127,8 @@ export class AppServer {
1071
1127
  titleReleases = new Map();
1072
1128
  titleAnswered = new Set(); // runs whose model has answered at least once
1073
1129
  sessionTitles = new Map();
1074
- workGeneration = 0;
1130
+ /** Automatic titles waiting to be asked again, by session, after an attempt was refused, failed, or cut short. */
1131
+ titleRetries = new Map();
1075
1132
  operations = new Set();
1076
1133
  prepareTask;
1077
1134
  foreignEngineWatch;
@@ -1148,6 +1205,7 @@ export class AppServer {
1148
1205
  return wakeId;
1149
1206
  },
1150
1207
  wakePending: id => this.timers.list().some(timer => timer.id === id),
1208
+ isWaiting: sessionId => this.reviewWaiters.has(sessionId) || this.reviewWaitsStarting.has(sessionId),
1151
1209
  log: (level, detail) => this.log(level, detail),
1152
1210
  covered: sessionId => this.githubEvents.covers(sessionId),
1153
1211
  onGhCall: sessionId => this.githubEvents.countGhCall(sessionId),
@@ -1216,7 +1274,7 @@ export class AppServer {
1216
1274
  const status = await readFile(runRecordPath(this.directory, runId, 'json'), 'utf8').then(text => JSON.parse(text).status, () => undefined);
1217
1275
  return status === 'interrupted' || status === 'running';
1218
1276
  },
1219
- workspace: async (sessionId) => (await this.readSession(sessionId).catch(() => undefined))?.workspace,
1277
+ workspace: async (sessionId) => { const record = await this.readSession(sessionId).catch(() => undefined); return record === undefined ? undefined : sessionWorkRoot(record); },
1220
1278
  defaultModel: async () => {
1221
1279
  const config = await loadConfig(this.directory);
1222
1280
  const provider = config.providers.find(entry => entry.id === config.provider);
@@ -1641,6 +1699,8 @@ export class AppServer {
1641
1699
  case 'andorra.remove': return this.hideListedEntry();
1642
1700
  case 'providers.discover': return this.discoverModels(params);
1643
1701
  case 'providers.test': return this.testProviderEndpoint(params);
1702
+ case 'providers.detectThinkingLevels': return this.detectThinkingLevels(params);
1703
+ case 'providers.setThinkingLevels': return this.setThinkingLevels(params);
1644
1704
  case 'providers.detectSignIns': return this.detectProviderSignIns(params);
1645
1705
  case 'providers.importSignIns': return this.importProviderSignIns(params);
1646
1706
  case 'providers.auth.status': return this.providerAuth('status', params);
@@ -1722,6 +1782,7 @@ export class AppServer {
1722
1782
  case 'github.status': return this.githubStatus();
1723
1783
  case 'github.connect': return this.githubConnect(params);
1724
1784
  case 'github.disconnect': return this.githubDisconnect();
1785
+ case 'github.repositories': return this.githubRepositories();
1725
1786
  case 'github.setAgentWrites': return this.githubSetAgentWrites(params);
1726
1787
  case 'issues.list': return this.listWorkspaceIssues(params);
1727
1788
  case 'sessions.changes.list': return this.sessionChanges.list(changesSessionId(params.id), diffLines(params.maxLines, LIST_DIFF_LINES));
@@ -2019,6 +2080,15 @@ export class AppServer {
2019
2080
  const root = await workspaceRoot(params.workspace);
2020
2081
  return readWorkspaceFile(root, params.path);
2021
2082
  }
2083
+ case 'workspace.image': {
2084
+ const root = await workspaceRoot(params.workspace);
2085
+ try {
2086
+ return await readWorkspaceImage(root, params.path);
2087
+ }
2088
+ catch (error) {
2089
+ throw new AppServerError('invalid-params', message(error));
2090
+ }
2091
+ }
2022
2092
  case 'workspace.write': {
2023
2093
  const root = await workspaceRoot(params.workspace);
2024
2094
  if (params.sessionId !== undefined && (typeof params.sessionId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(params.sessionId)))
@@ -2085,6 +2155,20 @@ export class AppServer {
2085
2155
  return listBranches(root);
2086
2156
  }
2087
2157
  case 'workspace.checkout': return this.switchBranch(params);
2158
+ case 'workspace.startPoints': {
2159
+ const root = await workspaceRoot(params.workspace);
2160
+ return taskStartPoints(root);
2161
+ }
2162
+ case 'workspace.prepareTask': return this.prepareTaskCheckout(params);
2163
+ case 'workspace.discardPrepared': {
2164
+ const root = await workspaceRoot(params.workspace);
2165
+ return { removed: await discardPreparedWorktree(this.directory, root, text(params.key, 'key', 64)) };
2166
+ }
2167
+ case 'sessions.setReviewed': return { session: this.summary(await this.setSessionReviewed(params)) };
2168
+ case 'sessions.checkout.state': return this.sessionCheckoutState(params);
2169
+ case 'sessions.checkout.recover': return { session: this.summary(await this.recoverSessionCheckout(params)) };
2170
+ case 'sessions.checkout.inspect': return this.inspectSessionCheckout(params);
2171
+ case 'sessions.checkout.remove': return this.removeSessionCheckout(params);
2088
2172
  case 'workspace.diff': {
2089
2173
  const root = await workspaceRoot(params.workspace);
2090
2174
  return gitDiff(root, { path: params.path, staged: params.staged, base: params.base });
@@ -2135,6 +2219,7 @@ export class AppServer {
2135
2219
  case 'remote.owner.roots': return this.remoteOwnerRoots(params);
2136
2220
  case 'remote.owner.browse': return this.remoteOwnerBrowse(params);
2137
2221
  case 'remote.owner.projects.add': return this.remoteOwnerAddProject(params);
2222
+ case 'remote.owner.github.clone': return this.remoteOwnerGitHubClone(params);
2138
2223
  case 'remote.engine.connect': return this.remoteEngineConnect(params);
2139
2224
  case 'remote.engine.request': return this.remoteEngineRequest(params);
2140
2225
  case 'remote.engine.disconnect': return this.remoteEngineDisconnect(params);
@@ -2854,6 +2939,65 @@ export class AppServer {
2854
2939
  throw new AppServerError('network', message(error));
2855
2940
  }
2856
2941
  }
2942
+ thinkingLevelTarget(config, params) {
2943
+ const id = identifier(params.providerId, 'providerId');
2944
+ const provider = config.providers.find(item => item.id === id);
2945
+ if (!provider)
2946
+ throw new AppServerError('not-found', `Unknown provider: ${id}`);
2947
+ if (!supportsReasoningEffort(provider.type) || provider.type === 'relayed')
2948
+ throw new AppServerError('invalid-params', `The ${provider.type} provider does not take a thinking level`);
2949
+ const model = params.model === undefined ? provider.model : params.model;
2950
+ if (typeof model !== 'string' || !model.trim() || model.length > 500)
2951
+ throw new AppServerError('invalid-params', 'model must be a non-empty model id');
2952
+ return { provider, model: model.trim() };
2953
+ }
2954
+ thinkingLevelsView(provider, model, detected) {
2955
+ const entry = provider.thinkingLevels?.[model];
2956
+ return { providerId: provider.id, model, detected, supported: entry?.supported ?? [...REASONING_EFFORTS], disabled: entry?.disabled ?? [], enabled: enabledLevels(provider, model) };
2957
+ }
2958
+ /** Finds out which thinking levels a model accepts and saves them. An inconclusive answer saves nothing. */
2959
+ async detectThinkingLevels(params) {
2960
+ const { provider, model } = this.thinkingLevelTarget(await loadConfig(this.directory), params);
2961
+ let supported;
2962
+ try {
2963
+ supported = await this.operation(90_000, signal => detectProviderLevels(provider, model, signal));
2964
+ }
2965
+ catch (error) {
2966
+ throw new AppServerError('network', message(error));
2967
+ }
2968
+ if (supported === undefined)
2969
+ return this.thinkingLevelsView(provider, model, false);
2970
+ const saved = await this.saveThinkingLevels(provider.id, current => withDetectedLevels(current, model, supported));
2971
+ return this.thinkingLevelsView(saved, model, true);
2972
+ }
2973
+ async setThinkingLevels(params) {
2974
+ const { provider, model } = this.thinkingLevelTarget(await loadConfig(this.directory), params);
2975
+ const disabled = params.disabled;
2976
+ if (!Array.isArray(disabled) || disabled.some(level => typeof level !== 'string' || !REASONING_EFFORTS.includes(level))) {
2977
+ throw new AppServerError('invalid-params', `disabled must list thinking levels: ${REASONING_EFFORTS.join(', ')}`);
2978
+ }
2979
+ let saved;
2980
+ try {
2981
+ saved = await this.saveThinkingLevels(provider.id, current => withDisabledLevels(current, model, disabled));
2982
+ }
2983
+ catch (error) {
2984
+ if (error instanceof AppServerError)
2985
+ throw error;
2986
+ throw new AppServerError('invalid-params', message(error));
2987
+ }
2988
+ return this.thinkingLevelsView(saved, model, saved.thinkingLevels?.[model]?.supported !== undefined);
2989
+ }
2990
+ async saveThinkingLevels(id, change) {
2991
+ let next;
2992
+ await changeConfigFile(this.directory, current => {
2993
+ const at = current.providers.findIndex(item => item.id === id);
2994
+ if (at < 0)
2995
+ throw new AppServerError('not-found', `Unknown provider: ${id}`);
2996
+ next = change(current.providers[at]);
2997
+ return { ...current, providers: current.providers.map((item, index) => index === at ? next : item) };
2998
+ });
2999
+ return next;
3000
+ }
2857
3001
  operation(deadlineMs, run) {
2858
3002
  const controller = new AbortController();
2859
3003
  const timer = deadlineMs === undefined ? undefined : setTimeout(() => controller.abort(), deadlineMs);
@@ -3211,11 +3355,15 @@ export class AppServer {
3211
3355
  widgets: record.widgets,
3212
3356
  context: record.context,
3213
3357
  };
3214
- await new SessionStore(this.directory).save(savedSessionFields(merged));
3215
- publish(merged);
3216
- if (merged.goal?.status === 'met' && metGoal !== undefined && merged.goal.setAt === metGoal.setAt)
3217
- this.emitSessionGoal(merged.id, merged.goal);
3218
- return merged;
3358
+ // A completed turn waits for the lead's review in Needs you; any other ending takes the task off that list.
3359
+ const review = reviewAfterTurn(merged.history, fresh?.review, record.updatedAt);
3360
+ const { review: _was, ...rest } = merged;
3361
+ const reviewed = review === undefined ? rest : { ...rest, review };
3362
+ await new SessionStore(this.directory).save(savedSessionFields(reviewed));
3363
+ publish(reviewed);
3364
+ if (reviewed.goal?.status === 'met' && metGoal !== undefined && reviewed.goal.setAt === metGoal.setAt)
3365
+ this.emitSessionGoal(reviewed.id, reviewed.goal);
3366
+ return reviewed;
3219
3367
  });
3220
3368
  }
3221
3369
  catch (error) {
@@ -3244,6 +3392,24 @@ export class AppServer {
3244
3392
  return updated;
3245
3393
  });
3246
3394
  }
3395
+ /** Marks a task's completed turn reviewed, as Needs you's Mark Reviewed does: only the turn the lead was shown. */
3396
+ async setSessionReviewed(params) {
3397
+ const id = identifier(params.id, 'id');
3398
+ const runId = identifier(params.runId, 'runId');
3399
+ return this.withSessionMutation(id, async () => {
3400
+ const record = await this.readSession(id);
3401
+ if (record.review === undefined)
3402
+ throw new AppServerError('not-found', 'That task has no finished turn waiting for review.');
3403
+ if (record.review.runId !== runId)
3404
+ throw new AppServerError('invalid-params', 'A newer turn of that task finished since you read it. Look at it before marking it reviewed.');
3405
+ if (record.review.reviewedAt !== undefined)
3406
+ return record;
3407
+ const updated = { ...record, review: { ...record.review, reviewedAt: new Date().toISOString() } };
3408
+ await this.store().save(savedSessionFields(updated));
3409
+ this.emit('session.updated', { session: this.summary(updated) });
3410
+ return updated;
3411
+ });
3412
+ }
3247
3413
  /** Pins or unpins a task in the rail. The pin is rail-owned like a rename, so this window's own run may be pinned too: the run carries it forward when it saves. */
3248
3414
  async setSessionPinned(params) {
3249
3415
  const id = identifier(params.id, 'id');
@@ -3472,13 +3638,123 @@ export class AppServer {
3472
3638
  this.checkout = undefined;
3473
3639
  }
3474
3640
  }
3641
+ /** Makes a writing task's worktree before its run starts; the same key returns the same worktree on a retry. */
3642
+ async prepareTaskCheckout(params) {
3643
+ const root = await workspaceRoot(params.workspace);
3644
+ const base = text(params.base, 'base', 200);
3645
+ const slug = text(params.slug, 'slug', MAX_TASK_CHARS);
3646
+ const key = text(params.key, 'key', 64);
3647
+ if (await folderChangeHeld(this.directory, root))
3648
+ throw new AppServerError('busy', folderChangeBusy);
3649
+ try {
3650
+ return await prepareTaskWorktree({ home: this.directory, root, base, slug, key });
3651
+ }
3652
+ catch (error) {
3653
+ if (error instanceof TaskCheckoutError)
3654
+ throw new AppServerError('invalid-params', error.message);
3655
+ throw error;
3656
+ }
3657
+ }
3658
+ async sessionCheckoutState(params) {
3659
+ const record = await this.readSession(identifier(params.id, 'id'));
3660
+ if (record.checkout === undefined)
3661
+ return { state: 'ok' };
3662
+ return { ...await checkoutState(record.checkout, resolve(record.workspace)), checkout: record.checkout };
3663
+ }
3664
+ refuseCheckoutChange(id, doing) {
3665
+ if (this.run?.sessionId === id || this.startingSession === id || this.starting || this.finishingSessionId === id)
3666
+ throw new AppServerError('busy', `That task is running. Stop the run or wait for it to finish, then ${doing}.`);
3667
+ }
3668
+ /** Recreates a task's missing worktree from its branch, or takes the folder it moved to. */
3669
+ async recoverSessionCheckout(params) {
3670
+ const id = identifier(params.id, 'id');
3671
+ if (params.mode !== 'recreate' && params.mode !== 'locate')
3672
+ throw new AppServerError('invalid-params', 'mode must be recreate or locate');
3673
+ const mode = params.mode;
3674
+ const picked = mode === 'locate' ? text(params.path, 'path', 4096) : undefined;
3675
+ this.refuseCheckoutChange(id, 'recover its worktree');
3676
+ return this.withSessionMutation(id, async () => {
3677
+ this.refuseCheckoutChange(id, 'recover its worktree');
3678
+ if (await sessionHasOpenRun(this.directory, id))
3679
+ throw new AppServerError('busy', 'That task is running in another window. Wait for it to finish, then recover its worktree.');
3680
+ const record = await this.readSession(id);
3681
+ if (record.checkout?.kind !== 'worktree')
3682
+ throw new AppServerError('invalid-params', 'That task does not work in a worktree of its own.');
3683
+ const root = resolve(record.workspace);
3684
+ let checkout;
3685
+ try {
3686
+ checkout = mode === 'recreate' ? await recreateTaskWorktree(record.checkout, root) : await locateTaskWorktree(record.checkout, root, picked);
3687
+ }
3688
+ catch (error) {
3689
+ if (error instanceof TaskCheckoutError)
3690
+ throw new AppServerError('invalid-params', error.message);
3691
+ throw error;
3692
+ }
3693
+ const updated = { ...record, checkout };
3694
+ await this.store().save(savedSessionFields(updated));
3695
+ this.emit('session.updated', { session: this.summary(updated) });
3696
+ return updated;
3697
+ });
3698
+ }
3699
+ async inspectSessionCheckout(params) {
3700
+ const id = identifier(params.id, 'id');
3701
+ const record = await this.readSession(id);
3702
+ if (record.checkout?.kind !== 'worktree' || record.checkout.removedAt !== undefined)
3703
+ throw new AppServerError('invalid-params', 'That task has no worktree of its own to remove.');
3704
+ const running = this.run?.sessionId === id || this.startingSession === id || await sessionHasOpenRun(this.directory, id);
3705
+ // A continuation shares its task's worktree: removing it leaves the other without one.
3706
+ const path = record.checkout.path;
3707
+ const sharedWith = (await this.store().list(record.workspace)).filter(other => other.id !== id && other.checkout?.kind === 'worktree' && other.checkout.removedAt === undefined && resolve(other.checkout.path) === resolve(path)).map(other => other.name);
3708
+ try {
3709
+ return { check: await inspectWorktreeRemoval(record.checkout, resolve(record.workspace)), running, checkout: record.checkout, sharedWith };
3710
+ }
3711
+ catch (error) {
3712
+ if (error instanceof TaskCheckoutError)
3713
+ throw new AppServerError('invalid-params', error.message);
3714
+ throw error;
3715
+ }
3716
+ }
3717
+ /** Removes a task's worktree after the lead saw what it holds; the branch stays when it has commits nothing else has. */
3718
+ async removeSessionCheckout(params) {
3719
+ const id = identifier(params.id, 'id');
3720
+ const expectDirty = params.expectDirty;
3721
+ if (typeof expectDirty !== 'number' || !Number.isSafeInteger(expectDirty) || expectDirty < 0)
3722
+ throw new AppServerError('invalid-params', 'expectDirty must be the number of files the check found');
3723
+ this.refuseCheckoutChange(id, 'remove its worktree');
3724
+ return this.withSessionMutation(id, async () => {
3725
+ this.refuseCheckoutChange(id, 'remove its worktree');
3726
+ if (await sessionHasOpenRun(this.directory, id))
3727
+ throw new AppServerError('busy', 'That task is running in another window. Wait for it to finish, then remove its worktree.');
3728
+ const record = await this.readSession(id);
3729
+ if (record.checkout?.kind !== 'worktree' || record.checkout.removedAt !== undefined)
3730
+ throw new AppServerError('invalid-params', 'That task has no worktree of its own to remove.');
3731
+ let removal;
3732
+ try {
3733
+ removal = await removeTaskWorktree(record.checkout, resolve(record.workspace), { expectDirty });
3734
+ }
3735
+ catch (error) {
3736
+ if (error instanceof TaskCheckoutError)
3737
+ throw new AppServerError('invalid-params', error.message);
3738
+ throw error;
3739
+ }
3740
+ const updated = { ...record, checkout: removal.checkout };
3741
+ await this.store().save(savedSessionFields(updated));
3742
+ const summary = this.summary(updated);
3743
+ this.emit('session.updated', { session: summary });
3744
+ return { session: summary, branchDeleted: removal.branchDeleted };
3745
+ });
3746
+ }
3475
3747
  assertRunning() {
3476
3748
  if (this.closed)
3477
3749
  throw new AppServerError('cancelled', 'The engine is shutting down.');
3478
3750
  }
3479
3751
  async prepareRun(params, internal) {
3480
- this.cancelSessionTitles();
3481
- this.workGeneration++;
3752
+ // New work owns the provider from here: abort the title work of the session it is about to use. A
3753
+ // brand-new session has no title of its own pending, so nothing is cancelled for it, and other
3754
+ // sessions' titles are left alone — a task started elsewhere never costs them their name.
3755
+ const titleSession = internal?.sameSession ?? (typeof params.sessionId === 'string' && params.sessionId ? params.sessionId : undefined);
3756
+ if (titleSession !== undefined)
3757
+ this.cancelSessionTitles(titleSession);
3482
3758
  const createdSpools = [];
3483
3759
  let releaseStartLock;
3484
3760
  if (internal?.sameSession !== undefined) {
@@ -3571,7 +3847,8 @@ export class AppServer {
3571
3847
  const modelId = carriedModel !== undefined
3572
3848
  ? (carriedModelConfigured ? carriedModel : provider.model)
3573
3849
  : (params.model === undefined ? provider.model : text(params.model, 'model', 200));
3574
- const effort = params.reasoningEffort === undefined || params.reasoningEffort === '' ? undefined : reasoningEffort(params.reasoningEffort);
3850
+ const autoEffort = params.reasoningEffort === 'auto';
3851
+ const effort = autoEffort || params.reasoningEffort === undefined || params.reasoningEffort === '' ? undefined : reasoningEffort(params.reasoningEffort);
3575
3852
  if (effort !== undefined && !supportsReasoningEffort(provider.type))
3576
3853
  throw new AppServerError('invalid-params', `The ${provider.type} provider does not support a thinking effort`);
3577
3854
  const overrideAllNodes = params.overrideAllNodes === true;
@@ -3632,7 +3909,8 @@ export class AppServer {
3632
3909
  throw new AppServerError('invalid-params', 'That session belongs to a different project');
3633
3910
  // The pin belongs to the task the user pinned; its continuation is listed under it and shares its place.
3634
3911
  const { archived: _archived, autoArchived: _autoArchived, pinned: _pinned, ...continued } = existing;
3635
- const { trajectoryId: _parentTrajectory, ...forked } = continued;
3912
+ // 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;
3636
3914
  if (!canExtendLineage(existing.ancestors)) {
3637
3915
  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.');
3638
3916
  }
@@ -3644,6 +3922,26 @@ export class AppServer {
3644
3922
  if (params.jevEnabled !== undefined && typeof params.jevEnabled !== 'boolean')
3645
3923
  throw new AppServerError('invalid-params', 'jevEnabled must be a boolean');
3646
3924
  record = { ...record, workspace: root, projectId: record.projectId ?? await this.projectIdFor(root), updatedAt: new Date().toISOString(), ...(params.jevEnabled === undefined ? {} : { jevEnabled: params.jevEnabled }) };
3925
+ // A new task records where it works; a follow-up goes on in that same place, which must still be there.
3926
+ const preparedKey = params.sessionId === undefined ? preparedCheckoutKey(params.checkout) : undefined;
3927
+ if (params.sessionId === undefined) {
3928
+ let checkout;
3929
+ try {
3930
+ checkout = preparedKey !== undefined ? await takePrepared(this.directory, root, preparedKey) : await inPlaceCheckout(root);
3931
+ }
3932
+ catch (error) {
3933
+ if (error instanceof TaskCheckoutError)
3934
+ throw new AppServerError('invalid-params', error.message);
3935
+ throw error;
3936
+ }
3937
+ record = { ...record, checkout };
3938
+ }
3939
+ else if (record.checkout !== undefined) {
3940
+ const state = await checkoutState(record.checkout, root);
3941
+ if (state.state !== 'ok')
3942
+ throw new AppServerError('checkout-missing', state.reason);
3943
+ }
3944
+ const workRoot = sessionWorkRoot(record);
3647
3945
  const controller = new AbortController();
3648
3946
  const runId = randomUUID();
3649
3947
  const telemetryRunId = randomUUID();
@@ -3996,7 +4294,7 @@ export class AppServer {
3996
4294
  surface: configuredSurface('desktop'),
3997
4295
  ...(accountSubject ? { accountSubject } : {}),
3998
4296
  telemetry: { runId: telemetryRunId, nodes: 0, subagents: false, jevEnabled: config.jevEnabled !== false && record.jevEnabled !== false, decisionRouting: config.decisions?.mode ?? 'off', permissionMode: internal?.inheritedPermissions ?? effective, startSent: false },
3999
- ...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }), ...(effort === undefined ? {} : { reasoningEffort: effort }),
4297
+ ...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }), ...(effort === undefined ? autoEffort ? { reasoningEffort: 'auto' } : {} : { reasoningEffort: effort }),
4000
4298
  ...(automationContext === undefined ? {} : { automationContext }),
4001
4299
  ...(internal?.inheritedPermissions === undefined ? {} : { permissions: internal.inheritedPermissions }),
4002
4300
  ...(overrideAllNodes ? { overrideAllNodes: true } : {}),
@@ -4042,14 +4340,14 @@ export class AppServer {
4042
4340
  throw error;
4043
4341
  }
4044
4342
  this.runAbort = undefined;
4045
- if (!claimProcessWorkspace(root, runId)) {
4343
+ if (!claimProcessWorkspace(workRoot, runId)) {
4046
4344
  throw new AppServerError('busy', 'This project is being worked in by another engine in this process.');
4047
4345
  }
4048
4346
  const liveSteers = [];
4049
4347
  const permissionControl = new RunControl();
4050
4348
  permissionControl.permissions = effective;
4051
4349
  permissionControl.yolo = effective === 'full-access';
4052
- this.run = { runId, sessionId: record.id, controller, workspace: root, steers: liveSteers, subagents: new Set(), steersClosed: false,
4350
+ this.run = { runId, sessionId: record.id, controller, workspace: root, workRoot, steers: liveSteers, subagents: new Set(), steersClosed: false,
4053
4351
  permissionControl, permissionRevision: 0, approvals: new Set(), boundPermissions: internal?.inheritedPermissions !== undefined,
4054
4352
  codeIntelPermissions: effective, ...(lineage.length === 0 ? {} : { lineage: [...lineage] }), ...(relay === undefined ? {} : { relayProviders: relay.providers }) };
4055
4353
  {
@@ -4062,6 +4360,8 @@ export class AppServer {
4062
4360
  }
4063
4361
  this.emit('session.updated', { session: sessionSummary(record) });
4064
4362
  this.emit('run.started', { runId, sessionId: record.id, task, graph: selection, provider: provider.id, model: modelId, workspace: root, permissions: effective, session: sessionSummary(record), ...(internal?.resumedFrom === undefined ? {} : { resumedFrom: internal.resumedFrom }), ...(resumedDirection === undefined ? {} : { direction: resumedDirection }), ...(attachments?.refs.length ? { attachments: attachments.refs } : {}), ...(wake === undefined ? {} : { wake }) });
4363
+ if (preparedKey !== undefined)
4364
+ void forgetPrepared(this.directory, preparedKey);
4065
4365
  bootMark('run.started.emitted');
4066
4366
  for (const text of resumeWarnings) {
4067
4367
  void this.recordRunEvent(runId, { type: 'run.resume.warning', time: new Date().toISOString(), data: { runId, sessionId: record.id, text } });
@@ -4071,7 +4371,7 @@ export class AppServer {
4071
4371
  const preparedGraph = resumedGraph ?? relayPrepared;
4072
4372
  const invocationText = internal?.resumedFrom === undefined ? task
4073
4373
  : internal.recoveredDirection === true || internal.wake !== undefined ? undefined : internal.direction;
4074
- const runTask = this.executeRun({ runId, startedAt, telemetryRunId, ...(accountSubject ? { accountSubject } : {}), ...(invocationText === undefined ? {} : { invocationText }), task, ...(note === undefined ? {} : { note }), ...(turnNote === undefined ? {} : { turnNote }), selection, providerId: provider.id, modelId, root, permissions: effective, liveSteers, ...(internal?.inheritedPermissions === undefined ? {} : { boundPermissions: internal.inheritedPermissions }), ...(effort === undefined ? {} : { reasoningEffort: effort }), ...(overrideAllNodes ? { overrideAllNodes: true } : {}), ...(modelPinned ? { modelPinned: true } : {}), ...(nodeModelOverrides === undefined ? {} : { nodeModelOverrides }), ...(panelRelay ? { panelBrowserRelay: 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 }) })
4374
+ const runTask = this.executeRun({ runId, startedAt, telemetryRunId, ...(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 } : {}), ...(modelPinned ? { modelPinned: true } : {}), ...(nodeModelOverrides === undefined ? {} : { nodeModelOverrides }), ...(panelRelay ? { panelBrowserRelay: 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 }) })
4075
4375
  .catch(error => this.log('error', `Run ${runId} failed: ${message(error)}`));
4076
4376
  this.runTask = runTask;
4077
4377
  runTask.finally(() => {
@@ -4086,7 +4386,6 @@ export class AppServer {
4086
4386
  return Promise.resolve();
4087
4387
  const controller = new AbortController();
4088
4388
  this.operations.add(controller);
4089
- const generation = this.workGeneration;
4090
4389
  this.sessionTitles.set(record.id, controller);
4091
4390
  const firstAnswer = new Promise(resolve => { this.titleReleases.set(runId, resolve); });
4092
4391
  const released = controller.signal.aborted ? Promise.resolve() : Promise.race([firstAnswer, new Promise(resolve => {
@@ -4094,25 +4393,20 @@ export class AppServer {
4094
4393
  })]);
4095
4394
  const settled = released
4096
4395
  // A run Andorra refused (unavailable, sign in, allowance, busy) ended without an answer: no second request follows the refusal.
4097
- .then(() => controller.signal.aborted || this.workGeneration !== generation || (provider.type === 'andorra' && !this.titleAnswered.has(runId)) ? '' : summarizeSessionPrompt(task, createAdapter(provider), modelId, controller.signal))
4396
+ .then(() => controller.signal.aborted || (provider.type === 'andorra' && !this.titleAnswered.has(runId)) ? '' : summarizeSessionPrompt(task, createAdapter(provider), modelId, controller.signal))
4098
4397
  .then(async (summary) => {
4099
- if (!summary || controller.signal.aborted || record.renamed === true)
4398
+ // No name landed: the run was refused, the request was cut short by new work, it failed, or the save
4399
+ // had to step aside. The retry asks again later instead of keeping the prompt's first words forever.
4400
+ if (!summary || controller.signal.aborted || record.renamed === true) {
4401
+ this.scheduleTitleRetry(record.id, task, provider, modelId, 0);
4100
4402
  return;
4101
- await this.withSessionMutation(record.id, async () => {
4102
- const ownRunId = this.run?.runId === runId ? runId
4103
- : this.finishingRunId === runId && this.finishingSessionId === record.id ? runId : undefined;
4104
- if (ownRunId === undefined && (this.run?.sessionId === record.id || await sessionHasOpenRun(this.directory, record.id)))
4105
- return;
4106
- const fresh = await this.readSession(record.id).catch(() => undefined);
4107
- if (!fresh || fresh.renamed === true || fresh.name === summary)
4108
- return;
4109
- if (ownRunId === undefined && (fresh.history ?? []).some(turn => turn.runId === runId && turn.completion?.status === 'running'))
4110
- return;
4111
- const titled = { ...fresh, name: summary };
4112
- await this.store().save(savedSessionFields(titled));
4113
- this.emit('session.updated', { session: this.summary(titled) });
4114
- });
4403
+ }
4404
+ if (await this.saveSessionTitle(record.id, runId, summary) === 'busy') {
4405
+ // The name was made but the session is claimed: stand back without spending an attempt.
4406
+ this.scheduleTitleRetry(record.id, task, provider, modelId, 0, 1);
4407
+ }
4115
4408
  })
4409
+ .catch(() => { this.scheduleTitleRetry(record.id, task, provider, modelId, 0); })
4116
4410
  .finally(() => {
4117
4411
  this.titleReleases.delete(runId);
4118
4412
  this.titleAnswered.delete(runId);
@@ -4125,6 +4419,94 @@ export class AppServer {
4125
4419
  tracked.finally(() => { this.requests.delete(tracked); });
4126
4420
  return settled;
4127
4421
  }
4422
+ /** Saves an automatic title under the same lock and guards a user rename takes. */
4423
+ /** `saved`: the name landed. `busy`: a run owns the session — the title can land once it settles. `stale`: the record is gone, renamed, already carrying the name, or waiting on a failed final save that recovery owns. */
4424
+ async saveSessionTitle(recordId, runId, summary) {
4425
+ return await this.withSessionMutation(recordId, async () => {
4426
+ // A retry names a session with no run of its own: its guards must stay active, so an undefined
4427
+ // run id stays undefined here (a `&&` chain would yield false and skip every check below).
4428
+ const ownRunId = runId === undefined ? undefined : this.run?.runId === runId ? runId
4429
+ : this.finishingRunId === runId && this.finishingSessionId === recordId ? runId : undefined;
4430
+ if (ownRunId === undefined && (this.run?.sessionId === recordId || await sessionHasOpenRun(this.directory, recordId)))
4431
+ return 'busy';
4432
+ const fresh = await this.readSession(recordId).catch(() => undefined);
4433
+ if (!fresh || fresh.renamed === true || fresh.name === summary)
4434
+ return 'stale';
4435
+ // A history turn still marked running is an attempt whose final save failed (or is in flight in
4436
+ // another window): the title must not publish that snapshot back as running. A retry with no run
4437
+ // of its own defers on any such marker.
4438
+ if (ownRunId === undefined && (fresh.history ?? []).some(turn => turn.completion?.status === 'running'
4439
+ && (runId === undefined || turn.runId === runId)))
4440
+ return 'stale';
4441
+ const titled = { ...fresh, name: summary };
4442
+ await this.store().save(savedSessionFields(titled));
4443
+ this.emit('session.updated', { session: this.summary(titled) });
4444
+ return 'saved';
4445
+ });
4446
+ }
4447
+ /** 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
+ scheduleTitleRetry(sessionId, task, provider, modelId, attempt, deferrals = 0) {
4449
+ if (this.closed || !titleRequestSupported(provider))
4450
+ return;
4451
+ if (attempt >= TITLE_RETRY_DELAYS_MS.length)
4452
+ return;
4453
+ if (this.titleRetries.has(sessionId))
4454
+ return;
4455
+ const controller = new AbortController();
4456
+ const timer = setTimeout(() => { void this.retrySessionTitle(sessionId, task, provider, modelId, attempt); }, TITLE_RETRY_DELAYS_MS[attempt]);
4457
+ timer.unref();
4458
+ controller.signal.addEventListener('abort', () => { clearTimeout(timer); this.titleRetries.delete(sessionId); }, { once: true });
4459
+ this.titleRetries.set(sessionId, { timer, controller, task, provider, modelId, attempt, deferrals });
4460
+ }
4461
+ async retrySessionTitle(sessionId, task, provider, modelId, attempt) {
4462
+ // A storage failure anywhere below must never surface as an unhandled rejection from the retry
4463
+ // timer: the bounded attempt budget covers it instead.
4464
+ try {
4465
+ await this.runTitleRetry(sessionId, task, provider, modelId, attempt);
4466
+ }
4467
+ catch {
4468
+ this.scheduleTitleRetry(sessionId, task, provider, modelId, attempt + 1);
4469
+ }
4470
+ }
4471
+ async runTitleRetry(sessionId, task, provider, modelId, attempt) {
4472
+ const pending = this.titleRetries.get(sessionId);
4473
+ this.titleRetries.delete(sessionId);
4474
+ if (!pending || pending.controller.signal.aborted || this.closed)
4475
+ return;
4476
+ const fresh = await this.readSession(sessionId).catch(() => undefined);
4477
+ // 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))
4479
+ return;
4480
+ // A run is working on the session, so the save would step aside anyway. Step back without
4481
+ // spending one of the bounded attempts: the title is not lost, it is just not this minute's.
4482
+ if (this.run?.sessionId === sessionId || await sessionHasOpenRun(this.directory, sessionId)) {
4483
+ if (pending.deferrals >= MAX_TITLE_RETRY_DEFERRALS)
4484
+ return;
4485
+ this.scheduleTitleRetry(sessionId, task, provider, modelId, attempt, pending.deferrals + 1);
4486
+ return;
4487
+ }
4488
+ const controller = new AbortController();
4489
+ this.operations.add(controller);
4490
+ this.sessionTitles.set(sessionId, controller);
4491
+ try {
4492
+ const summary = await summarizeSessionPrompt(task, createAdapter(provider), modelId, controller.signal);
4493
+ if (!summary) {
4494
+ // The model answered nothing usable: spend the attempt the way an empty first title does.
4495
+ this.scheduleTitleRetry(sessionId, task, provider, modelId, attempt + 1);
4496
+ return;
4497
+ }
4498
+ const outcome = await this.saveSessionTitle(sessionId, undefined, summary);
4499
+ if (outcome === 'busy' && pending.deferrals < MAX_TITLE_RETRY_DEFERRALS) {
4500
+ // The name was made but the session was claimed meanwhile: stand back, spend nothing.
4501
+ this.scheduleTitleRetry(sessionId, task, provider, modelId, attempt, pending.deferrals + 1);
4502
+ }
4503
+ }
4504
+ finally {
4505
+ if (this.sessionTitles.get(sessionId) === controller)
4506
+ this.sessionTitles.delete(sessionId);
4507
+ this.operations.delete(controller);
4508
+ }
4509
+ }
4128
4510
  releaseTitleWaiter(runId) {
4129
4511
  const release = this.titleReleases.get(runId);
4130
4512
  if (release !== undefined) {
@@ -4132,14 +4514,40 @@ export class AppServer {
4132
4514
  release();
4133
4515
  }
4134
4516
  }
4135
- cancelSessionTitles() {
4136
- for (const controller of this.sessionTitles.values())
4517
+ /** Abort title work for the session given, or for all: the request on the wire, and a retry that is still waiting is moved back, not dropped. */
4518
+ cancelSessionTitles(onlySessionId) {
4519
+ const postpone = (sessionId) => {
4520
+ const pending = this.titleRetries.get(sessionId);
4521
+ if (pending === undefined)
4522
+ return;
4523
+ this.titleRetries.delete(sessionId);
4524
+ pending.controller.abort();
4525
+ // New work on the session does not ask for a title itself, so killing a waiting retry here would
4526
+ // leave the session unnamed for good. Push the attempt back instead of discarding it.
4527
+ this.scheduleTitleRetry(sessionId, pending.task, pending.provider, pending.modelId, pending.attempt + 1);
4528
+ };
4529
+ if (onlySessionId !== undefined) {
4530
+ const controller = this.sessionTitles.get(onlySessionId);
4531
+ if (controller !== undefined) {
4532
+ this.sessionTitles.delete(onlySessionId);
4533
+ controller.abort();
4534
+ }
4535
+ postpone(onlySessionId);
4536
+ return;
4537
+ }
4538
+ for (const [id, controller] of this.sessionTitles) {
4539
+ this.sessionTitles.delete(id);
4137
4540
  controller.abort();
4138
- this.sessionTitles.clear();
4541
+ }
4542
+ for (const pending of this.titleRetries.values())
4543
+ pending.controller.abort();
4544
+ this.titleRetries.clear();
4139
4545
  }
4140
4546
  async executeRun(input) {
4141
- const { runId, startedAt, telemetryRunId, accountSubject, task, note, turnNote, selection, providerId, modelId, root, permissions, liveSteers, boundPermissions, reasoningEffort, overrideAllNodes = 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;
4547
+ const { runId, startedAt, telemetryRunId, accountSubject, task, note, turnNote, selection, providerId, modelId, root, project, permissions, liveSteers, boundPermissions, reasoningEffort, autoEffort = false, overrideAllNodes = 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;
4142
4548
  const signal = controller.signal;
4549
+ const turnObservations = [];
4550
+ const turnEdits = [];
4143
4551
  const panelHold = createPanelBrowserHold(this.browserViews, input.record.id, panelBrowserRelay ? this.panelBrowserRelayFor(input.record.id) : undefined);
4144
4552
  const liveRun = this.run?.runId === runId ? this.run : undefined;
4145
4553
  if (liveRun)
@@ -4193,7 +4601,7 @@ export class AppServer {
4193
4601
  };
4194
4602
  for (const entry of carriedDirections ?? []) {
4195
4603
  const refs = entry.attachments ?? [];
4196
- const images = refs.length ? await loadResolvedImages(this.directory, root, refs) : [];
4604
+ const images = refs.length ? await loadResolvedImages(this.directory, project, refs) : [];
4197
4605
  const said = wakeMessageText(entry.wake, entry.direction);
4198
4606
  arm(entry.wake === undefined ? undefined : entry.node, { ...(entry.id === undefined ? {} : { id: entry.id }), content: refs.length ? `${said}\n\n${attachmentReferenceBlock(refs, { imagesIncluded: images.length > 0 })}` : said, images });
4199
4607
  }
@@ -4238,7 +4646,7 @@ export class AppServer {
4238
4646
  if (telemetryHandle === undefined) {
4239
4647
  telemetryHandle = createRunHandle(telemetryRunId, startedAt, {
4240
4648
  graphId: selection, nodes: 0, subagents: false, permissionMode: boundPermissions ?? permissions,
4241
- }, root);
4649
+ }, project);
4242
4650
  const placeholder = telemetryHandle;
4243
4651
  telemetryStart = reportRunStarted(telemetrySurfaceFor(runConfig), placeholder).catch(() => { });
4244
4652
  }
@@ -4268,7 +4676,7 @@ export class AppServer {
4268
4676
  bootMark('run.exec.config-loaded');
4269
4677
  runConfig = config;
4270
4678
  if (archive.length === 0)
4271
- trackTelemetry(reportSessionStarted({ ...telemetrySurfaceFor(config), workspace: root }));
4679
+ trackTelemetry(reportSessionStarted({ ...telemetrySurfaceFor(config), workspace: project }));
4272
4680
  const provider = config.providers.find(item => item.id === providerId);
4273
4681
  if (!provider)
4274
4682
  throw new Error(`Unknown provider: ${providerId}`);
@@ -4291,7 +4699,7 @@ export class AppServer {
4291
4699
  const startedHandle = createRunHandle(telemetryRunId, startedAt, {
4292
4700
  graphId: selection, ...graphShape(graph), permissionMode: boundPermissions ?? permissions,
4293
4701
  jevEnabled: config.jevEnabled !== false && input.record.jevEnabled !== false, decisionRouting: config.decisions?.mode ?? 'off',
4294
- }, root);
4702
+ }, project);
4295
4703
  telemetryHandle = startedHandle;
4296
4704
  telemetryStart = reportRunStarted(telemetrySurfaceFor(config), startedHandle).catch(() => { });
4297
4705
  await telemetryStart;
@@ -4378,7 +4786,7 @@ export class AppServer {
4378
4786
  contextWindow = snapshot.contextWindow;
4379
4787
  this.emit('run.context', { runId, provider: provider.id, model: snapshot.model, ...(snapshot.contextWindow === undefined ? {} : { contextWindow: snapshot.contextWindow }), ...(snapshot.reasoningEffort === undefined ? {} : { reasoningEffort: snapshot.reasoningEffort }) });
4380
4788
  const invocationInput = input.invocationText;
4381
- const runExtensions = effectiveExtensionConfig(config, root);
4789
+ const runExtensions = effectiveExtensionConfig(config, project);
4382
4790
  bootMark('run.exec.model-context.resolved');
4383
4791
  const invocations = invocationInput === undefined || isBuiltinSlashCommand(invocationInput) ? []
4384
4792
  : await resolveSkillInvocations(invocationInput, runExtensions, signal, this.directory);
@@ -4393,9 +4801,9 @@ export class AppServer {
4393
4801
  this.emit('log', { level: 'info', message: notice });
4394
4802
  bootMark('run.exec.extensions.loaded');
4395
4803
  if (config.commandMemory !== false)
4396
- commandMemory = await LocalToolMemory.open({ directory: this.directory, workspace: root });
4804
+ commandMemory = await LocalToolMemory.open({ directory: this.directory, workspace: project });
4397
4805
  if (config.projectMemory !== false)
4398
- projectMemory = await ProjectMemory.open({ home: this.directory, workspace: root });
4806
+ projectMemory = await ProjectMemory.open({ home: this.directory, workspace: project });
4399
4807
  bootMark('run.exec.command-memory.opened');
4400
4808
  const attachmentRoots = await attachmentReadRoots(this.directory, [
4401
4809
  ...(attachments?.refs ?? []),
@@ -4403,7 +4811,8 @@ export class AppServer {
4403
4811
  ...(history ?? []).flatMap(turn => [...(turn.attachments ?? []), ...(turn.steers ?? []).flatMap(steer => steer.attachments ?? [])]),
4404
4812
  ]);
4405
4813
  const wakeCarry = { graph: selection, provider: providerId, model: modelId,
4406
- ...(reasoningEffort === undefined ? {} : { reasoningEffort }),
4814
+ // A run on Auto thinking hands Auto to the runs its wakes start, as it hands a fixed level.
4815
+ ...(reasoningEffort === undefined ? autoEffort ? { reasoningEffort: 'auto' } : {} : { reasoningEffort }),
4407
4816
  ...(overrideAllNodes ? { overrideAllNodes: true } : {}),
4408
4817
  ...(panelBrowserRelay ? { panelBrowserRelay: true } : {}),
4409
4818
  ...(input.relayProviders === undefined ? {} : { relayed: true }),
@@ -4412,8 +4821,26 @@ export class AppServer {
4412
4821
  if (liveRun)
4413
4822
  liveRun.wakeCarry = wakeCarry;
4414
4823
  const pullRequestDetector = new PullRequestCreateDetector();
4824
+ // What this turn's commands ran against, and when files were edited: the turn's evidence is resolved from them.
4825
+ const observeCommand = async (start) => {
4826
+ // Kept as the transcript keeps tool text: terminal escapes stripped, known secret shapes redacted.
4827
+ const observation = { id: randomUUID(), command: cleanRecorded(start.command).slice(0, COMMAND_LIMIT), directory: start.directory, startedAt: new Date().toISOString() };
4828
+ const revision = await readRevision(start.directory, start.signal).catch(() => undefined);
4829
+ if (revision !== undefined)
4830
+ observation.revision = revision;
4831
+ turnObservations.push(observation);
4832
+ if (turnObservations.length > MAX_TURN_OBSERVATIONS)
4833
+ turnObservations.shift();
4834
+ return end => {
4835
+ observation.endedAt = new Date().toISOString();
4836
+ if (end.exitCode !== undefined)
4837
+ observation.exitCode = end.exitCode;
4838
+ if (end.output)
4839
+ observation.output = outputTail(cleanRecorded(end.output));
4840
+ };
4841
+ };
4415
4842
  const toolContext = {
4416
- workspace: root, signal, userSignal: signal, yolo: permissions === 'full-access', permissions, approvalMode: 'interactive',
4843
+ workspace: root, ...(project !== root ? { project } : {}), signal, userSignal: signal, yolo: permissions === 'full-access', permissions, approvalMode: 'interactive',
4417
4844
  ...(liveRun ? { runControl: liveRun.permissionControl } : {}),
4418
4845
  attachmentRoots,
4419
4846
  approve: (name, args, toolSignal) => this.approve(runId, name, args, toolSignal),
@@ -4431,10 +4858,11 @@ export class AppServer {
4431
4858
  this.trajectory?.recordEvent(event),
4432
4859
  ]);
4433
4860
  },
4434
- timers: this.timers, sessionScope: input.record.id, wakesArmed, automationDirectory: this.directory,
4861
+ timers: this.timers, sessionScope: input.record.id, sessionId: input.record.id, wakesArmed, automationDirectory: this.directory,
4435
4862
  wakeCarry,
4436
4863
  pullRequests: this.pullRequestControl(input.record.id, wakeCarry),
4437
- fileChanges: 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'),
4864
+ 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
+ observeCommand,
4438
4866
  };
4439
4867
  bootMark('run.exec.mcp.connect.start');
4440
4868
  const healthGate = judgeHealth();
@@ -4469,7 +4897,7 @@ export class AppServer {
4469
4897
  createBrowserIncognitoTool(this.browserViews, input.record.id, panelBrowserRelay ? this.panelBrowserRelayFor(input.record.id) : undefined, panelHold),
4470
4898
  createBrowserExtensionsTool(panelBrowserRelay ? relayExtensionSteps(this.panelBrowserRelayFor(input.record.id)) : step => this.runExtensionStep(input.record.id, step)), ...extension.tools, ...(mcp?.tools ?? [])], installedSkillClaims: extension.claimsSkillName, history: contextSeed,
4471
4899
  ...(runSkill.skills?.length ? { inheritedSkills: runSkill.skills.map(skill => skill.id), skillInvocationInstruction: runSkill.instruction } : {}),
4472
- instructions: `${await loadWorkspaceInstructions(root, signal, systemPromptOverrideFor(graph, config.systemPromptOverride))}${extension.instructions}`,
4900
+ instructions: `${await loadWorkspaceInstructions(root, signal, systemPromptOverrideFor(graph, config.systemPromptOverride))}${extension.instructions}${worktreeInstructions(input.record.checkout)}`,
4473
4901
  codeIntel, todoStore: new TodoStore(), ...(commandMemory ? { commandMemory } : {}), ...(projectMemory ? { projectMemory } : {}),
4474
4902
  limits: resolveConfiguredLimits(config),
4475
4903
  ...hostedDecisionPolicy(membership, config.jevEnabled !== false && input.record.jevEnabled !== false, config.decisions),
@@ -4479,7 +4907,9 @@ export class AppServer {
4479
4907
  ...(entryHistory ? { entryHistory: true } : {}),
4480
4908
  ...(startNode === undefined ? {} : { startNode }),
4481
4909
  configuredModels: config.providers.map(item => ({ id: item.id, model: item.model, ...(item.models ? { models: [...item.models] } : {}) })),
4482
- resolveModel: (id, model, modelSignal) => this.resolveModel(config, id, model, modelSignal, id === provider.id && (model === undefined || model === modelId) ? reasoningEffort : undefined, input.record.id).then(watchResolved),
4910
+ 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
+ ...(autoEffort ? { sessionEffortAuto: true } : {}),
4912
+ thinkingLevels: (id, model, forAuto) => (forAuto ? autoLevels : enabledLevels)(config.providers.find(item => item.id === id), model),
4483
4913
  resolveProvider: id => watchResolved(this.resolveProvider(config, id, input.record.id)),
4484
4914
  getLiveModel: async (nodeId, fallbackProvider, fallbackModel, modelSignal) => {
4485
4915
  while (true) {
@@ -4493,12 +4923,18 @@ export class AppServer {
4493
4923
  const effectiveModel = targetModel ?? current.config.providers.find(item => item.id === targetProvider)?.model;
4494
4924
  if (targetProvider === fallbackProvider && effectiveModel === fallbackModel)
4495
4925
  return undefined;
4496
- const selectedEffort = targetProvider === current.provider && effectiveModel === current.model
4497
- ? current.reasoningEffort : undefined;
4498
- const resolved = watchResolved(await this.resolveModel(current.config, targetProvider, targetModel, modelSignal, selectedEffort, input.record.id));
4926
+ const onSessionModel = targetProvider === current.provider && effectiveModel === current.model;
4927
+ const selectedEffort = onSessionModel ? current.reasoningEffort : undefined;
4928
+ // A level switched off for the replacement model is never sent, whether it is the run's or the provider's
4929
+ // saved one. The runtime installs this adapter mid-attempt, past the attempt-start check.
4930
+ const liveProvider = current.config.providers.find(item => item.id === targetProvider);
4931
+ const saved = selectedEffort ?? (effectiveModel === liveProvider?.model ? liveProvider?.reasoningEffort : undefined);
4932
+ const allowed = effectiveModel === undefined ? [] : enabledLevels(liveProvider, effectiveModel);
4933
+ const liveEffort = saved === undefined || allowed.length === 0 ? selectedEffort : nearestEnabled(allowed, saved);
4934
+ const resolved = watchResolved(await this.resolveModel(current.config, targetProvider, targetModel, modelSignal, liveEffort, input.record.id));
4499
4935
  if (liveRun?.modelSelection !== current)
4500
4936
  continue;
4501
- return { ...resolved, provider: targetProvider };
4937
+ return { ...resolved, provider: targetProvider, ...(onSessionModel ? { sessionModel: true } : {}) };
4502
4938
  }
4503
4939
  },
4504
4940
  context: toolContext,
@@ -4662,7 +5098,16 @@ export class AppServer {
4662
5098
  await releaseRunResumeClaim(this.directory, resumedFrom);
4663
5099
  await checkpointWrites;
4664
5100
  const closedWithRun = controller.signal.aborted && this.runAbort === 'shutdown';
4665
- const completion = finalCompletion(result, controller.signal.aborted, failure, closedWithRun);
5101
+ const finished = finalCompletion(result, controller.signal.aborted, failure, closedWithRun);
5102
+ // The outcomes the agent listed, each tied to the runtime's record of the command that shows it.
5103
+ // The folders as the turn left them: a check followed by a shell edit is noticed even when nothing ran after it.
5104
+ const finalRevisions = new Map();
5105
+ if (finished.outcomes?.length) {
5106
+ for (const directory of [...new Set(turnObservations.map(item => item.directory))].slice(-5)) {
5107
+ finalRevisions.set(directory, await readRevision(directory).catch(() => undefined));
5108
+ }
5109
+ }
5110
+ const completion = finished.outcomes?.length ? { ...finished, evidence: resolveEvidence(finished.outcomes, turnObservations, turnEdits, finalRevisions) } : finished;
4666
5111
  if (result)
4667
5112
  foldUsage(result.usage, probeUsage);
4668
5113
  foldUsage(usage, result?.usage ?? runUsage);
@@ -4707,7 +5152,7 @@ export class AppServer {
4707
5152
  ...(automationContext === undefined ? {} : { automationContext }),
4708
5153
  ...(liveRun?.modelSelection ? { liveModelChanged: true } : {}),
4709
5154
  ...((liveRun?.modelSelection ? liveRun.modelSelection.reasoningEffort : reasoningEffort) === undefined
4710
- ? {} : { reasoningEffort: liveRun?.modelSelection ? liveRun.modelSelection.reasoningEffort : reasoningEffort }),
5155
+ ? ((liveRun?.modelSelection ? liveRun.modelSelection.autoEffort === true : autoEffort) ? { reasoningEffort: 'auto' } : {}) : { reasoningEffort: liveRun?.modelSelection ? liveRun.modelSelection.reasoningEffort : reasoningEffort }),
4711
5156
  ...((liveRun?.modelSelection?.overrideAllNodes ?? overrideAllNodes) ? { overrideAllNodes: true } : {}),
4712
5157
  ...((liveNodeOverrides !== undefined && Object.keys(liveNodeOverrides).length > 0)
4713
5158
  ? { nodeModelOverrides: liveNodeOverrides } : {}),
@@ -4866,6 +5311,9 @@ export class AppServer {
4866
5311
  : config.providers.find(item => item.id === node.provider)?.model);
4867
5312
  existing.nodeModelOverrides = { ...(existing.nodeModelOverrides ?? {}), [scopedNode]: { provider, model } };
4868
5313
  existing.liveModelChanged = true;
5314
+ // A model override replaces the node's whole model choice, its own thinking level included, as one given at
5315
+ // run start does (applyNodeModelOverrides).
5316
+ delete node.reasoningEffort;
4869
5317
  switched = { scope: 'node', from: { provider: previousProvider, ...(previousModel === undefined ? {} : { model: String(previousModel) }) }, nodeName: node.name };
4870
5318
  }
4871
5319
  else {
@@ -4893,6 +5341,11 @@ export class AppServer {
4893
5341
  else
4894
5342
  target[key] = source[key];
4895
5343
  }
5344
+ // The thinking level goes with the model choice: an override removes the node's own, and lifting it restores it.
5345
+ if (source.reasoningEffort === undefined)
5346
+ delete target.reasoningEffort;
5347
+ else
5348
+ target.reasoningEffort = source.reasoningEffort;
4896
5349
  if (target.retry && source.retry)
4897
5350
  target.retry.fallback = structuredClone(source.retry.fallback);
4898
5351
  if (target.subagents && source.subagents) {
@@ -4914,8 +5367,9 @@ export class AppServer {
4914
5367
  }
4915
5368
  }
4916
5369
  }
4917
- const liveEffort = typeof existing.reasoningEffort === 'string'
5370
+ const liveEffort = typeof existing.reasoningEffort === 'string' && existing.reasoningEffort !== 'auto'
4918
5371
  ? reasoningEffort(existing.reasoningEffort) : undefined;
5372
+ const liveAuto = existing.reasoningEffort === 'auto';
4919
5373
  if (scopedNode !== undefined) {
4920
5374
  const previous = run.modelSelection;
4921
5375
  run.modelSelection = {
@@ -4925,6 +5379,7 @@ export class AppServer {
4925
5379
  nodeOnly: previous === undefined ? true : previous.nodeOnly === true,
4926
5380
  config,
4927
5381
  ...(liveEffort === undefined ? {} : { reasoningEffort: liveEffort }),
5382
+ ...(liveAuto ? { autoEffort: true } : {}),
4928
5383
  nodeOverrides: { ...(existing.nodeModelOverrides ?? previous?.nodeOverrides ?? {}), [scopedNode]: { provider, model } },
4929
5384
  revision: (previous?.revision ?? 0) + 1,
4930
5385
  };
@@ -4932,13 +5387,16 @@ export class AppServer {
4932
5387
  else {
4933
5388
  run.modelSelection = { provider, model, overrideAllNodes: params.overrideAllNodes, config,
4934
5389
  ...(liveEffort === undefined ? {} : { reasoningEffort: liveEffort }),
5390
+ ...(liveAuto ? { autoEffort: true } : {}),
4935
5391
  revision: (run.modelSelection?.revision ?? 0) + 1 };
4936
5392
  }
4937
5393
  if (replacement !== undefined && run.wakeCarry) {
4938
- if (liveEffort === undefined)
4939
- delete run.wakeCarry.reasoningEffort;
4940
- else
5394
+ if (liveEffort !== undefined)
4941
5395
  run.wakeCarry.reasoningEffort = liveEffort;
5396
+ else if (liveAuto)
5397
+ run.wakeCarry.reasoningEffort = 'auto';
5398
+ else
5399
+ delete run.wakeCarry.reasoningEffort;
4942
5400
  run.wakeCarry.provider = provider;
4943
5401
  run.wakeCarry.model = model;
4944
5402
  if (params.overrideAllNodes)
@@ -5056,7 +5514,7 @@ export class AppServer {
5056
5514
  }
5057
5515
  syncCodeIntelPermissions(live) {
5058
5516
  const apply = async () => {
5059
- const manager = this.codeIntel?.workspace === live.workspace ? this.codeIntel.manager : undefined;
5517
+ const manager = this.codeIntel?.workspace === live.workRoot ? this.codeIntel.manager : undefined;
5060
5518
  const target = live.codeIntelPermissions;
5061
5519
  if (!manager || live.codeIntelApplied === target)
5062
5520
  return;
@@ -5665,6 +6123,7 @@ export class AppServer {
5665
6123
  case 'invalid_name': return new AppServerError('invalid-params', MACHINE_NAME_RULE);
5666
6124
  case 'not_found': return new AppServerError('not-found', 'That machine is not linked to your account.');
5667
6125
  case 'cloud_not_enabled': return new AppServerError('forbidden', 'Cloud is not available for your account yet.');
6126
+ case 'cloud_plan': return new AppServerError('forbidden', 'Cloud is not included in the Free plan. Upgrade to use it.');
5668
6127
  case 'cloud_environment': return new AppServerError('invalid-params', 'Delete Cloud from Settings → Environments.');
5669
6128
  case 'invalid_version': return new AppServerError('invalid-params', 'This version of Andorra Code cannot start Cloud. Update Andorra Code and try again.');
5670
6129
  case 'stopping': return new AppServerError('busy', 'Cloud is still stopping. Try again in a moment.');
@@ -5860,10 +6319,13 @@ export class AppServer {
5860
6319
  this.environmentIdsLoading = undefined; });
5861
6320
  return loading;
5862
6321
  }
6322
+ offlineEnvironmentLine(env) {
6323
+ return env === this.cloudEnvironmentId ? 'Connecting to Cloud…' : MACHINE_OFFLINE;
6324
+ }
5863
6325
  /** A call for a machine whose link is waiting for it to come back fails now instead of at its deadline. */
5864
6326
  refuseWhileReconnecting(env) {
5865
6327
  if (this.engineLinks.get(env)?.reconnecting)
5866
- throw new AppServerError('network', MACHINE_OFFLINE);
6328
+ throw new AppServerError('network', this.offlineEnvironmentLine(env));
5867
6329
  }
5868
6330
  hostOperation(params, op, operationParams = {}) {
5869
6331
  const env = environmentId(params.workspaceId);
@@ -6342,6 +6804,18 @@ export class AppServer {
6342
6804
  this.refuseWhileReconnecting(env);
6343
6805
  let inner = params.params !== undefined && typeof params.params === 'object' && !Array.isArray(params.params)
6344
6806
  ? params.params : undefined;
6807
+ if (inner?.attachments !== undefined && env === this.cloudEnvironmentId && ['run.start', 'run.resume', 'run.steer'].includes(method)) {
6808
+ const generation = this.accountGeneration;
6809
+ try {
6810
+ inner = { ...inner, attachments: await cloudAttachments(inner.attachments) };
6811
+ }
6812
+ catch (error) {
6813
+ throw new AppServerError('invalid-params', message(error));
6814
+ }
6815
+ if (generation !== this.accountGeneration)
6816
+ throw new AppServerError('cancelled', 'The Andorra account changed.');
6817
+ this.refuseWhileReconnecting(env);
6818
+ }
6345
6819
  const relayMachine = this.engineLinks.get(env)?.capabilities?.includes(MODEL_RELAY_CAPABILITY) === true;
6346
6820
  // A machine whose engine takes relayed providers runs this computer's models: its start carries them by id only.
6347
6821
  let relayed = false;
@@ -6634,7 +7108,7 @@ export class AppServer {
6634
7108
  if (!link)
6635
7109
  return { error: { code: 'cancelled', message: 'The connection to that machine was closed.' } };
6636
7110
  if (link.reconnecting || this.closed)
6637
- return { error: { code: 'network', message: MACHINE_OFFLINE } };
7111
+ return { error: { code: 'network', message: this.offlineEnvironmentLine(env) } };
6638
7112
  try {
6639
7113
  const answer = await this.relayLink().request(env, { connectionId: link.connectionId, viewerWorkspaceId: env, engine, method, params, deadlineMs: MODEL_RELAY_CALL_MS }, Date.now() + MODEL_RELAY_CALL_MS + RELAY_TRANSPORT_SLACK_MS);
6640
7114
  return { ...answer, via: link.connectionId };
@@ -6677,6 +7151,30 @@ export class AppServer {
6677
7151
  throw new AppServerError('invalid-params', 'Host path required');
6678
7152
  return this.hostOperation(params, 'owner.projects.add', { path: params.path, ...(typeof params.name === 'string' ? { name: params.name } : {}) });
6679
7153
  }
7154
+ /** Asks a Cloud machine to clone a GitHub repository and register it; answered at once, and asked again while it clones. */
7155
+ async remoteOwnerGitHubClone(params) {
7156
+ const { owner, repo } = params;
7157
+ if (typeof owner !== 'string' || !GITHUB_ACCOUNT.test(owner) || typeof repo !== 'string' || !GITHUB_REPO.test(repo))
7158
+ throw new AppServerError('invalid-params', 'A GitHub owner and repository name are required.');
7159
+ let answer;
7160
+ try {
7161
+ answer = await this.hostOperation(params, 'owner.github.clone', { owner, repo });
7162
+ }
7163
+ catch (error) {
7164
+ // A machine running an engine from before this operation: Cloud installs the desktop's version when it starts.
7165
+ if (error instanceof Error && /Unknown host operation/.test(error.message))
7166
+ throw new AppServerError('remote', 'This Cloud engine cannot clone from GitHub. Update Andorra Code to a release that supports Cloud repository cloning, then restart Cloud.');
7167
+ throw error;
7168
+ }
7169
+ const found = (answer ?? {});
7170
+ if (found.state === 'cloning')
7171
+ return { state: 'cloning' };
7172
+ if (found.state === 'ready' && typeof found.rootId === 'string' && typeof found.name === 'string')
7173
+ return { state: 'ready', rootId: found.rootId, name: found.name };
7174
+ if (found.state === 'failed' && typeof found.message === 'string')
7175
+ return { state: 'failed', message: found.message.slice(0, 600) };
7176
+ throw new AppServerError('remote', 'The machine sent a malformed answer about the clone.');
7177
+ }
6680
7178
  async listProjects() {
6681
7179
  const config = await loadConfig(this.directory);
6682
7180
  return config.projects ?? [];
@@ -7061,7 +7559,19 @@ export class AppServer {
7061
7559
  void this.pullRequestWatcher.readNow(sessionId);
7062
7560
  return every;
7063
7561
  }
7064
- deliver({ kind: 'approved', pullRequest: current, ...(head === undefined ? {} : { headSha: head }) });
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);
7065
7575
  return every;
7066
7576
  }
7067
7577
  if (!approveBump || head === undefined || !seen.open || seen.reviewing || seen.reviewed || seen.asked || current.reviewBumped === head || watch.skipped === head) {
@@ -7156,8 +7666,29 @@ export class AppServer {
7156
7666
  }
7157
7667
  }
7158
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
+ }
7159
7682
  const prompt = !current.autoFix || pending === undefined || this.timers.isHeld(pending.wakeId) ? undefined : pending.prompt ?? this.timers.get(pending.wakeId)?.prompt;
7160
- if (pending !== undefined && prompt !== undefined && deliver({ kind: 'comments', 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 })) {
7161
7692
  if (this.autoFixWakes.has(pending.wakeId))
7162
7693
  this.cancelAutoFixWake(sessionId, pending.wakeId);
7163
7694
  next = { ...handedOver(next, pending), updatedAt: at };
@@ -7646,6 +8177,20 @@ export class AppServer {
7646
8177
  throw new AppServerError('forbidden', 'The GitHub App is turned off on the Andorra service for now.');
7647
8178
  return { url: answer.url };
7648
8179
  }
8180
+ /** The repositories the GitHub App can reach for this account's linked GitHub user: what a Cloud machine may clone. */
8181
+ async githubRepositories() {
8182
+ if (!await this.githubSignedIn().catch(() => false))
8183
+ throw this.githubError(new GitHubAppError('signed-out', 'Sign in to Andorra first.'));
8184
+ try {
8185
+ return await this.githubClient.repositories();
8186
+ }
8187
+ catch (error) {
8188
+ // An account API from before this route reads as the App being off here, not as an error.
8189
+ if (error instanceof GitHubAppError && error.code === 'not-found')
8190
+ return { enabled: false, connected: false, repositories: [], more: false };
8191
+ throw this.githubError(error);
8192
+ }
8193
+ }
7649
8194
  async githubDisconnect() {
7650
8195
  if (!await this.githubSignedIn().catch(() => false))
7651
8196
  throw this.githubError(new GitHubAppError('signed-out', 'Sign in to Andorra first.'));
@@ -7987,9 +8532,10 @@ export class AppServer {
7987
8532
  const record = await this.readSession(sessionId);
7988
8533
  if (await readPullRequest(this.directory, sessionId))
7989
8534
  return { draft: null, blocked: { kind: 'has-pull-request', message: 'This task already has a pull request.' } };
8535
+ const gitRoot = sessionGitRoot(record);
7990
8536
  try {
7991
8537
  const prompt = record.history[0]?.task;
7992
- return { draft: await readCreateDraft(this.gh, this.git(record.workspace), record.workspace, { taskName: record.name, ...(base === undefined ? {} : { base }), closesIssue: (owner, repo) => issueNamedIn(prompt, owner, repo) }) };
8538
+ return { draft: await readCreateDraft(this.gh, this.git(gitRoot), gitRoot, { taskName: record.name, ...(base === undefined ? {} : { base }), closesIssue: (owner, repo) => issueNamedIn(prompt, owner, repo) }) };
7993
8539
  }
7994
8540
  catch (error) {
7995
8541
  if (error instanceof PullRequestCreateBlocked)
@@ -8021,9 +8567,10 @@ export class AppServer {
8021
8567
  const record = await this.readSession(sessionId);
8022
8568
  if (await readPullRequest(this.directory, sessionId))
8023
8569
  return { ok: false, error: { kind: 'refused', message: 'This task already has a pull request.' } };
8570
+ const gitRoot = sessionGitRoot(record);
8024
8571
  let opened;
8025
8572
  try {
8026
- opened = await runAsAccount(this.gh, input.as, gh => createFromFolder(gh, this.git(record.workspace), input));
8573
+ opened = await runAsAccount(this.gh, input.as, gh => createFromFolder(gh, this.git(gitRoot), input));
8027
8574
  }
8028
8575
  catch (error) {
8029
8576
  const failure = classifyWriteError(error);
@@ -8172,7 +8719,7 @@ export class AppServer {
8172
8719
  throw error;
8173
8720
  }
8174
8721
  const folder = record === undefined || committed.commit === undefined ? undefined
8175
- : await this.catchUpFolder(record.workspace, { repository, branch: meta.headRefName, from: input.headSha, to: committed.commit }, () => accountToken(gh, input.as));
8722
+ : await this.catchUpFolder(sessionWorkRoot(record), { repository, branch: meta.headRefName, from: input.headSha, to: committed.commit }, () => accountToken(gh, input.as));
8176
8723
  return { ...committed, ...(folder === undefined ? {} : { folder }) };
8177
8724
  }, { details: true });
8178
8725
  return this.afterReviewWrite(sessionId, pullRequest, answer);
@@ -8913,6 +9460,7 @@ export class AppServer {
8913
9460
  new Promise(resolve => { choresTimer = setTimeout(resolve, 5_000); choresTimer.unref?.(); }),
8914
9461
  ]);
8915
9462
  clearTimeout(choresTimer);
9463
+ this.cancelSessionTitles();
8916
9464
  for (const controller of this.operations)
8917
9465
  controller.abort();
8918
9466
  for (const settle of [...this.pending.values()])