@nathanstephenson/flow 0.1.10-beta.1 → 0.1.10-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -22
- package/build/backend-worker-chunks/{chunk-CYE5L6Z5.mjs → chunk-3KDHJA5P.mjs} +41 -10
- package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
- package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
- package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
- package/build/backend-worker-chunks/claude-JG2FXYBQ.mjs +35859 -0
- package/build/backend-worker-chunks/{pi-UKRC4DDM.mjs → pi-KJSP23AO.mjs} +2091 -92
- package/build/backend-worker.mjs +69 -122
- package/build/workflow-runtime.cjs +12 -12
- package/dist/backend/claude/background-calls.js +7 -3
- package/dist/backend/claude/import.js +415 -0
- package/dist/backend/claude/index.js +188 -25
- package/dist/backend/claude/subagents.js +41 -9
- package/dist/backend/claude/todo-list.js +114 -0
- package/dist/backend/claude/workflow-parent.js +1 -1
- package/dist/backend/diff-excerpt-instructions.js +8 -0
- package/dist/backend/fake/index.js +54 -6
- package/dist/backend/mcp.js +4 -1
- package/dist/backend/pi/agent-permissions.js +1 -1
- package/dist/backend/pi/cache-warming.js +8 -0
- package/dist/backend/pi/canonical-json.js +120 -0
- package/dist/backend/pi/compaction-model.js +3 -2
- package/dist/backend/pi/host-auth.js +258 -0
- package/dist/backend/pi/import.js +269 -0
- package/dist/backend/pi/index.js +118 -20
- package/dist/backend/pi/model-auth.js +159 -0
- package/dist/backend/pi/model-catalog.js +120 -0
- package/dist/backend/pi/model-config.js +5 -0
- package/dist/backend/pi/model-selection.js +32 -0
- package/dist/backend/pi/plan-limits.js +41 -0
- package/dist/backend/pi/state.js +19 -1
- package/dist/backend/pi/subagents.js +7 -3
- package/dist/backend/pi/todo-list.js +23 -0
- package/dist/backend/pi/work.js +9 -1
- package/dist/backend/pi/workflow-parent.js +1 -1
- package/dist/backend/pi/workflow-subagent.js +4 -3
- package/dist/backend/plan-limits.js +17 -0
- package/dist/backend/session-tools.js +1 -1
- package/dist/backend/worker/claude-state.js +48 -0
- package/dist/backend/worker/entry.js +42 -8
- package/dist/backend/worker/index.js +131 -15
- package/dist/backend/worker/launcher.js +11 -4
- package/dist/backend/worker/protocol.js +2 -1
- package/dist/backend/worker/rpc.js +13 -0
- package/dist/backend/worker/sandbox-mcp.js +18 -7
- package/dist/backend/workflow-tools.js +9 -7
- package/dist/build-id +1 -1
- package/dist/cli/application.js +48 -42
- package/dist/cli/bootstrap.js +2 -2
- package/dist/cli/host-control.js +1 -1
- package/dist/cli/install-guard.js +2 -2
- package/dist/cli/main.js +4 -4
- package/dist/cli/systemd-update.js +3 -3
- package/dist/cli/update.js +6 -6
- package/dist/cli/web-update.js +6 -6
- package/dist/client/connection.js +46 -0
- package/dist/client/context-usage.js +3 -4
- package/dist/client/diff.js +40 -0
- package/dist/client/enquiry.js +0 -6
- package/dist/client/markdown.js +3 -2
- package/dist/client/model-choices.js +1 -1
- package/dist/client/permission.js +1 -2
- package/dist/client/project-name.js +3 -1
- package/dist/client/reduce.js +77 -3
- package/dist/client/relative-time.js +1 -1
- package/dist/client/scope-kind.js +6 -3
- package/dist/client/search.js +1 -1
- package/dist/client/status.js +1 -1
- package/dist/client/subagent-tree.js +49 -0
- package/dist/client/tool-chains.js +1 -1
- package/dist/client/tool-summary.js +28 -18
- package/dist/daemon/changes.js +128 -0
- package/dist/daemon/commit.js +84 -0
- package/dist/daemon/config-store.js +8 -3
- package/dist/daemon/config.js +105 -4
- package/dist/daemon/diff-excerpts.js +52 -0
- package/dist/daemon/git-state.js +197 -0
- package/dist/daemon/git.js +53 -10
- package/dist/daemon/github-image.js +18 -0
- package/dist/daemon/github.js +54 -0
- package/dist/daemon/host-control-routes.js +1 -1
- package/dist/daemon/host.js +940 -119
- package/dist/daemon/http.js +4 -1
- package/dist/daemon/log.js +3 -0
- package/dist/daemon/mcp-auth.js +1 -1
- package/dist/daemon/models.js +2 -2
- package/dist/daemon/pi-model-cache.js +44 -0
- package/dist/daemon/pull-request.js +223 -138
- package/dist/daemon/push.js +43 -0
- package/dist/daemon/repository.js +123 -0
- package/dist/daemon/runtime.js +103 -22
- package/dist/daemon/secret-store.js +1 -1
- package/dist/daemon/server.js +111 -14
- package/dist/daemon/skills.js +24 -0
- package/dist/daemon/spend-ledger.js +118 -0
- package/dist/daemon/stack-metadata.js +12 -5
- package/dist/daemon/stack.js +162 -657
- package/dist/daemon/store.js +2 -0
- package/dist/daemon/summariser.js +30 -12
- package/dist/daemon/tour.js +56 -0
- package/dist/daemon/whisper.js +144 -0
- package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
- package/dist/daemon/workflow-authoring-scope.js +1 -1
- package/dist/daemon/workflow-builder-files.js +2 -2
- package/dist/daemon/workflow-builder-guidance.js +1 -1
- package/dist/daemon/workflow-builder-routes.js +2 -2
- package/dist/daemon/workflow-builder.js +44 -17
- package/dist/daemon/workflow-environment.js +193 -0
- package/dist/daemon/workflow-execution-launch.js +77 -0
- package/dist/daemon/workflow-execution-resources.js +76 -0
- package/dist/daemon/workflow-execution-routes.js +12 -9
- package/dist/daemon/workflow-execution-values.js +128 -0
- package/dist/daemon/workflow-executions.js +400 -311
- package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
- package/dist/daemon/workflow-mcp-authoring.js +4 -4
- package/dist/daemon/workflow-mcp.js +1 -1
- package/dist/daemon/workflow-routes.js +60 -2
- package/dist/daemon/workflow-schedule-driver.js +251 -0
- package/dist/daemon/workflow-schedule-routes.js +137 -0
- package/dist/daemon/workflow-schedules.js +342 -0
- package/dist/isolation/filesystem.js +6 -2
- package/dist/isolation/sandbox.js +61 -18
- package/dist/isolation/shared-sandbox.js +3 -3
- package/dist/isolation/toolchain-assets.js +1 -1
- package/dist/protocol/events.js +3 -0
- package/dist/protocol/plan-limits.js +1 -0
- package/dist/protocol/settings.js +1 -0
- package/dist/protocol/spend.js +2 -0
- package/dist/protocol/stack.js +12 -39
- package/dist/protocol/workflow-schedules.js +1 -0
- package/dist/workflows/calls.js +53 -0
- package/dist/workflows/errors.js +2 -0
- package/dist/workflows/executors.js +6 -5
- package/dist/workflows/graph.js +83 -9
- package/dist/workflows/invocations.js +23 -0
- package/dist/workflows/mcp.js +1 -1
- package/dist/workflows/owner.js +45 -0
- package/dist/workflows/records.js +127 -11
- package/dist/workflows/recovery.js +38 -2
- package/dist/workflows/runtime-settings.js +16 -16
- package/dist/workflows/runtime.js +2 -2
- package/dist/workflows/schedule-errors.js +2 -0
- package/dist/workflows/schedule-store.js +385 -0
- package/dist/workflows/scheduler.js +367 -96
- package/dist/workflows/schedules.js +130 -0
- package/dist/workflows/schema.js +3 -1
- package/dist/workflows/store.js +126 -13
- package/package.json +10 -6
- package/web/dist/assets/index-C76t-z4w.css +2 -0
- package/web/dist/assets/{index-DRfeO6GJ.js → index-WPfbYVQ4.js} +39 -23
- package/web/dist/assets/{switch-DIogWclb.js → select-C5Ly2OpB.js} +1 -1
- package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-BF-yqpeQ.js} +1 -1
- package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-WLarr2QP.js} +1 -1
- package/web/dist/assets/settings-workflows-DdcdRWFD.js +23 -0
- package/web/dist/assets/workflow-api-GjAmHc22.js +6 -0
- package/web/dist/assets/workflows-BhY3Uibo.js +149 -0
- package/web/dist/assets/workflows-pane-DElCcEpN.js +1 -0
- package/web/dist/index.html +6 -5
- package/build/backend-worker-chunks/claude-UXZDJKZQ.mjs +0 -30816
- package/dist/daemon/publish.js +0 -289
- package/dist/tui/app.js +0 -612
- package/dist/tui/keys.js +0 -90
- package/dist/tui/render.js +0 -411
- package/web/dist/assets/index-DgQFpKbn.css +0 -2
- package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
- package/web/dist/assets/workflow-api-BfExddae.js +0 -6
- package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
- package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
- package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
- /package/dist/protocol/{publish.js → imports.js} +0 -0
package/dist/daemon/host.js
CHANGED
|
@@ -1,25 +1,36 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { waitForAbort } from "../backend/worker/rpc.js";
|
|
2
|
+
import { sessionListInput, sessionInspectInput, sessionCreateInput, sessionSendInput } from '../backend/session-tools.js';
|
|
3
|
+
import { sessionToolSummary, sessionToolPage } from './session-tool-views.js';
|
|
4
|
+
import { credentialKey } from './credential-redaction.js';
|
|
4
5
|
import { randomUUID } from "node:crypto";
|
|
5
|
-
import { existsSync, realpathSync } from "node:fs";
|
|
6
|
+
import { copyFileSync, existsSync, mkdirSync, realpathSync, rmSync } from "node:fs";
|
|
6
7
|
import { isAbsolute, join, resolve } from "node:path";
|
|
7
8
|
import { validateFilesystemScope } from "../isolation/filesystem.js";
|
|
8
|
-
import { pullRequest, commentPullRequest, resolvePullRequestThread, pullBranch, changePullRequest } from "./pull-request.js";
|
|
9
|
-
import { stackStatus,
|
|
10
|
-
import {
|
|
9
|
+
import { pullRequest, commentPullRequest, resolvePullRequestThread, pullBranch, changePullRequest, createPullRequest, editPullRequest, setPullRequestDraft, rerunPullRequestChecks, checkLog, dropUnchangedBranch, fetchBranch, listPullRequests, projectPullRequest, projectTarget, pullRequestRange, remoteUrl, submitReview } from "./pull-request.js";
|
|
10
|
+
import { otherWorktreeRebase, stackStatus, stackTitles, cleanStack, stackFingerprint, changeStack, stackConflictMessage, mergeableStack, stackMergeMethods } from "./stack.js";
|
|
11
|
+
import { changes, changesText, commitContext, diff, fileDiff, rangeChanges } from "./changes.js";
|
|
12
|
+
import { gh } from "./github.js";
|
|
13
|
+
import { resolveRepository } from "./repository.js";
|
|
14
|
+
import { commit } from "./commit.js";
|
|
15
|
+
import { push, pushState } from "./push.js";
|
|
16
|
+
import { GitStates, readStatus } from "./git-state.js";
|
|
17
|
+
import { TOUR_INSTRUCTIONS, TOUR_READ_TOOLS, pullRequestTourInput, tourInput, tourText } from "./tour.js";
|
|
18
|
+
import { diffExcerpts, hasDiffReference, messageExcerpts } from "./diff-excerpts.js";
|
|
11
19
|
import { resolveDefaultBackend } from "../protocol/settings.js";
|
|
12
20
|
import { isAttachmentMediaType, mediaTypeOf, MAX_ATTACHMENTS_PER_MESSAGE, MAX_ATTACHMENT_BASE64_BYTES, } from "../protocol/attachments.js";
|
|
13
21
|
import { deriveStatus, railGroupRank } from "../client/status.js";
|
|
14
22
|
// `switchBranch` is aliased because this class has a method of that name: the method is the
|
|
15
23
|
// Session Host's refusal-and-record wrapper, and the import is the git invocation it wraps.
|
|
16
|
-
import { createWorktree, head, isClean, isRepository, removeMergedBranch, removeWorktree, repairWorktree, switchBranch as gitSwitchBranch, } from "./git.js";
|
|
24
|
+
import { addDetachedCheckout, createWorktree, refExists, removeDetachedCheckout, head, isClean, isRepository, removeMergedBranch, removeWorktree, repairWorktree, updateSourceBranch, switchBranch as gitSwitchBranch, } from "./git.js";
|
|
17
25
|
import { SessionLog } from "./log.js";
|
|
18
26
|
import { probeModels } from "./models.js";
|
|
19
|
-
import {
|
|
27
|
+
import { PiModelProbeCache } from "./pi-model-cache.js";
|
|
28
|
+
import { ScheduleValidationError } from "../workflows/schedule-errors.js";
|
|
29
|
+
import { probePlanLimits, probeSkills } from "./skills.js";
|
|
20
30
|
import { recordTiming } from "./timings.js";
|
|
21
31
|
import { SharedSandbox } from "../isolation/shared-sandbox.js";
|
|
22
|
-
import { nameInput,
|
|
32
|
+
import { nameInput, suggestGitText, SummaryModelSpare } from "./summariser.js";
|
|
33
|
+
import { SpendLedger } from "./spend-ledger.js";
|
|
23
34
|
/**
|
|
24
35
|
* A command the Session Host will not carry out in the state the thing is in — a turn in flight, a
|
|
25
36
|
* Scope that is not a repository, a checkout git itself refused.
|
|
@@ -42,6 +53,7 @@ export class SessionHost {
|
|
|
42
53
|
backends = new Map();
|
|
43
54
|
/** Model probes by backend name, held in flight rather than resolved — see `models`. */
|
|
44
55
|
modelProbes = new Map();
|
|
56
|
+
piModelProbeCache = new PiModelProbeCache();
|
|
45
57
|
/** One warm Skills session per Backend Adapter, for the last Scope asked — see `skillsFor` (ADR 0035). */
|
|
46
58
|
skillSessions = new Map();
|
|
47
59
|
/**
|
|
@@ -52,6 +64,7 @@ export class SessionHost {
|
|
|
52
64
|
* one dimension.
|
|
53
65
|
*/
|
|
54
66
|
skillProbes = new Map();
|
|
67
|
+
planLimitProbe;
|
|
55
68
|
/**
|
|
56
69
|
* One Summary Model session, booted before a naming needs it (ADR 0020).
|
|
57
70
|
*
|
|
@@ -59,10 +72,13 @@ export class SessionHost {
|
|
|
59
72
|
* `settle` — it is a throwaway that outlives any one of them, in the same way `modelProbes` is.
|
|
60
73
|
*/
|
|
61
74
|
summarySpare = new SummaryModelSpare();
|
|
75
|
+
spendLedger;
|
|
62
76
|
stackReviews = new Map();
|
|
63
77
|
gitOperations = new Set();
|
|
78
|
+
gitStates = new GitStates();
|
|
64
79
|
closingScopes = new Set();
|
|
65
|
-
|
|
80
|
+
tours = new Map();
|
|
81
|
+
pullRequestTours = new Map();
|
|
66
82
|
refuseGitOperation(scope) {
|
|
67
83
|
if (this.gitOperations.has(scopeKey(scope)))
|
|
68
84
|
throw new CommandRefused("A Git operation is in progress in this Scope. Wait for it to finish.");
|
|
@@ -99,45 +115,54 @@ export class SessionHost {
|
|
|
99
115
|
}
|
|
100
116
|
finally {
|
|
101
117
|
this.gitOperations.delete(key);
|
|
118
|
+
void this.gitStates.refresh(scope);
|
|
102
119
|
}
|
|
103
120
|
}
|
|
104
121
|
async prepareStack(sessionId, action) {
|
|
105
|
-
if (action !== "submit" && action !== "sync")
|
|
122
|
+
if (action !== "submit" && action !== "sync" && action !== "merge")
|
|
106
123
|
throw new CommandRefused("Invalid Stack review action.");
|
|
107
124
|
const record = this.record(sessionId);
|
|
108
125
|
return this.withGitOperation(record.scope, async () => {
|
|
109
126
|
this.stackReviews.delete(sessionId);
|
|
110
127
|
await cleanStack(record.scope);
|
|
111
|
-
const status = await
|
|
128
|
+
const status = await stackStatus(record.scope);
|
|
112
129
|
if (!status.view)
|
|
113
|
-
throw new Error(status.
|
|
130
|
+
throw new Error(status.notice ?? "This branch is not in a stack.");
|
|
131
|
+
const fingerprint = await stackFingerprint(record.scope, status.view, action === "sync");
|
|
114
132
|
const review = { token: randomUUID(), action, view: status.view };
|
|
115
|
-
|
|
133
|
+
if (action === "merge") {
|
|
134
|
+
review.view = await mergeableStack(record.scope);
|
|
135
|
+
review.mergeMethods = await stackMergeMethods(record.scope, review.view);
|
|
136
|
+
if (!review.mergeMethods.length)
|
|
137
|
+
throw new Error("You cannot merge pull requests in this repository.");
|
|
138
|
+
}
|
|
139
|
+
this.stackReviews.set(sessionId, { review, fingerprint, expires: Date.now() + 15 * 60_000 });
|
|
116
140
|
return review;
|
|
117
141
|
});
|
|
118
142
|
}
|
|
119
143
|
async changeStack(sessionId, input) {
|
|
120
144
|
const record = this.record(sessionId);
|
|
121
145
|
return this.withGitOperation(record.scope, async () => {
|
|
122
|
-
if (input.action === "submit" || input.action === "sync") {
|
|
146
|
+
if (input.action === "submit" || input.action === "sync" || input.action === "merge") {
|
|
123
147
|
const saved = this.stackReviews.get(sessionId);
|
|
124
148
|
this.stackReviews.delete(sessionId);
|
|
125
149
|
if (!saved || saved.expires < Date.now() || saved.review.token !== input.token || saved.review.action !== input.action)
|
|
126
150
|
throw new Error("This Stack review expired. Review again.");
|
|
151
|
+
if (input.action === "merge" && !saved.review.mergeMethods?.includes(input.method))
|
|
152
|
+
throw new Error("This repository does not permit that merge method.");
|
|
127
153
|
await cleanStack(record.scope);
|
|
128
|
-
const status = await
|
|
154
|
+
const status = await stackStatus(record.scope);
|
|
129
155
|
if (!status.view || await stackFingerprint(record.scope, status.view, input.action === "sync") !== saved.fingerprint)
|
|
130
156
|
throw new Error("The reviewed stack changed. Review again.");
|
|
131
157
|
}
|
|
132
158
|
try {
|
|
133
|
-
return await changeStack(record.scope, input);
|
|
159
|
+
return await this.afterPullRequestWrite(record.scope, changeStack(record.scope, input));
|
|
134
160
|
}
|
|
135
161
|
finally {
|
|
136
162
|
for (const other of this.sessions.values()) {
|
|
137
163
|
if (scopeKey(other.scope) !== scopeKey(record.scope))
|
|
138
164
|
continue;
|
|
139
165
|
this.stackReviews.delete(other.id);
|
|
140
|
-
this.publishReviews.delete(other.id);
|
|
141
166
|
await this.refreshBranch(other);
|
|
142
167
|
other.pendingBranchNote = "[Flow] A Stack operation was attempted in this Scope. Re-read the branch and changed files before relying on earlier reads.";
|
|
143
168
|
}
|
|
@@ -147,67 +172,282 @@ export class SessionHost {
|
|
|
147
172
|
async assistStack(sessionId) {
|
|
148
173
|
const record = this.record(sessionId);
|
|
149
174
|
await this.withGitOperation(record.scope, async () => {
|
|
150
|
-
const status = await
|
|
175
|
+
const status = await stackStatus(record.scope);
|
|
151
176
|
if (!status.rebasing)
|
|
152
|
-
throw new Error("No Stack rebase is in progress. Use Rebase first after a Sync conflict.");
|
|
177
|
+
throw new Error(status.notice === otherWorktreeRebase ? otherWorktreeRebase : "No Stack rebase is in progress. Use Rebase first after a Sync conflict.");
|
|
153
178
|
});
|
|
154
179
|
await this.send(sessionId, stackConflictMessage, "now");
|
|
155
180
|
}
|
|
156
|
-
|
|
157
|
-
return
|
|
181
|
+
pollGitState(forced) {
|
|
182
|
+
return this.gitStates.poll([...this.sessions.values()].map(record => ({ scope: record.scope, lifecycle: record.lifecycle, watched: record.log.watched })), forced);
|
|
158
183
|
}
|
|
159
|
-
async
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
const suggestion = await canNameBranch(record.scope, reviewed.branch, destination)
|
|
183
|
-
? text.suggestedBranch ?? suggestedBranch((record.titleSource !== "scope" ? record.title : "") || text.commitMessage || committed.commits[0]?.replace(/^[a-f0-9]+ /, "") || record.title)
|
|
184
|
-
: undefined;
|
|
185
|
-
delete text.suggestedBranch;
|
|
186
|
-
const token = randomUUID();
|
|
187
|
-
this.publishReviews.set(sessionId, { token, expires: Date.now() + 15 * 60_000, snapshot: reviewed, target: destination });
|
|
188
|
-
return { ...text, ...(suggestion ? { suggestedBranch: suggestion } : {}), token, files: reviewed.files, committedFiles: committed.files, commits: committed.commits, branch: reviewed.branch, defaultBranch: destination.defaultBranch, ...(destination.baseBranch ? { baseBranch: destination.baseBranch } : {}), ...(destination.pr ? { pr: destination.pr } : {}), ...(warning ? { warning } : {}) };
|
|
184
|
+
async afterPullRequestWrite(scope, write) {
|
|
185
|
+
try {
|
|
186
|
+
return await write;
|
|
187
|
+
}
|
|
188
|
+
finally {
|
|
189
|
+
await this.pollGitState(scope);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
async readGit(read) {
|
|
193
|
+
try {
|
|
194
|
+
return await read();
|
|
195
|
+
}
|
|
196
|
+
catch (error) {
|
|
197
|
+
throw new CommandRefused(error instanceof Error ? error.message : String(error));
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
readStack(sessionId) {
|
|
201
|
+
const scope = this.gitScope(sessionId);
|
|
202
|
+
return this.readGit(async () => {
|
|
203
|
+
const status = await stackStatus(scope);
|
|
204
|
+
if (status.view && !await stackTitles(scope, status.view))
|
|
205
|
+
status.notice = "Pull request titles could not be read. Copy uses the links.";
|
|
206
|
+
return status;
|
|
189
207
|
});
|
|
190
208
|
}
|
|
191
|
-
|
|
209
|
+
projectScope(project) {
|
|
210
|
+
if (typeof project !== "string" || !isRepository(project))
|
|
211
|
+
throw new CommandRefused(`${project} is not a git repository.`);
|
|
212
|
+
return project;
|
|
213
|
+
}
|
|
214
|
+
pullRequestPlace(target) {
|
|
215
|
+
if (target.project === undefined)
|
|
216
|
+
return { scope: this.record(target.sessionId).scope };
|
|
217
|
+
return { scope: this.projectScope(target.project), find: projectTarget };
|
|
218
|
+
}
|
|
219
|
+
/** Start an Agent Session in a Worktree on the head branch of a Pull Request, or focus the one already on it. */
|
|
220
|
+
async startPullRequestSession(project, ref) {
|
|
221
|
+
const scope = this.projectScope(project);
|
|
222
|
+
const pr = await this.readGit(() => projectTarget(scope, ref, gh));
|
|
223
|
+
const repository = await this.readGit(() => resolveRepository(scope, undefined, gh));
|
|
224
|
+
if (pr.state !== "OPEN")
|
|
225
|
+
throw new CommandRefused("This pull request is not open.");
|
|
226
|
+
if (pr.headRepository?.id !== repository.base.id)
|
|
227
|
+
throw new CommandRefused("This pull request comes from a fork. Flow can start an Agent Session only on a branch in the base repository.");
|
|
228
|
+
const existing = [...this.sessions.values()].find(record => record.lifecycle !== "ended" && scopeKey(record.worktree?.repo ?? record.scope) === scopeKey(scope) && !record.branch?.detached && record.branch?.name === pr.headRefName);
|
|
229
|
+
if (existing)
|
|
230
|
+
return existing.id;
|
|
231
|
+
if (await refExists(scope, pr.headRefName))
|
|
232
|
+
throw new CommandRefused(`The branch ${pr.headRefName} already exists in ${scope}. Start an Agent Session on it from the New Agent Session page.`);
|
|
233
|
+
const { remote } = await this.readGit(() => remoteUrl(scope, pr.repo));
|
|
234
|
+
if (!remote)
|
|
235
|
+
throw new CommandRefused(`No remote in ${scope} points to ${pr.repo}. Add one.`);
|
|
236
|
+
const fetched = await this.readGit(() => fetchBranch(scope, remote, pr.headRefName));
|
|
237
|
+
try {
|
|
238
|
+
return await this.create({ scope, worktree: { from: `${remote}/${pr.headRefName}`, branch: pr.headRefName } });
|
|
239
|
+
}
|
|
240
|
+
catch (error) {
|
|
241
|
+
await dropUnchangedBranch(scope, pr.headRefName, fetched);
|
|
242
|
+
throw error;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
gitScope(sessionId) {
|
|
246
|
+
const scope = this.record(sessionId).scope;
|
|
247
|
+
if (!isRepository(scope))
|
|
248
|
+
throw new CommandRefused("This Scope is not a Git repository.");
|
|
249
|
+
return scope;
|
|
250
|
+
}
|
|
251
|
+
async readChanges(command) {
|
|
252
|
+
const scope = this.gitScope(command.sessionId);
|
|
253
|
+
const base = (branch) => this.gitStates.pullRequestBase(scope, branch);
|
|
254
|
+
return this.readGit(async () => {
|
|
255
|
+
if (command.type === "git_diff")
|
|
256
|
+
return await diff(scope, command.view, command.path, base);
|
|
257
|
+
if (command.view === "branch")
|
|
258
|
+
return await changes(scope, command.view, base);
|
|
259
|
+
const read = await readStatus(scope);
|
|
260
|
+
return { files: read.files, commits: [], fingerprint: read.fingerprint, ...await commitContext(scope, read.local.branch, branch => this.gitStates.hasPullRequest(scope, branch)) };
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
async commit(sessionId, input) {
|
|
264
|
+
this.gitScope(sessionId);
|
|
192
265
|
const record = this.record(sessionId);
|
|
193
266
|
return this.withGitOperation(record.scope, async () => {
|
|
194
|
-
const
|
|
195
|
-
if (!review || review.token !== input.token || review.expires < Date.now())
|
|
196
|
-
throw new CommandRefused("This Publish review expired. Open Publish again.");
|
|
197
|
-
this.publishReviews.delete(sessionId);
|
|
267
|
+
const before = await head(record.scope);
|
|
198
268
|
try {
|
|
199
|
-
return await
|
|
269
|
+
return await commit(record.scope, input);
|
|
200
270
|
}
|
|
201
271
|
finally {
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
272
|
+
const after = await head(record.scope);
|
|
273
|
+
if (after.ok && before.ok && after.value.name !== before.value.name) {
|
|
274
|
+
for (const other of this.sessions.values()) {
|
|
275
|
+
if (scopeKey(other.scope) !== scopeKey(record.scope))
|
|
276
|
+
continue;
|
|
277
|
+
await this.refreshBranch(other);
|
|
278
|
+
other.pendingBranchNote = `[Flow] A commit from the Git pane moved this Scope to branch ${after.value.name}. Re-read the branch and changed files before relying on earlier reads.`;
|
|
279
|
+
}
|
|
207
280
|
}
|
|
208
281
|
}
|
|
209
282
|
});
|
|
210
283
|
}
|
|
284
|
+
async suggestGitText(sessionId, kind, paths) {
|
|
285
|
+
const record = this.record(sessionId);
|
|
286
|
+
if (!["commit", "pull_request", "branch"].includes(kind) || (paths !== undefined && (!Array.isArray(paths) || paths.some(path => typeof path !== "string"))))
|
|
287
|
+
throw new CommandRefused("Invalid suggestion request.");
|
|
288
|
+
const model = this.summaryModel?.(record.backendName);
|
|
289
|
+
if (!model)
|
|
290
|
+
throw new CommandRefused("No Summary Model is configured. Choose one in Settings, or enter the text.");
|
|
291
|
+
return this.readGit(async () => {
|
|
292
|
+
const text = await changesText(record.scope, kind === "pull_request" ? "branch" : "uncommitted", paths, branch => this.gitStates.pullRequestBase(record.scope, branch));
|
|
293
|
+
return await suggestGitText({ backend: this.backendFor(model.backend), modelId: model.modelId, text, kind,
|
|
294
|
+
spent: (spend) => this.recordSpend("publish", randomUUID(), this.spendScope(this.record(sessionId)), spend) });
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
tour(sessionId) {
|
|
298
|
+
this.record(sessionId);
|
|
299
|
+
return this.tours.get(sessionId)?.view ?? { state: "idle" };
|
|
300
|
+
}
|
|
301
|
+
startTour(sessionId) {
|
|
302
|
+
const record = this.record(sessionId);
|
|
303
|
+
this.dropTour(sessionId);
|
|
304
|
+
const tour = { id: randomUUID(), view: { state: "running" } };
|
|
305
|
+
this.tours.set(sessionId, tour);
|
|
306
|
+
void this.runTour(record, tour);
|
|
307
|
+
return tour.view;
|
|
308
|
+
}
|
|
309
|
+
cancelTour(sessionId) {
|
|
310
|
+
this.record(sessionId);
|
|
311
|
+
this.dropTour(sessionId);
|
|
312
|
+
return { state: "idle" };
|
|
313
|
+
}
|
|
314
|
+
dropTour(sessionId) {
|
|
315
|
+
const tour = this.tours.get(sessionId);
|
|
316
|
+
this.tours.delete(sessionId);
|
|
317
|
+
void tour?.handle?.cancel().catch(() => undefined);
|
|
318
|
+
}
|
|
319
|
+
async runTour(record, tour) {
|
|
320
|
+
const current = () => this.tours.get(record.id) === tour;
|
|
321
|
+
let made;
|
|
322
|
+
try {
|
|
323
|
+
const { input, base, ...found } = await tourInput(record.scope);
|
|
324
|
+
made = found;
|
|
325
|
+
if (!current())
|
|
326
|
+
return;
|
|
327
|
+
tour.view = { state: "running", branch: made.branch, head: made.head };
|
|
328
|
+
if (!record.session)
|
|
329
|
+
await this.revive(record.id);
|
|
330
|
+
const session = record.session;
|
|
331
|
+
if (!current())
|
|
332
|
+
return;
|
|
333
|
+
if (!session)
|
|
334
|
+
throw new Error("This Backend Adapter cannot run a tour.");
|
|
335
|
+
const log = record.log.since(0);
|
|
336
|
+
const model = log.findLast(({ event }) => event.type === "model_changed")?.event;
|
|
337
|
+
const effort = log.findLast(({ event }) => event.type === "effort_changed")?.event;
|
|
338
|
+
const chosen = this.tourModel?.(record.backendName);
|
|
339
|
+
const modelId = chosen?.modelId ?? (model?.type === "model_changed" ? model.model.id : record.modelId);
|
|
340
|
+
if (!modelId)
|
|
341
|
+
throw new Error("The Agent Session's model is unknown. Choose a Tour Model in Settings.");
|
|
342
|
+
const text = await this.writeTour(session, tour, input, modelId, chosen?.effort ?? (effort?.type === "effort_changed" ? effort.effort : record.effort) ?? "off", spend => this.workflowSpend(record.id, `tour:${tour.id}`, spend));
|
|
343
|
+
const excerpts = await diffExcerpts(text, found.head, async (path) => ({ view: "branch", diff: await fileDiff(record.scope, path, base, found.head) }));
|
|
344
|
+
if (current())
|
|
345
|
+
tour.view = { state: "done", text, excerpts, ...made };
|
|
346
|
+
}
|
|
347
|
+
catch (error) {
|
|
348
|
+
if (current())
|
|
349
|
+
tour.view = { state: "failed", problem: error instanceof Error ? error.message : String(error), ...(made ? { branch: made.branch, head: made.head } : {}) };
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
async writeTour(session, tour, input, modelId, effort, spent) {
|
|
353
|
+
if (!session.startWorkflowSubagent)
|
|
354
|
+
throw new Error("This Backend Adapter cannot run a tour.");
|
|
355
|
+
tour.handle = session.startWorkflowSubagent({
|
|
356
|
+
id: tour.id, name: "Tour", instructions: TOUR_INSTRUCTIONS, input, modelId, effort, permissionMode: "ask",
|
|
357
|
+
emit: ({ event }) => {
|
|
358
|
+
if (event.type === "permission" && event.state === "asked") {
|
|
359
|
+
queueMicrotask(() => void tour.handle?.answerPermission(event.callId, TOUR_READ_TOOLS.includes(event.tool) ? "allow" : "deny").catch(() => undefined));
|
|
360
|
+
}
|
|
361
|
+
if (event.type === "enquiry" && event.state === "asked") {
|
|
362
|
+
queueMicrotask(() => void tour.handle?.answerEnquiry(event.askId, event.questions.map(() => ["No human is available. Continue without an answer."])).catch(() => undefined));
|
|
363
|
+
}
|
|
364
|
+
if (event.type === "spend")
|
|
365
|
+
spent(event.spend);
|
|
366
|
+
},
|
|
367
|
+
});
|
|
368
|
+
return tourText(await tour.handle.done);
|
|
369
|
+
}
|
|
370
|
+
pullRequestTourKey(project, ref) {
|
|
371
|
+
return `${scopeKey(this.projectScope(project))}\0${ref?.repo}#${ref?.number}`;
|
|
372
|
+
}
|
|
373
|
+
pullRequestTour(project, ref) {
|
|
374
|
+
return this.pullRequestTours.get(this.pullRequestTourKey(project, ref))?.view ?? { state: "idle" };
|
|
375
|
+
}
|
|
376
|
+
startPullRequestTour(project, ref) {
|
|
377
|
+
const key = this.pullRequestTourKey(project, ref);
|
|
378
|
+
if (!this.store)
|
|
379
|
+
throw new CommandRefused("This Session Host keeps no state, so it cannot make a tour.");
|
|
380
|
+
this.dropPullRequestTour(key);
|
|
381
|
+
const tour = { id: randomUUID(), view: { state: "running" } };
|
|
382
|
+
this.pullRequestTours.set(key, tour);
|
|
383
|
+
tour.running = this.runPullRequestTour(project, ref, key, tour);
|
|
384
|
+
return tour.view;
|
|
385
|
+
}
|
|
386
|
+
cancelPullRequestTour(project, ref) {
|
|
387
|
+
this.dropPullRequestTour(this.pullRequestTourKey(project, ref));
|
|
388
|
+
return { state: "idle" };
|
|
389
|
+
}
|
|
390
|
+
dropPullRequestTour(key) {
|
|
391
|
+
const tour = this.pullRequestTours.get(key);
|
|
392
|
+
this.pullRequestTours.delete(key);
|
|
393
|
+
void tour?.handle?.cancel().catch(() => undefined);
|
|
394
|
+
}
|
|
395
|
+
/** A Tour with no Agent Session: a host Backend Session over a read-only checkout of the Pull Request head. */
|
|
396
|
+
async runPullRequestTour(project, ref, key, tour) {
|
|
397
|
+
const current = () => this.pullRequestTours.get(key) === tour;
|
|
398
|
+
let made;
|
|
399
|
+
let checkout;
|
|
400
|
+
let session;
|
|
401
|
+
try {
|
|
402
|
+
const range = await pullRequestRange(project, ref);
|
|
403
|
+
made = { branch: range.pr.headRefName, head: range.head, repo: range.pr.repo };
|
|
404
|
+
if (current())
|
|
405
|
+
tour.view = { state: "running", branch: made.branch, head: made.head };
|
|
406
|
+
const input = await pullRequestTourInput(project, range, { headRefName: range.pr.headRefName, baseRefName: range.pr.baseBranch });
|
|
407
|
+
const backendName = resolveDefaultBackend([...this.backends.keys()], this.defaultBackend?.());
|
|
408
|
+
if (backendName === undefined)
|
|
409
|
+
throw new Error("No backends available");
|
|
410
|
+
const chosen = this.tourModel?.(backendName);
|
|
411
|
+
const configured = chosen?.modelId ?? this.defaultModel?.(backendName);
|
|
412
|
+
let reported;
|
|
413
|
+
if (!current())
|
|
414
|
+
return;
|
|
415
|
+
checkout = join(this.store.worktreesRoot(), ".tours", tour.id);
|
|
416
|
+
const added = await addDetachedCheckout(project, range.head, checkout);
|
|
417
|
+
if (!added.ok) {
|
|
418
|
+
checkout = undefined;
|
|
419
|
+
throw new Error(added.failure.message);
|
|
420
|
+
}
|
|
421
|
+
if (!current())
|
|
422
|
+
return;
|
|
423
|
+
session = await this.backendFor(backendName).create({
|
|
424
|
+
scope: checkout, permissionMode: "ask", readOnly: this.readOnlyEnforcement(), ...(configured ? { modelId: configured } : {}),
|
|
425
|
+
emit: (event) => { if (event.type === "model_changed")
|
|
426
|
+
reported = event.model.id; },
|
|
427
|
+
});
|
|
428
|
+
if (!current())
|
|
429
|
+
return;
|
|
430
|
+
const modelId = configured ?? reported;
|
|
431
|
+
if (!modelId)
|
|
432
|
+
throw new Error("The Default Backend reported no model. Choose a Tour Model in Settings.");
|
|
433
|
+
const text = await this.writeTour(session, tour, input, modelId, chosen?.effort ?? this.defaultEffort?.(backendName) ?? "off", spend => this.recordSpend("tour", tour.id, scopeKey(project), spend));
|
|
434
|
+
const excerpts = await diffExcerpts(text, range.head, async (path) => ({ view: "branch", diff: await fileDiff(project, path, range.base, range.head) }));
|
|
435
|
+
if (current())
|
|
436
|
+
tour.view = { state: "done", text, excerpts, ...made };
|
|
437
|
+
}
|
|
438
|
+
catch (error) {
|
|
439
|
+
if (current())
|
|
440
|
+
tour.view = { state: "failed", problem: error instanceof Error ? error.message : String(error), ...(made ? { branch: made.branch, head: made.head } : {}) };
|
|
441
|
+
}
|
|
442
|
+
finally {
|
|
443
|
+
await session?.dispose().catch(() => undefined);
|
|
444
|
+
if (checkout)
|
|
445
|
+
await removeDetachedCheckout(project, checkout);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
readOnlyEnforcement(isolationMode = this.filesystemIsolationMode()) {
|
|
449
|
+
return isolationMode === "bubblewrap" || (isolationMode === "sandbox" && this.sandboxSharing?.() !== "shared") ? "mounted" : "tools";
|
|
450
|
+
}
|
|
211
451
|
store;
|
|
212
452
|
retention;
|
|
213
453
|
standingAuthorisations;
|
|
@@ -219,12 +459,17 @@ export class SessionHost {
|
|
|
219
459
|
defaultEffort;
|
|
220
460
|
defaultPermissionMode;
|
|
221
461
|
summaryModel;
|
|
462
|
+
tourModel;
|
|
222
463
|
closedListeners = new Set();
|
|
464
|
+
attentionListeners = new Set();
|
|
223
465
|
backendFailures = new Set();
|
|
224
466
|
keptListeners = new Set();
|
|
225
467
|
filesystemIsolation;
|
|
226
468
|
sandbox;
|
|
227
469
|
sandboxSharing;
|
|
470
|
+
updateSourceBranch;
|
|
471
|
+
projectRoot;
|
|
472
|
+
projectPaths;
|
|
228
473
|
shared;
|
|
229
474
|
mcpConnections;
|
|
230
475
|
mcpAuth;
|
|
@@ -233,11 +478,15 @@ export class SessionHost {
|
|
|
233
478
|
this.filesystemIsolation = options.filesystemIsolationMode;
|
|
234
479
|
this.sandbox = options.sandboxSupport;
|
|
235
480
|
this.sandboxSharing = options.sandboxSharing;
|
|
481
|
+
this.updateSourceBranch = options.updateSourceBranch;
|
|
482
|
+
this.projectRoot = options.projectRoot;
|
|
483
|
+
this.projectPaths = options.projectPaths;
|
|
236
484
|
this.shared = options.store ? new SharedSandbox(options.store.root, options.projectRoot ?? (() => undefined)) : undefined;
|
|
237
485
|
this.mcpConnections = options.mcpConnections;
|
|
238
486
|
this.mcpAuth = options.mcpAuth;
|
|
239
487
|
this.resolveSecret = options.resolveSecret;
|
|
240
488
|
this.store = options.store;
|
|
489
|
+
this.spendLedger = options.store ? new SpendLedger(options.store.root) : undefined;
|
|
241
490
|
this.retention = options.retention ?? "never";
|
|
242
491
|
this.standingAuthorisations = options.standingAuthorisations;
|
|
243
492
|
this.allowTool = options.allowTool;
|
|
@@ -248,6 +497,7 @@ export class SessionHost {
|
|
|
248
497
|
this.defaultEffort = options.defaultEffort;
|
|
249
498
|
this.defaultPermissionMode = options.defaultPermissionMode;
|
|
250
499
|
this.summaryModel = options.summaryModel;
|
|
500
|
+
this.tourModel = options.tourModel;
|
|
251
501
|
}
|
|
252
502
|
/**
|
|
253
503
|
* Notified when an Agent Session stops being something its owner is working in — Settled, Ended
|
|
@@ -261,6 +511,10 @@ export class SessionHost {
|
|
|
261
511
|
this.closedListeners.add(listener);
|
|
262
512
|
return () => this.closedListeners.delete(listener);
|
|
263
513
|
}
|
|
514
|
+
onAttentionRaised(listener) {
|
|
515
|
+
this.attentionListeners.add(listener);
|
|
516
|
+
return () => this.attentionListeners.delete(listener);
|
|
517
|
+
}
|
|
264
518
|
announceClosed(sessionId) {
|
|
265
519
|
for (const listener of this.closedListeners)
|
|
266
520
|
listener(sessionId);
|
|
@@ -298,19 +552,29 @@ export class SessionHost {
|
|
|
298
552
|
* In flight rather than resolved is what is remembered, so two clients opening the page at once
|
|
299
553
|
* spawn one probe between them rather than one each.
|
|
300
554
|
*/
|
|
301
|
-
async models(scope, refresh = false) {
|
|
555
|
+
async models(scope, refresh = false, backendName) {
|
|
302
556
|
if (refresh)
|
|
303
557
|
this.modelProbes.clear();
|
|
304
|
-
const
|
|
558
|
+
const backends = backendName === undefined ? [...this.backends.values()] : [this.backendFor(backendName)];
|
|
559
|
+
const probes = backends.map((backend) => {
|
|
305
560
|
const held = this.modelProbes.get(backend.name);
|
|
306
561
|
if (held)
|
|
307
562
|
return held;
|
|
308
|
-
const probe = this.timed("models", backend, false, (timed) => probeModels(timed, scope, false, (held) => this.holdSkillSession(backend.name, held, false)));
|
|
563
|
+
const probe = this.timed("models", backend, false, (timed) => probeModels(backend.name === 'pi' ? this.piModelProbeCache.wrap(timed) : timed, scope, false, (held) => this.holdSkillSession(backend.name, held, false), refresh));
|
|
309
564
|
this.modelProbes.set(backend.name, probe);
|
|
310
565
|
return probe;
|
|
311
566
|
});
|
|
312
567
|
return await Promise.all(probes);
|
|
313
568
|
}
|
|
569
|
+
async workflowAgentModels(scope, backend) {
|
|
570
|
+
const [catalogue] = await this.models(scope, false, backend);
|
|
571
|
+
if (!catalogue || catalogue.problem)
|
|
572
|
+
throw new Error(catalogue?.problem ?? 'Workflow model capabilities are unavailable');
|
|
573
|
+
const probe = this.skillSessions.get(backend);
|
|
574
|
+
if (!probe || probe.dead || !probe.session.startWorkflowSubagent)
|
|
575
|
+
throw new Error('Workflow agent capabilities are unavailable. Retry after the Backend Session is ready.');
|
|
576
|
+
return catalogue.models;
|
|
577
|
+
}
|
|
314
578
|
/**
|
|
315
579
|
* Which Skills a Scope offers through one Backend Adapter, with no Agent Session in it.
|
|
316
580
|
*
|
|
@@ -357,6 +621,27 @@ export class SessionHost {
|
|
|
357
621
|
}
|
|
358
622
|
return await this.timed("skills", backend, false, (timed) => probeSkills(timed, scope, (held) => this.holdSkillSession(backend.name, held, true)));
|
|
359
623
|
}
|
|
624
|
+
async planLimits(scope) {
|
|
625
|
+
this.planLimitProbe ??= Promise.all([...this.backends.values()].map(async (backend) => (await this.askPlanLimits(backend, scope)).map((windows) => ({ backend: backend.name, ...windows }))))
|
|
626
|
+
.then((answers) => answers.flat())
|
|
627
|
+
.finally(() => { this.planLimitProbe = undefined; });
|
|
628
|
+
return await this.planLimitProbe;
|
|
629
|
+
}
|
|
630
|
+
async askPlanLimits(backend, scope) {
|
|
631
|
+
const warm = this.skillSessions.get(backend.name);
|
|
632
|
+
if (warm && !warm.dead) {
|
|
633
|
+
if (!warm.session.planLimits)
|
|
634
|
+
return [];
|
|
635
|
+
try {
|
|
636
|
+
return await this.timed("planLimits", backend, true, () => warm.session.planLimits());
|
|
637
|
+
}
|
|
638
|
+
catch {
|
|
639
|
+
this.skillSessions.delete(backend.name);
|
|
640
|
+
void warm.session.dispose().catch(() => { });
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
return await this.timed("planLimits", backend, false, (timed) => probePlanLimits(timed, scope, (held) => this.holdSkillSession(backend.name, held, false)));
|
|
644
|
+
}
|
|
360
645
|
/** `replace` is false for the model probe: it fills an empty or dead slot and never replaces a live one. */
|
|
361
646
|
holdSkillSession(name, held, replace) {
|
|
362
647
|
const old = this.skillSessions.get(name);
|
|
@@ -425,6 +710,9 @@ export class SessionHost {
|
|
|
425
710
|
};
|
|
426
711
|
if (reason !== "Input needed")
|
|
427
712
|
record.latestOutcome = record.latestAttention;
|
|
713
|
+
for (const listener of this.attentionListeners) {
|
|
714
|
+
listener({ sessionId: record.id, title: record.title, reason, version, at });
|
|
715
|
+
}
|
|
428
716
|
return { at, version };
|
|
429
717
|
}
|
|
430
718
|
/**
|
|
@@ -457,6 +745,7 @@ export class SessionHost {
|
|
|
457
745
|
// lifting an Ended row back out of Filed away.
|
|
458
746
|
const input = record.lifecycle === "live" ? newestAt(parentInput, workflowInput) : undefined;
|
|
459
747
|
const outcome = record.latestOutcome;
|
|
748
|
+
const git = this.gitStates.summary(record.scope);
|
|
460
749
|
const unread = outcome !== undefined && outcome.version > record.readAttentionVersion;
|
|
461
750
|
const attention = input
|
|
462
751
|
? {
|
|
@@ -492,7 +781,9 @@ export class SessionHost {
|
|
|
492
781
|
lastSeq: record.log.lastSeq,
|
|
493
782
|
...(record.capabilities ? { capabilities: record.capabilities } : {}),
|
|
494
783
|
...(record.branch ? { branch: record.branch } : {}),
|
|
784
|
+
...(git ? { git } : {}),
|
|
495
785
|
...(record.worktree ? { worktree: true } : {}),
|
|
786
|
+
...(record.readOnly ? { readOnly: true } : {}),
|
|
496
787
|
...(record.session || existsSync(record.scope) ? {} : {
|
|
497
788
|
scopeMissing: true,
|
|
498
789
|
...this.suggestion(record.scope),
|
|
@@ -522,11 +813,14 @@ export class SessionHost {
|
|
|
522
813
|
async load() {
|
|
523
814
|
if (!this.store)
|
|
524
815
|
return;
|
|
816
|
+
rmSync(join(this.store.worktreesRoot(), ".tours"), { recursive: true, force: true });
|
|
525
817
|
for (const id of await this.store.listSessionIds()) {
|
|
526
818
|
const meta = this.store.readMeta(id);
|
|
527
819
|
if (!meta || this.sessions.has(id))
|
|
528
820
|
continue;
|
|
529
821
|
const entries = this.store.readEntries(id);
|
|
822
|
+
if (this.spendLedger?.needsBackfill)
|
|
823
|
+
this.backfillSpend(id, scopeKey(meta.worktree?.repo ?? meta.scope), entries);
|
|
530
824
|
const record = {
|
|
531
825
|
id: meta.id,
|
|
532
826
|
scope: meta.scope,
|
|
@@ -566,11 +860,15 @@ export class SessionHost {
|
|
|
566
860
|
branch: branchFrom(entries),
|
|
567
861
|
branchGeneration: 0,
|
|
568
862
|
worktree: meta.worktree,
|
|
863
|
+
...(meta.readOnly ? { readOnly: true } : {}),
|
|
864
|
+
...(meta.scheduledOccurrenceId ? { scheduledOccurrenceId: meta.scheduledOccurrenceId } : {}),
|
|
569
865
|
pendingBranchNote: undefined,
|
|
570
866
|
capabilities: capabilitiesFrom(entries),
|
|
571
867
|
spend: spendFrom(entries),
|
|
572
868
|
mcpConnectionIds: meta.mcpConnectionIds ?? [],
|
|
573
869
|
resumeToken: meta.resumeToken,
|
|
870
|
+
imported: meta.imported,
|
|
871
|
+
rewindTo: meta.rewindTo,
|
|
574
872
|
modelId: meta.modelId,
|
|
575
873
|
effort: meta.effort,
|
|
576
874
|
permissionMode: meta.permissionMode ?? this.permissionDefault(meta.backend),
|
|
@@ -591,9 +889,53 @@ export class SessionHost {
|
|
|
591
889
|
}
|
|
592
890
|
this.persist(record);
|
|
593
891
|
}
|
|
892
|
+
this.spendLedger?.finishBackfill();
|
|
594
893
|
await this.reap();
|
|
595
894
|
}
|
|
895
|
+
backfillSpend(sessionId, scope, entries) {
|
|
896
|
+
for (const { event, at } of entries.slice(entries.findLastIndex(({ event }) => event.type === "forked") + 1)) {
|
|
897
|
+
if (event.type === "context_usage" && event.spend)
|
|
898
|
+
this.spendLedger.record("session", sessionId, scope, event.spend, at);
|
|
899
|
+
if (event.type === "workflow_spend")
|
|
900
|
+
this.spendLedger.record("workflow", JSON.stringify([sessionId, event.executionId]), scope, event.spend, at);
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
recordSpend(source, key, scope, spend) {
|
|
904
|
+
this.spendLedger?.record(source, key, scope, spend);
|
|
905
|
+
}
|
|
906
|
+
spendSummary() {
|
|
907
|
+
return this.spendLedger?.summary();
|
|
908
|
+
}
|
|
909
|
+
namingSpent(record) {
|
|
910
|
+
return (spend) => this.recordSpend("naming", randomUUID(), this.spendScope(record), spend);
|
|
911
|
+
}
|
|
912
|
+
spendScope(record) {
|
|
913
|
+
return scopeKey(record.worktree?.repo ?? record.scope);
|
|
914
|
+
}
|
|
915
|
+
scheduledAttachments = new Map();
|
|
916
|
+
/** Internal attachment lane: concurrent agent/input/recovery callbacks share creation and Revive.
|
|
917
|
+
* The caller has already journaled the intended identity before entering this operation. */
|
|
918
|
+
attachScheduled(options) {
|
|
919
|
+
if (this.workflowShutdown)
|
|
920
|
+
return Promise.reject(new CommandRefused('Session Host is stopping'));
|
|
921
|
+
const id = options.scheduled.id;
|
|
922
|
+
const pending = this.scheduledAttachments.get(id);
|
|
923
|
+
if (pending)
|
|
924
|
+
return pending;
|
|
925
|
+
const attachment = this.create(options).finally(() => { this.scheduledAttachments.delete(id); });
|
|
926
|
+
this.scheduledAttachments.set(id, attachment);
|
|
927
|
+
return attachment;
|
|
928
|
+
}
|
|
596
929
|
async create(options) {
|
|
930
|
+
if (options.scheduled) {
|
|
931
|
+
const existing = this.sessions.get(options.scheduled.id);
|
|
932
|
+
if (existing) {
|
|
933
|
+
if (existing.scheduledOccurrenceId !== options.scheduled.occurrenceId)
|
|
934
|
+
throw new Error('Scheduled association mismatch');
|
|
935
|
+
await this.openWorkflowSession(existing.id);
|
|
936
|
+
return existing.id;
|
|
937
|
+
}
|
|
938
|
+
}
|
|
597
939
|
const connections = this.mcpConnections?.() ?? [];
|
|
598
940
|
if (options.mcpConnectionIds !== undefined && (!Array.isArray(options.mcpConnectionIds) || options.mcpConnectionIds.some((id) => typeof id !== "string")))
|
|
599
941
|
throw new Error("Invalid MCP selection");
|
|
@@ -605,17 +947,26 @@ export class SessionHost {
|
|
|
605
947
|
// Reject an unsupported policy before creating a worktree or any durable Agent Session state.
|
|
606
948
|
const permissionMode = options.permissionMode ?? this.permissionDefault(backend.name);
|
|
607
949
|
this.validatePermissionMode(backend.name, permissionMode);
|
|
608
|
-
|
|
950
|
+
if (options.readOnly) {
|
|
951
|
+
const root = this.projectRoot?.();
|
|
952
|
+
if (root === undefined || scopeKey(options.scope) !== scopeKey(root))
|
|
953
|
+
throw new CommandRefused("A Read-only Scope must be the Project Root.");
|
|
954
|
+
if (options.worktree)
|
|
955
|
+
throw new CommandRefused("A Read-only Scope cannot be a Worktree.");
|
|
956
|
+
}
|
|
957
|
+
const cut = options.scheduled?.worktree || !options.worktree ? undefined : await this.cutWorktree(options.scope, options.worktree);
|
|
958
|
+
const worktree = options.scheduled?.worktree ?? cut?.worktree;
|
|
609
959
|
// The Scope from here down, and for this Agent Session's whole life. Resolved before any record
|
|
610
960
|
// exists so that a `worktree add` which failed leaves nothing persisted pointing at a directory
|
|
611
961
|
// that is not there.
|
|
612
962
|
const scope = scopeKey(worktree?.path ?? options.scope);
|
|
613
|
-
const id = randomUUID();
|
|
963
|
+
const id = options.scheduled?.id ?? randomUUID();
|
|
614
964
|
const now = new Date().toISOString();
|
|
615
965
|
const modelId = options.modelId ?? this.defaultModel?.(backend.name);
|
|
616
966
|
const effort = options.effort ?? this.defaultEffort?.(backend.name);
|
|
617
967
|
const record = {
|
|
618
968
|
id,
|
|
969
|
+
...(options.scheduled ? { scheduledOccurrenceId: options.scheduled.occurrenceId } : {}),
|
|
619
970
|
scope,
|
|
620
971
|
backendName: backend.name,
|
|
621
972
|
log: this.newLog(id),
|
|
@@ -645,11 +996,14 @@ export class SessionHost {
|
|
|
645
996
|
branch: undefined,
|
|
646
997
|
branchGeneration: 0,
|
|
647
998
|
worktree,
|
|
999
|
+
...(options.readOnly ? { readOnly: true } : {}),
|
|
648
1000
|
pendingBranchNote: undefined,
|
|
649
1001
|
capabilities: undefined,
|
|
650
1002
|
spend: undefined,
|
|
651
1003
|
mcpConnectionIds,
|
|
652
1004
|
resumeToken: undefined,
|
|
1005
|
+
imported: undefined,
|
|
1006
|
+
rewindTo: undefined,
|
|
653
1007
|
/*
|
|
654
1008
|
* Resolved here and never again.
|
|
655
1009
|
*
|
|
@@ -671,6 +1025,8 @@ export class SessionHost {
|
|
|
671
1025
|
record.buffered = [];
|
|
672
1026
|
let session;
|
|
673
1027
|
try {
|
|
1028
|
+
if (options.fork)
|
|
1029
|
+
this.copyForkState(record, options.fork.source, options.fork.userMessageId, options.fork.prefix);
|
|
674
1030
|
session = await this.startPermissionBackend(record);
|
|
675
1031
|
if (session.capabilities.models.length === 0) {
|
|
676
1032
|
throw new CommandRefused("Model capabilities are unavailable. Check the backend and try again.");
|
|
@@ -680,7 +1036,8 @@ export class SessionHost {
|
|
|
680
1036
|
// Creation never returns an Agent Session without confirmed models. In particular, do not
|
|
681
1037
|
// leave a persisted, empty Agent Session (or a newly cut worktree) after a failed probe.
|
|
682
1038
|
await record.session?.dispose().catch(() => { });
|
|
683
|
-
|
|
1039
|
+
if (!options.scheduled)
|
|
1040
|
+
await this.releaseWorktree(record);
|
|
684
1041
|
record.log.closeSubscribers();
|
|
685
1042
|
this.sessions.delete(id);
|
|
686
1043
|
this.store?.deleteSession(id);
|
|
@@ -694,7 +1051,11 @@ export class SessionHost {
|
|
|
694
1051
|
permissionMode: record.permissionMode,
|
|
695
1052
|
...(worktree === undefined ? {} : { worktree: true }),
|
|
696
1053
|
});
|
|
1054
|
+
if (options.fork)
|
|
1055
|
+
this.appendForkPrefix(record, options.fork.source.id, options.fork.userMessageId, options.fork.prefix);
|
|
697
1056
|
this.flushBuffered(record);
|
|
1057
|
+
if (cut?.warning)
|
|
1058
|
+
record.log.append({ type: "notice", level: "warn", text: cut.warning });
|
|
698
1059
|
// After session_started, never before: the transcript has to open with it (see `buffered`).
|
|
699
1060
|
await this.refreshBranch(record);
|
|
700
1061
|
/*
|
|
@@ -706,9 +1067,150 @@ export class SessionHost {
|
|
|
706
1067
|
* how a spare gets dropped when somebody clears the Setting: nothing will ever *tell* us it
|
|
707
1068
|
* changed (ADR 0009), so a read-through is the only moment it can be noticed.
|
|
708
1069
|
*/
|
|
709
|
-
|
|
1070
|
+
if (!options.scheduled)
|
|
1071
|
+
this.warmSummaryModel(backend.name);
|
|
710
1072
|
return id;
|
|
711
1073
|
}
|
|
1074
|
+
/** The conversations a backend's own tool recorded in `scope` that could be imported here (ADR 0047). */
|
|
1075
|
+
async listImports(backendName, scope) {
|
|
1076
|
+
const name = this.importBackendName(backendName);
|
|
1077
|
+
const key = scopeKey(scope);
|
|
1078
|
+
const imported = new Map();
|
|
1079
|
+
for (const record of this.sessions.values()) {
|
|
1080
|
+
if (record.imported && record.backendName === name && record.scope === key)
|
|
1081
|
+
imported.set(record.imported.conversationId, record.id);
|
|
1082
|
+
}
|
|
1083
|
+
return (await this.importBackend(name).listImports(key)).map((conversation) => {
|
|
1084
|
+
const as = imported.get(conversation.id);
|
|
1085
|
+
return as === undefined ? conversation : { ...conversation, importedAs: as };
|
|
1086
|
+
});
|
|
1087
|
+
}
|
|
1088
|
+
/**
|
|
1089
|
+
* Make an Agent Session from one conversation a backend's own tool recorded (ADR 0047).
|
|
1090
|
+
*
|
|
1091
|
+
* Starts no Backend Session, which is what keeps an import cheap and safe to try: nothing is
|
|
1092
|
+
* spent and nothing runs until somebody writes to the result. A `continue` import is Dormant, so
|
|
1093
|
+
* that first message Revives it through the ordinary path (ADR 0003); a `view` import is Ended,
|
|
1094
|
+
* which is already the Lifecycle that means "readable, never Revived, never Reaped".
|
|
1095
|
+
*
|
|
1096
|
+
* Everything is read and copied before any record exists, and a failure removes what was written
|
|
1097
|
+
* so far: a half-made import must not load on the next boot as an Agent Session with no transcript.
|
|
1098
|
+
*/
|
|
1099
|
+
importConversation(options) {
|
|
1100
|
+
if (options.mode !== "continue" && options.mode !== "view")
|
|
1101
|
+
throw new CommandRefused(`Unknown import mode: ${String(options.mode)}`);
|
|
1102
|
+
const backendName = this.importBackendName(options.backend);
|
|
1103
|
+
const backend = this.importBackend(backendName);
|
|
1104
|
+
const store = this.storeOrThrow();
|
|
1105
|
+
const scope = scopeKey(options.scope);
|
|
1106
|
+
if (!existsSync(scope))
|
|
1107
|
+
throw new CommandRefused(`${scope} does not exist`);
|
|
1108
|
+
const id = randomUUID();
|
|
1109
|
+
let conversation;
|
|
1110
|
+
let resumeToken;
|
|
1111
|
+
try {
|
|
1112
|
+
conversation = backend.readImport(scope, options.conversationId, (mediaType, base64) => isAttachmentMediaType(mediaType) ? store.writeAttachment(id, mediaType, base64) : undefined);
|
|
1113
|
+
if (options.mode === "continue")
|
|
1114
|
+
resumeToken = backend.copyImport(store.backendDir(id), scope, options.conversationId);
|
|
1115
|
+
}
|
|
1116
|
+
catch (error) {
|
|
1117
|
+
store.deleteSession(id);
|
|
1118
|
+
throw new CommandRefused(error instanceof Error ? error.message : String(error));
|
|
1119
|
+
}
|
|
1120
|
+
const now = new Date().toISOString();
|
|
1121
|
+
const effort = options.mode === "continue" ? this.defaultEffort?.(backendName) : undefined;
|
|
1122
|
+
const record = {
|
|
1123
|
+
id,
|
|
1124
|
+
scope,
|
|
1125
|
+
backendName,
|
|
1126
|
+
log: this.newLog(id),
|
|
1127
|
+
session: undefined,
|
|
1128
|
+
reviving: undefined,
|
|
1129
|
+
lifecycle: options.mode === "continue" ? "dormant" : "ended",
|
|
1130
|
+
turnInFlight: false,
|
|
1131
|
+
openSubagentIds: new Set(),
|
|
1132
|
+
openBackgroundCallIds: new Set(),
|
|
1133
|
+
// Now, not when the conversation last moved: somebody who has just imported something is
|
|
1134
|
+
// about to look for it, and a week-old resting time would bury it beneath the Bands above.
|
|
1135
|
+
restingAt: now,
|
|
1136
|
+
settledAt: undefined,
|
|
1137
|
+
// What `backendEpoch` reads back on load, since the transcript opens with `session_started`.
|
|
1138
|
+
backendEpoch: 1,
|
|
1139
|
+
latestAttention: undefined,
|
|
1140
|
+
latestOutcome: undefined,
|
|
1141
|
+
seenAttentionKeys: new Set(),
|
|
1142
|
+
readAttentionVersion: 0,
|
|
1143
|
+
outputPreview: undefined,
|
|
1144
|
+
openPermissionAttention: new Map(),
|
|
1145
|
+
openEnquiryAttention: new Map(),
|
|
1146
|
+
buffered: undefined,
|
|
1147
|
+
queue: [],
|
|
1148
|
+
title: conversation.title,
|
|
1149
|
+
// A name the source gave it is as considered as one ours would be, so it is not replaced by
|
|
1150
|
+
// the first line of whatever is typed next. A first prompt is still only a first line.
|
|
1151
|
+
titleSource: conversation.named ? "summary" : "first-line",
|
|
1152
|
+
titleGeneration: 0,
|
|
1153
|
+
branch: undefined,
|
|
1154
|
+
branchGeneration: 0,
|
|
1155
|
+
worktree: undefined,
|
|
1156
|
+
pendingBranchNote: undefined,
|
|
1157
|
+
capabilities: IMPORTED_CAPABILITIES,
|
|
1158
|
+
spend: undefined,
|
|
1159
|
+
mcpConnectionIds: (this.mcpConnections?.() ?? []).filter((connection) => connection.enabledByDefault).map((connection) => connection.id),
|
|
1160
|
+
resumeToken,
|
|
1161
|
+
imported: { conversationId: options.conversationId },
|
|
1162
|
+
rewindTo: undefined,
|
|
1163
|
+
// Resolved once, as `create` resolves them, so a Revive a month from now does not pick up
|
|
1164
|
+
// whatever the defaults are by then.
|
|
1165
|
+
modelId: options.mode === "continue" ? this.defaultModel?.(backendName) : undefined,
|
|
1166
|
+
effort,
|
|
1167
|
+
permissionMode: this.permissionDefault(backendName),
|
|
1168
|
+
initialEffortUnconfirmed: effort !== undefined,
|
|
1169
|
+
createdAt: conversation.startedAt,
|
|
1170
|
+
updatedAt: now,
|
|
1171
|
+
};
|
|
1172
|
+
try {
|
|
1173
|
+
/*
|
|
1174
|
+
* Opened with `session_started` like every other transcript, so a client reducing it learns
|
|
1175
|
+
* the backend and Scope the usual way. Its Capabilities are honest about having none: no
|
|
1176
|
+
* Backend Session has served this Agent Session yet, and the first Revive reports the real
|
|
1177
|
+
* ones (see `reviveOnce`).
|
|
1178
|
+
*/
|
|
1179
|
+
record.log.append({
|
|
1180
|
+
type: "session_started",
|
|
1181
|
+
backend: backendName,
|
|
1182
|
+
scope,
|
|
1183
|
+
capabilities: IMPORTED_CAPABILITIES,
|
|
1184
|
+
permissionMode: record.permissionMode,
|
|
1185
|
+
}, conversation.startedAt);
|
|
1186
|
+
for (const { at, event } of conversation.events)
|
|
1187
|
+
record.log.append(event, at);
|
|
1188
|
+
record.log.append(options.mode === "continue"
|
|
1189
|
+
? { type: "session_dormant", reason: "imported" }
|
|
1190
|
+
: { type: "session_ended", reason: "imported as read-only" });
|
|
1191
|
+
record.outputPreview = latestParentOutputPreview(record.log.since(0));
|
|
1192
|
+
this.sessions.set(id, record);
|
|
1193
|
+
this.persist(record);
|
|
1194
|
+
}
|
|
1195
|
+
catch (error) {
|
|
1196
|
+
this.sessions.delete(id);
|
|
1197
|
+
store.deleteSession(id);
|
|
1198
|
+
throw error;
|
|
1199
|
+
}
|
|
1200
|
+
return id;
|
|
1201
|
+
}
|
|
1202
|
+
importBackendName(name) {
|
|
1203
|
+
const resolved = name ?? resolveDefaultBackend([...this.backends.keys()], this.defaultBackend?.());
|
|
1204
|
+
if (resolved === undefined)
|
|
1205
|
+
throw new CommandRefused("This Session Host has no backend");
|
|
1206
|
+
return resolved;
|
|
1207
|
+
}
|
|
1208
|
+
importBackend(name) {
|
|
1209
|
+
const backend = this.backends.get(name);
|
|
1210
|
+
if (!backend?.listImports || !backend.readImport || !backend.copyImport)
|
|
1211
|
+
throw new CommandRefused(`Backend Adapter ${name} cannot import conversations`);
|
|
1212
|
+
return backend;
|
|
1213
|
+
}
|
|
712
1214
|
/**
|
|
713
1215
|
* Boot a Summary Model session ahead of needing one, or drop the one held if the Setting is gone.
|
|
714
1216
|
*
|
|
@@ -758,6 +1260,7 @@ export class SessionHost {
|
|
|
758
1260
|
throw new CommandRefused("This Session Host keeps no state, so it cannot make a worktree");
|
|
759
1261
|
if (!isRepository(repo))
|
|
760
1262
|
throw new CommandRefused(`${repo} is not a git repository`);
|
|
1263
|
+
const updated = this.updateSourceBranch?.() && await refExists(repo, options.from) ? await updateSourceBranch(repo, options.from) : undefined;
|
|
761
1264
|
const created = await createWorktree({
|
|
762
1265
|
repo,
|
|
763
1266
|
from: options.from,
|
|
@@ -766,7 +1269,10 @@ export class SessionHost {
|
|
|
766
1269
|
});
|
|
767
1270
|
if (!created.ok)
|
|
768
1271
|
throw new CommandRefused(created.failure.message);
|
|
769
|
-
return {
|
|
1272
|
+
return {
|
|
1273
|
+
worktree: { path: created.value.path, repo, branch: created.value.branch },
|
|
1274
|
+
...(updated?.ok === false ? { warning: `Source Branch ${options.from} was not updated, so the Worktree was cut from the local branch: ${updated.failure.message}` } : {}),
|
|
1275
|
+
};
|
|
770
1276
|
}
|
|
771
1277
|
/** Attach a fresh Backend Session to a Dormant Agent Session, continuing the same transcript. */
|
|
772
1278
|
async revive(sessionId) {
|
|
@@ -805,6 +1311,8 @@ export class SessionHost {
|
|
|
805
1311
|
async relocate(sessionId, scope, repo) {
|
|
806
1312
|
const record = this.record(sessionId);
|
|
807
1313
|
const from = record.scope;
|
|
1314
|
+
if (record.readOnly)
|
|
1315
|
+
throw new CommandRefused("An Agent Session with a Read-only Scope cannot relocate.");
|
|
808
1316
|
if (record.session || record.reviving)
|
|
809
1317
|
throw new CommandRefused("This Agent Session is running. Only a stopped Agent Session can relocate.");
|
|
810
1318
|
if (existsSync(from))
|
|
@@ -867,7 +1375,15 @@ export class SessionHost {
|
|
|
867
1375
|
this.closeOpenSubagents(record, record.log.since(0));
|
|
868
1376
|
this.closeOpenBackgroundCalls(record, record.log.since(0));
|
|
869
1377
|
record.backendEpoch += 1;
|
|
870
|
-
await this.startPermissionBackend(record);
|
|
1378
|
+
const session = await this.startPermissionBackend(record);
|
|
1379
|
+
// An imported Agent Session's transcript opened with no models, because nothing had served it
|
|
1380
|
+
// (ADR 0047). Its first Revive is the first moment its Capabilities are known, and a client
|
|
1381
|
+
// reads them off the transcript — so they are written there, after `revived` like the rest.
|
|
1382
|
+
// Only when the adapter did not already announce them on its way up, which Claude's does.
|
|
1383
|
+
if (record.imported && capabilitiesFrom(record.log.since(0))?.models.length === 0
|
|
1384
|
+
&& !record.buffered?.some((event) => event.type === "capabilities_changed")) {
|
|
1385
|
+
record.buffered?.push({ type: "capabilities_changed", capabilities: session.capabilities });
|
|
1386
|
+
}
|
|
871
1387
|
record.lifecycle = "live";
|
|
872
1388
|
// Un-settled, so the retention window starts again from the next Settle rather than from the
|
|
873
1389
|
// one this Revive just undid.
|
|
@@ -887,7 +1403,7 @@ export class SessionHost {
|
|
|
887
1403
|
* value that can bypass the Steering Queue, and "after_turn" already means "queue if busy, else
|
|
888
1404
|
* dispatch now" — so there is no sensible default to pick. It matches `Command` either way.
|
|
889
1405
|
*/
|
|
890
|
-
async send(sessionId, text, when, attachments, beforeAccept, titleText) {
|
|
1406
|
+
async send(sessionId, text, when, attachments, beforeAccept, titleText, fromSessionId) {
|
|
891
1407
|
const record = this.record(sessionId);
|
|
892
1408
|
this.refuseGitOperation(record.scope);
|
|
893
1409
|
// ADR 0003: the first message revives a Dormant session, so resuming work is one action.
|
|
@@ -900,14 +1416,15 @@ export class SessionHost {
|
|
|
900
1416
|
// Checked before anything is written, so a refused send leaves no bytes behind.
|
|
901
1417
|
this.refuseUnservableAttachments(record, attachments);
|
|
902
1418
|
const ids = (attachments ?? []).map((attachment) => this.storeOrThrow().writeAttachment(record.id, attachment.mediaType, attachment.data));
|
|
1419
|
+
const from = fromSessionId === undefined ? {} : { fromSessionId };
|
|
903
1420
|
if (when === "after_turn" && record.turnInFlight) {
|
|
904
|
-
record.queue.push({ id: randomUUID(), text, attachments: ids });
|
|
1421
|
+
record.queue.push({ id: randomUUID(), text, attachments: ids, ...from });
|
|
905
1422
|
record.log.append(queueChanged(record.queue));
|
|
906
1423
|
this.touch(record);
|
|
907
1424
|
return;
|
|
908
1425
|
}
|
|
909
1426
|
// A title override applies only to the initial dispatch; a queued turn already has a title.
|
|
910
|
-
await this.dispatch(record, { text, attachments: ids }, titleText);
|
|
1427
|
+
await this.dispatch(record, { text, attachments: ids, ...from }, titleText);
|
|
911
1428
|
}
|
|
912
1429
|
/**
|
|
913
1430
|
* Whether this send's Attachments can be carried at all, refused before any are written down.
|
|
@@ -1287,6 +1804,127 @@ export class SessionHost {
|
|
|
1287
1804
|
await session.compact(instructions);
|
|
1288
1805
|
this.touch(record);
|
|
1289
1806
|
}
|
|
1807
|
+
/** Rewind (CONTEXT.md). Answers with the user message, for the composer to offer again. */
|
|
1808
|
+
async rewind(sessionId, userMessageId, restore) {
|
|
1809
|
+
const record = this.record(sessionId);
|
|
1810
|
+
this.refuseGitOperation(record.scope);
|
|
1811
|
+
if (record.lifecycle === "ended")
|
|
1812
|
+
throw new CommandRefused(`Agent Session ${sessionId} has Ended`);
|
|
1813
|
+
const message = userMessage(record.log.since(0), userMessageId)?.event;
|
|
1814
|
+
if (message?.type !== "user_message")
|
|
1815
|
+
throw new CommandRefused("That user message is not in this Agent Session");
|
|
1816
|
+
if (!record.session)
|
|
1817
|
+
await this.revive(sessionId);
|
|
1818
|
+
if (record.permissionChanging)
|
|
1819
|
+
await this.waitForPermissionChange(record);
|
|
1820
|
+
const session = record.session;
|
|
1821
|
+
if (!session)
|
|
1822
|
+
throw new CommandRefused(`Agent Session ${sessionId} has no Backend Session`);
|
|
1823
|
+
if (record.turnInFlight || record.queue.length > 0 || record.openSubagentIds.size > 0 || record.openBackgroundCallIds.size > 0) {
|
|
1824
|
+
throw new CommandRefused("Wait for the turn, the queued messages and the background work to finish, or abort them, before rewinding");
|
|
1825
|
+
}
|
|
1826
|
+
const files = restore !== "conversation";
|
|
1827
|
+
if (files && record.readOnly)
|
|
1828
|
+
throw new CommandRefused("This Agent Session has a Read-only Scope. Rewind only its conversation.");
|
|
1829
|
+
const conversation = restore !== "files";
|
|
1830
|
+
if (conversation && !session.capabilities.rewind)
|
|
1831
|
+
throw new CommandRefused(`${record.backendName} cannot rewind a Conversation Context`);
|
|
1832
|
+
if (files && (!session.capabilities.rewindFiles || !session.rewindFiles))
|
|
1833
|
+
throw new CommandRefused(`${record.backendName} cannot rewind files`);
|
|
1834
|
+
if (files) {
|
|
1835
|
+
try {
|
|
1836
|
+
await session.rewindFiles(userMessageId);
|
|
1837
|
+
}
|
|
1838
|
+
catch (error) {
|
|
1839
|
+
throw new CommandRefused(`Files were not rewound: ${errorMessage(error)}`);
|
|
1840
|
+
}
|
|
1841
|
+
}
|
|
1842
|
+
if (conversation) {
|
|
1843
|
+
record.rewindTo = userMessageId;
|
|
1844
|
+
this.persist(record);
|
|
1845
|
+
record.session = undefined;
|
|
1846
|
+
await this.stopBackendSession(record.scope, session, record.id);
|
|
1847
|
+
record.buffered = [];
|
|
1848
|
+
record.backendEpoch += 1;
|
|
1849
|
+
try {
|
|
1850
|
+
await this.startPermissionBackend(record);
|
|
1851
|
+
}
|
|
1852
|
+
catch (error) {
|
|
1853
|
+
record.buffered = undefined;
|
|
1854
|
+
record.lifecycle = "dormant";
|
|
1855
|
+
record.log.append({ type: "session_dormant", reason: `rewind failed: ${errorMessage(error)}` });
|
|
1856
|
+
this.touch(record);
|
|
1857
|
+
throw error;
|
|
1858
|
+
}
|
|
1859
|
+
}
|
|
1860
|
+
record.log.append({ type: "rewound", userMessageId, restore });
|
|
1861
|
+
this.flushBuffered(record);
|
|
1862
|
+
this.touch(record);
|
|
1863
|
+
return { text: message.text, attachments: message.attachments ?? [] };
|
|
1864
|
+
}
|
|
1865
|
+
/** Fork (CONTEXT.md). Answers with the new Agent Session's id. */
|
|
1866
|
+
async fork(sessionId, userMessageId, worktree) {
|
|
1867
|
+
const source = this.record(sessionId);
|
|
1868
|
+
if (!source.capabilities?.fork)
|
|
1869
|
+
throw new CommandRefused(`${source.backendName} cannot fork a Conversation Context`);
|
|
1870
|
+
const events = source.log.since(0);
|
|
1871
|
+
const at = userMessage(events, userMessageId);
|
|
1872
|
+
if (!at)
|
|
1873
|
+
throw new CommandRefused("That user message is not in this Agent Session");
|
|
1874
|
+
return await this.create({
|
|
1875
|
+
scope: worktree ? source.worktree?.repo ?? source.scope : source.scope,
|
|
1876
|
+
backend: source.backendName,
|
|
1877
|
+
...(source.modelId === undefined ? {} : { modelId: source.modelId }),
|
|
1878
|
+
...(source.effort === undefined ? {} : { effort: source.effort }),
|
|
1879
|
+
permissionMode: source.permissionMode,
|
|
1880
|
+
mcpConnectionIds: source.mcpConnectionIds ?? [],
|
|
1881
|
+
...(worktree === undefined ? {} : { worktree }),
|
|
1882
|
+
...(source.readOnly ? { readOnly: true } : {}),
|
|
1883
|
+
fork: { source, userMessageId, prefix: events.filter((entry) => entry.seq < at.seq) },
|
|
1884
|
+
});
|
|
1885
|
+
}
|
|
1886
|
+
/** Give a Fork the source's Conversation Context, to be cut before the user message on start. */
|
|
1887
|
+
copyForkState(record, source, userMessageId, prefix) {
|
|
1888
|
+
record.title = `${source.title} (fork)`;
|
|
1889
|
+
record.titleSource = "summary";
|
|
1890
|
+
const backend = this.backendFor(source.backendName);
|
|
1891
|
+
const kept = prefix.some(({ event }) => event.type === "user_message");
|
|
1892
|
+
if (!kept || !this.store || !source.resumeToken)
|
|
1893
|
+
return;
|
|
1894
|
+
if (!backend.fork)
|
|
1895
|
+
throw new CommandRefused(`${source.backendName} cannot fork a Conversation Context`);
|
|
1896
|
+
record.resumeToken = backend.fork({ stateDir: this.store.backendDir(source.id), scope: source.scope, resume: source.resumeToken }, { stateDir: this.store.backendDir(record.id), scope: record.scope });
|
|
1897
|
+
record.rewindTo = userMessageId;
|
|
1898
|
+
this.persist(record);
|
|
1899
|
+
}
|
|
1900
|
+
/** Copy what the human saw before the Fork point. The source's session start, scope and queue are not this session's. */
|
|
1901
|
+
appendForkPrefix(record, sourceId, userMessageId, prefix) {
|
|
1902
|
+
for (const { event, at } of prefix) {
|
|
1903
|
+
if (event.type === "session_started" || event.type === "queue_changed" || event.type === "workflow_spend")
|
|
1904
|
+
continue;
|
|
1905
|
+
if (event.type === "context_usage" && event.spend) {
|
|
1906
|
+
const { spend: _, ...rest } = event;
|
|
1907
|
+
record.log.append(rest, at);
|
|
1908
|
+
continue;
|
|
1909
|
+
}
|
|
1910
|
+
if (event.type === "revived") {
|
|
1911
|
+
record.log.append({ type: "revived", fromSeq: event.fromSeq }, at);
|
|
1912
|
+
continue;
|
|
1913
|
+
}
|
|
1914
|
+
if (event.type === "user_message" && event.attachments && this.store) {
|
|
1915
|
+
const to = this.store.attachmentsDir(record.id);
|
|
1916
|
+
mkdirSync(to, { recursive: true });
|
|
1917
|
+
for (const id of event.attachments) {
|
|
1918
|
+
const from = join(this.store.attachmentsDir(sourceId), id);
|
|
1919
|
+
if (existsSync(from))
|
|
1920
|
+
copyFileSync(from, join(to, id));
|
|
1921
|
+
}
|
|
1922
|
+
}
|
|
1923
|
+
record.log.append(event, at);
|
|
1924
|
+
}
|
|
1925
|
+
this.closeTornTurn(record, record.log.since(0));
|
|
1926
|
+
record.log.append({ type: "forked", fromSessionId: sourceId, userMessageId });
|
|
1927
|
+
}
|
|
1290
1928
|
/**
|
|
1291
1929
|
* The Skills this Agent Session can be sent.
|
|
1292
1930
|
*
|
|
@@ -1392,7 +2030,7 @@ export class SessionHost {
|
|
|
1392
2030
|
if (!isRepository(record.scope))
|
|
1393
2031
|
return;
|
|
1394
2032
|
const generation = (record.branchGeneration += 1);
|
|
1395
|
-
const found = await head(record.scope);
|
|
2033
|
+
const [found] = await Promise.all([head(record.scope), this.gitStates.refresh(record.scope)]);
|
|
1396
2034
|
// A repository git cannot answer about is left as it was: this runs off the critical path, and
|
|
1397
2035
|
// there is no reader to tell.
|
|
1398
2036
|
if (!found.ok)
|
|
@@ -1716,6 +2354,7 @@ export class SessionHost {
|
|
|
1716
2354
|
if (previous?.event.type === 'workflow_spend' && JSON.stringify(previous.event.spend) === JSON.stringify(spend))
|
|
1717
2355
|
return;
|
|
1718
2356
|
record.log.append({ type: 'workflow_spend', executionId, spend });
|
|
2357
|
+
this.recordSpend("workflow", JSON.stringify([sessionId, executionId]), this.spendScope(record), spend);
|
|
1719
2358
|
}
|
|
1720
2359
|
authoriseWorkflowTool(tool) { this.allowTool?.(tool); }
|
|
1721
2360
|
workflowNamingAllowed(sessionId) {
|
|
@@ -1727,6 +2366,7 @@ export class SessionHost {
|
|
|
1727
2366
|
if (!record)
|
|
1728
2367
|
return;
|
|
1729
2368
|
this.refuseGitOperation(record.scope);
|
|
2369
|
+
this.dropTour(sessionId);
|
|
1730
2370
|
const session = record.session;
|
|
1731
2371
|
record.session = undefined;
|
|
1732
2372
|
record.lifecycle = "ended";
|
|
@@ -1753,6 +2393,7 @@ export class SessionHost {
|
|
|
1753
2393
|
throw new Error(`Session ${sessionId} has ended`);
|
|
1754
2394
|
if (record.lifecycle === "settled")
|
|
1755
2395
|
return;
|
|
2396
|
+
this.dropTour(sessionId);
|
|
1756
2397
|
const session = record.session;
|
|
1757
2398
|
record.session = undefined;
|
|
1758
2399
|
record.lifecycle = "settled";
|
|
@@ -1801,6 +2442,8 @@ export class SessionHost {
|
|
|
1801
2442
|
for (const record of [...this.sessions.values()]) {
|
|
1802
2443
|
if (record.lifecycle !== "settled")
|
|
1803
2444
|
continue;
|
|
2445
|
+
if (this.workflowOwner?.canForget?.(record.id, record.scheduledOccurrenceId) === false)
|
|
2446
|
+
continue;
|
|
1804
2447
|
const settledAt = record.settledAt === undefined ? NaN : Date.parse(record.settledAt);
|
|
1805
2448
|
// An unreadable timestamp means we cannot know the age; leaving it is the safe failure.
|
|
1806
2449
|
if (Number.isNaN(settledAt) || now - settledAt < retention)
|
|
@@ -1818,7 +2461,7 @@ export class SessionHost {
|
|
|
1818
2461
|
await this.releaseWorktree(record);
|
|
1819
2462
|
record.log.closeSubscribers();
|
|
1820
2463
|
this.sessions.delete(record.id);
|
|
1821
|
-
this.
|
|
2464
|
+
this.dropTour(record.id);
|
|
1822
2465
|
this.store?.deleteSession(record.id);
|
|
1823
2466
|
reaped.push(record.id);
|
|
1824
2467
|
}
|
|
@@ -1898,7 +2541,7 @@ export class SessionHost {
|
|
|
1898
2541
|
}
|
|
1899
2542
|
const generation = (record.titleGeneration += 1);
|
|
1900
2543
|
let reason;
|
|
1901
|
-
const name = await this.summarySpare.name(backend, summary, nameInput(entries), undefined, (problem) => { reason = problem; });
|
|
2544
|
+
const name = await this.summarySpare.name(backend, summary, nameInput(entries), undefined, (problem) => { reason = problem; }, this.namingSpent(record));
|
|
1902
2545
|
if (name === undefined)
|
|
1903
2546
|
throw new CommandRefused(`Could not name this Agent Session${reason ? `: ${reason}` : ""}`);
|
|
1904
2547
|
// Refused rather than applied when something newer has already been asked for. A human who
|
|
@@ -1932,7 +2575,7 @@ export class SessionHost {
|
|
|
1932
2575
|
const generation = (record.titleGeneration += 1);
|
|
1933
2576
|
let name;
|
|
1934
2577
|
try {
|
|
1935
|
-
name = await this.summarySpare.name(this.backendFor(summary.backend), summary, input);
|
|
2578
|
+
name = await this.summarySpare.name(this.backendFor(summary.backend), summary, input, undefined, undefined, this.namingSpent(record));
|
|
1936
2579
|
}
|
|
1937
2580
|
catch {
|
|
1938
2581
|
return;
|
|
@@ -1956,12 +2599,14 @@ export class SessionHost {
|
|
|
1956
2599
|
this.workflowShutdown = true;
|
|
1957
2600
|
// Creation can still be awaiting backend startup after its caller disconnects. Drain those
|
|
1958
2601
|
// accepted operations before walking sessions, so late children cannot escape shutdown.
|
|
1959
|
-
await Promise.allSettled([...this.sessionToolOperations]);
|
|
2602
|
+
await Promise.allSettled([...this.sessionToolOperations, ...this.scheduledAttachments.values()]);
|
|
1960
2603
|
// First, so that a naming still in flight cannot warm a replacement on the way out — the
|
|
1961
2604
|
// one-shot CLI runner shuts down microseconds before `process.exit`, and a spare booted in
|
|
1962
2605
|
// that window is a child process nothing is left to dispose. Not awaited, and cannot be: see
|
|
1963
2606
|
// `SummaryModelSpare.dispose`.
|
|
1964
2607
|
this.summarySpare.dispose();
|
|
2608
|
+
const tours = [...this.pullRequestTours.keys()].map(key => { const running = this.pullRequestTours.get(key)?.running; this.dropPullRequestTour(key); return running; });
|
|
2609
|
+
await Promise.allSettled(tours);
|
|
1965
2610
|
const warm = [...this.skillSessions.values()];
|
|
1966
2611
|
this.skillSessions.clear();
|
|
1967
2612
|
await Promise.all(warm.map((held) => held.session.dispose().catch(() => { })));
|
|
@@ -1984,8 +2629,15 @@ export class SessionHost {
|
|
|
1984
2629
|
this.persist(record);
|
|
1985
2630
|
}
|
|
1986
2631
|
await this.shared?.close().catch((error) => console.error(`Shared sandbox removal failed: ${error.message}`));
|
|
2632
|
+
const stopped = await Promise.allSettled([...this.backends.values()].map(async (backend) => backend.shutdown?.()));
|
|
2633
|
+
const failures = stopped.filter(result => result.status === "rejected").map(result => result.reason);
|
|
2634
|
+
if (failures.length)
|
|
2635
|
+
throw new AggregateError(failures, "Backend Adapter shutdown failed");
|
|
1987
2636
|
}
|
|
1988
2637
|
async execute(command) {
|
|
2638
|
+
if (READ_ONLY_REFUSED.has(command.type) && "sessionId" in command && this.record(command.sessionId).readOnly) {
|
|
2639
|
+
throw new CommandRefused("This Agent Session has a Read-only Scope. It cannot change Git state or run a Tour.");
|
|
2640
|
+
}
|
|
1989
2641
|
switch (command.type) {
|
|
1990
2642
|
case "create":
|
|
1991
2643
|
return await this.create({
|
|
@@ -1996,6 +2648,7 @@ export class SessionHost {
|
|
|
1996
2648
|
...(command.permissionMode === undefined ? {} : { permissionMode: command.permissionMode }),
|
|
1997
2649
|
...(command.mcpConnectionIds === undefined ? {} : { mcpConnectionIds: command.mcpConnectionIds }),
|
|
1998
2650
|
...(command.worktree === undefined ? {} : { worktree: command.worktree }),
|
|
2651
|
+
...(command.readOnly ? { readOnly: true } : {}),
|
|
1999
2652
|
});
|
|
2000
2653
|
case "send":
|
|
2001
2654
|
return await this.send(command.sessionId, command.text, command.when, command.attachments);
|
|
@@ -2023,28 +2676,100 @@ export class SessionHost {
|
|
|
2023
2676
|
return await this.setEffort(command.sessionId, command.effort);
|
|
2024
2677
|
case "pull_branch":
|
|
2025
2678
|
return await this.withGitOperation(this.record(command.sessionId).scope, () => pullBranch(this.record(command.sessionId).scope, command.branch));
|
|
2026
|
-
case "change_pull_request":
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
return await
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2679
|
+
case "change_pull_request": {
|
|
2680
|
+
const { scope, find } = this.pullRequestPlace(command);
|
|
2681
|
+
const change = () => this.afterPullRequestWrite(scope, changePullRequest(scope, command.action, command.input, gh, find));
|
|
2682
|
+
return await (find ? this.readGit(change) : this.withGitOperation(scope, change));
|
|
2683
|
+
}
|
|
2684
|
+
case "pull_request": {
|
|
2685
|
+
if ("project" in command) {
|
|
2686
|
+
const scope = this.projectScope(command.project);
|
|
2687
|
+
return await this.readGit(() => projectPullRequest(scope, command.number));
|
|
2688
|
+
}
|
|
2689
|
+
const scope = this.record(command.sessionId).scope;
|
|
2690
|
+
return await this.readGit(() => pullRequest(scope, this.gitStates.pullRequestRef(scope)));
|
|
2691
|
+
}
|
|
2692
|
+
case "comment_pull_request": {
|
|
2693
|
+
const { scope, find } = this.pullRequestPlace(command);
|
|
2694
|
+
return await this.afterPullRequestWrite(scope, commentPullRequest(scope, command.input, gh, find));
|
|
2695
|
+
}
|
|
2696
|
+
case "resolve_pull_request_thread": {
|
|
2697
|
+
const { scope, find } = this.pullRequestPlace(command);
|
|
2698
|
+
return await this.afterPullRequestWrite(scope, resolvePullRequestThread(scope, command.input, gh, find));
|
|
2699
|
+
}
|
|
2700
|
+
case "edit_pull_request": {
|
|
2701
|
+
const { scope, find } = this.pullRequestPlace(command);
|
|
2702
|
+
return await this.afterPullRequestWrite(scope, editPullRequest(scope, command.input, gh, find));
|
|
2703
|
+
}
|
|
2704
|
+
case "set_pull_request_draft": {
|
|
2705
|
+
const { scope, find } = this.pullRequestPlace(command);
|
|
2706
|
+
return await this.afterPullRequestWrite(scope, setPullRequestDraft(scope, command.input, gh, find));
|
|
2707
|
+
}
|
|
2708
|
+
case "rerun_pull_request_checks": {
|
|
2709
|
+
const { scope, find } = this.pullRequestPlace(command);
|
|
2710
|
+
return await this.afterPullRequestWrite(scope, rerunPullRequestChecks(scope, command.input, gh, find));
|
|
2711
|
+
}
|
|
2712
|
+
case "pull_request_check_log": {
|
|
2713
|
+
const { scope, find } = this.pullRequestPlace(command);
|
|
2714
|
+
return await checkLog(scope, command.pr, command.jobId, gh, find);
|
|
2715
|
+
}
|
|
2716
|
+
case "submit_pull_request_review": {
|
|
2717
|
+
const { scope, find } = this.pullRequestPlace(command);
|
|
2718
|
+
return await this.afterPullRequestWrite(scope, submitReview(scope, command.input, gh, find));
|
|
2719
|
+
}
|
|
2720
|
+
case "project_pull_requests": {
|
|
2721
|
+
const scope = this.projectScope(command.project);
|
|
2722
|
+
const query = typeof command.query === "string" ? command.query.trim() : "";
|
|
2723
|
+
return await this.readGit(() => listPullRequests(scope, gh, query || undefined));
|
|
2724
|
+
}
|
|
2725
|
+
case "pull_request_changes":
|
|
2726
|
+
case "pull_request_diff": {
|
|
2727
|
+
const scope = this.projectScope(command.project);
|
|
2728
|
+
return await this.readGit(async () => {
|
|
2729
|
+
const range = await pullRequestRange(scope, command.pr);
|
|
2730
|
+
return command.type === "pull_request_diff" ? await fileDiff(scope, command.path, range.base, range.head) : await rangeChanges(scope, range.base, range.head);
|
|
2731
|
+
});
|
|
2732
|
+
}
|
|
2733
|
+
case "start_pull_request_session":
|
|
2734
|
+
return await this.startPullRequestSession(command.project, command.pr);
|
|
2034
2735
|
case "stack_status":
|
|
2035
|
-
return await this.
|
|
2736
|
+
return await this.readStack(command.sessionId);
|
|
2036
2737
|
case "prepare_stack":
|
|
2037
2738
|
return await this.prepareStack(command.sessionId, command.action);
|
|
2038
2739
|
case "change_stack":
|
|
2039
2740
|
return await this.changeStack(command.sessionId, command.input);
|
|
2040
2741
|
case "assist_stack":
|
|
2041
2742
|
return await this.assistStack(command.sessionId);
|
|
2042
|
-
case "
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2743
|
+
case "refresh_git": {
|
|
2744
|
+
const scope = this.record(command.sessionId).scope;
|
|
2745
|
+
if (!isRepository(scope)) {
|
|
2746
|
+
await this.gitStates.refresh(scope);
|
|
2747
|
+
return { repository: false };
|
|
2748
|
+
}
|
|
2749
|
+
await Promise.all([...this.sessions.values()].filter(other => scopeKey(other.scope) === scopeKey(scope)).map(other => this.refreshBranch(other)));
|
|
2750
|
+
if (command.pullRequest === true)
|
|
2751
|
+
await this.pollGitState(scope);
|
|
2752
|
+
return { repository: true };
|
|
2753
|
+
}
|
|
2754
|
+
case "git_changes":
|
|
2755
|
+
case "git_diff":
|
|
2756
|
+
return await this.readChanges(command);
|
|
2757
|
+
case "commit":
|
|
2758
|
+
return await this.commit(command.sessionId, { fingerprint: command.fingerprint, paths: command.paths, message: command.message, ...(command.branch === undefined ? {} : { branch: command.branch }) });
|
|
2759
|
+
case "push_state":
|
|
2760
|
+
return await this.readGit(() => pushState(this.gitScope(command.sessionId)));
|
|
2761
|
+
case "push":
|
|
2762
|
+
return await this.withGitOperation(this.gitScope(command.sessionId), () => this.afterPullRequestWrite(this.record(command.sessionId).scope, push(this.record(command.sessionId).scope, { head: command.head, ...(command.replace === undefined ? {} : { replace: command.replace }) })));
|
|
2763
|
+
case "create_pull_request":
|
|
2764
|
+
return await this.withGitOperation(this.gitScope(command.sessionId), () => this.afterPullRequestWrite(this.record(command.sessionId).scope, createPullRequest(this.record(command.sessionId).scope, { head: command.head, title: command.title, body: command.body, draft: command.draft === true })));
|
|
2765
|
+
case "suggest_git_text":
|
|
2766
|
+
return await this.suggestGitText(command.sessionId, command.kind, command.paths);
|
|
2767
|
+
case "start_tour":
|
|
2768
|
+
return "project" in command ? this.startPullRequestTour(command.project, command.pr) : this.startTour(command.sessionId);
|
|
2769
|
+
case "tour":
|
|
2770
|
+
return "project" in command ? this.pullRequestTour(command.project, command.pr) : this.tour(command.sessionId);
|
|
2771
|
+
case "cancel_tour":
|
|
2772
|
+
return "project" in command ? this.cancelPullRequestTour(command.project, command.pr) : this.cancelTour(command.sessionId);
|
|
2048
2773
|
case "switch_branch":
|
|
2049
2774
|
return await this.switchBranch(command.sessionId, command.branch);
|
|
2050
2775
|
case "switch_scope_branch":
|
|
@@ -2053,12 +2778,20 @@ export class SessionHost {
|
|
|
2053
2778
|
return await this.rename(command.sessionId);
|
|
2054
2779
|
case "compact":
|
|
2055
2780
|
return await this.compact(command.sessionId, command.instructions);
|
|
2781
|
+
case "rewind":
|
|
2782
|
+
return await this.rewind(command.sessionId, command.userMessageId, command.restore);
|
|
2783
|
+
case "fork":
|
|
2784
|
+
return await this.fork(command.sessionId, command.userMessageId, command.worktree);
|
|
2056
2785
|
case "answer_enquiry":
|
|
2057
2786
|
return await this.answerEnquiry(command.sessionId, command.askId, command.answers);
|
|
2058
2787
|
case "answer_permission":
|
|
2059
2788
|
return await this.answerPermission(command.sessionId, command.callId, command.decision);
|
|
2060
2789
|
case "list_skills":
|
|
2061
2790
|
return await this.listSkills(command.sessionId);
|
|
2791
|
+
case "list_imports":
|
|
2792
|
+
return await this.listImports(command.backend, command.scope);
|
|
2793
|
+
case "import":
|
|
2794
|
+
return this.importConversation(command);
|
|
2062
2795
|
case "list":
|
|
2063
2796
|
return this.list();
|
|
2064
2797
|
}
|
|
@@ -2110,36 +2843,58 @@ export class SessionHost {
|
|
|
2110
2843
|
throw new Error('Unknown Agent Session');
|
|
2111
2844
|
return structuredClone((this.mcpConnections?.() ?? []).filter(connection => record.mcpConnectionIds?.includes(connection.id)));
|
|
2112
2845
|
}
|
|
2846
|
+
scheduledConnections(ids) {
|
|
2847
|
+
const connections = this.mcpConnections?.() ?? [];
|
|
2848
|
+
if (ids.some(id => !connections.some(connection => connection.id === id)))
|
|
2849
|
+
throw new ScheduleValidationError('Selected MCP connection is unavailable');
|
|
2850
|
+
return structuredClone(connections.filter(connection => ids.includes(connection.id)));
|
|
2851
|
+
}
|
|
2852
|
+
scheduledMcp(scope, ids, mode) {
|
|
2853
|
+
const connections = this.scheduledConnections(ids);
|
|
2854
|
+
const oauth = this.mcpAuth ? (connection) => this.mcpAuth.provider(connection) : undefined;
|
|
2855
|
+
return import('../backend/mcp.js').then(({ McpSession }) => new McpSession(connections, scope, oauth, true, this.resolveSecret, undefined, this.filesystemStateRoot(), mode));
|
|
2856
|
+
}
|
|
2857
|
+
scheduledSandboxMcp(scope, ids) {
|
|
2858
|
+
return import('../backend/worker/sandbox-mcp.js').then(({ SandboxMcpSession }) => new SandboxMcpSession(this.scheduledConnections(ids), scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, this.resolveSecret));
|
|
2859
|
+
}
|
|
2113
2860
|
/** Include an SDK-supplied owning root in every local execution's filesystem policy. */
|
|
2114
2861
|
filesystemStateRoot() { return this.store?.root; }
|
|
2115
2862
|
/** A host without configured Settings keeps the safe, restricted library default. */
|
|
2116
2863
|
filesystemIsolationMode() { return this.filesystemIsolation?.() ?? "bubblewrap"; }
|
|
2117
2864
|
sandboxSupport() { return this.sandbox?.(); }
|
|
2118
2865
|
/** The Shared Sandbox, when the Settings choose one VM for all sandbox sessions. */
|
|
2866
|
+
scheduledSandboxMounts(scope) {
|
|
2867
|
+
const mounts = [...this.backends.values()].flatMap(backend => backend.scheduledSandboxMounts?.(scope) ?? []);
|
|
2868
|
+
return { writable: mounts.flatMap(item => item.writable), readable: mounts.flatMap(item => item.readable) };
|
|
2869
|
+
}
|
|
2870
|
+
isReadOnly(sessionId) { return this.record(sessionId).readOnly === true; }
|
|
2119
2871
|
sharedSandbox() { return this.sandboxSharing?.() === "shared" ? this.shared : undefined; }
|
|
2120
|
-
async openWorkflowMcp(id, connectionId, isolationMode = this.filesystemIsolationMode()) {
|
|
2872
|
+
async openWorkflowMcp(id, connectionId, isolationMode = this.filesystemIsolationMode(), signal) {
|
|
2873
|
+
signal?.throwIfAborted();
|
|
2121
2874
|
if (isolationMode === "sandbox") {
|
|
2122
|
-
await this.openWorkflowSession(id);
|
|
2875
|
+
await waitForAbort(this.openWorkflowSession(id), signal);
|
|
2876
|
+
signal?.throwIfAborted();
|
|
2123
2877
|
const { SandboxMcpSession } = await import("../backend/worker/sandbox-mcp.js");
|
|
2124
2878
|
const mcp = this.record(id).mcp;
|
|
2125
2879
|
if (!(mcp instanceof SandboxMcpSession))
|
|
2126
2880
|
throw new Error("Sandbox isolation is unavailable; unrestricted launch refused: the Agent Session has no sandbox");
|
|
2127
|
-
return mcp.directView(connectionId);
|
|
2881
|
+
return mcp.directView(connectionId, signal);
|
|
2128
2882
|
}
|
|
2129
2883
|
const connection = this.workflowMcpConnections(id).find(connection => connection.id === connectionId);
|
|
2130
2884
|
if (!connection)
|
|
2131
2885
|
throw new Error('MCP connection is removed or disabled for this Agent Session. Enable it in the Agent Session settings and reconfigure the step.');
|
|
2132
|
-
const { McpSession } = await import(
|
|
2886
|
+
const { McpSession } = await import('../backend/mcp.js');
|
|
2133
2887
|
const scope = this.workflowSession(id).scope;
|
|
2134
|
-
|
|
2888
|
+
signal?.throwIfAborted();
|
|
2889
|
+
return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode, undefined, undefined, this.isReadOnly(id));
|
|
2135
2890
|
}
|
|
2136
2891
|
/** Metadata discovery owned by authoring, never by an Agent/Backend Session. */
|
|
2137
2892
|
async openWorkflowMcpAuthoring(scope, connectionId, isolationMode = this.filesystemIsolationMode(), expectedScopeIdentity) {
|
|
2138
2893
|
const connection = (this.mcpConnections?.() ?? []).find(connection => connection.id === connectionId);
|
|
2139
2894
|
if (!connection)
|
|
2140
2895
|
throw new Error('MCP connection removed. Refresh the workflow editor.');
|
|
2141
|
-
const { McpSession } = await import(
|
|
2142
|
-
return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode, expectedScopeIdentity);
|
|
2896
|
+
const { McpSession } = await import('../backend/mcp.js');
|
|
2897
|
+
return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode, expectedScopeIdentity, undefined, true);
|
|
2143
2898
|
}
|
|
2144
2899
|
mcpStatus(id) {
|
|
2145
2900
|
const record = this.sessions.get(id);
|
|
@@ -2247,21 +3002,25 @@ export class SessionHost {
|
|
|
2247
3002
|
},
|
|
2248
3003
|
create: (input, signal) => owned(async () => {
|
|
2249
3004
|
check(signal);
|
|
2250
|
-
const { text, scope = source.scope, backend: name = source.backendName, modelId, effort
|
|
3005
|
+
const { text, worktree, scope = worktree ? source.worktree?.repo ?? source.scope : source.scope, backend: name = source.backendName, modelId, effort } = sessionCreateInput.parse(input);
|
|
2251
3006
|
if (!isAbsolute(scope))
|
|
2252
3007
|
throw new CommandRefused('Scope must be an absolute directory');
|
|
3008
|
+
const readOnly = source.readOnly && !(this.projectPaths?.() ?? []).some(path => scopeKey(path) === scopeKey(scope));
|
|
3009
|
+
if (readOnly && scopeKey(scope) !== scopeKey(this.projectRoot?.() ?? scope))
|
|
3010
|
+
throw new CommandRefused('A read-only Agent Session can create Agent Sessions only in a Project or at the Project Root');
|
|
2253
3011
|
const sessionId = await this.create({ scope, backend: name,
|
|
3012
|
+
...(readOnly ? { readOnly: true } : {}),
|
|
2254
3013
|
...(modelId === undefined ? {} : { modelId }),
|
|
2255
3014
|
...(effort === undefined ? {} : { effort }),
|
|
2256
3015
|
...(worktree === undefined ? {} : { worktree: { from: worktree.from, ...(worktree.branch === undefined ? {} : { branch: worktree.branch }) } }),
|
|
2257
3016
|
mcpConnectionIds: source.mcpConnectionIds ?? [],
|
|
2258
3017
|
permissionMode: source.permissionMode === 'auto' && name !== 'claude' ? 'ask' : source.permissionMode });
|
|
2259
3018
|
// Persist a receipt even if cancellation loses the RPC result; never blindly recreate.
|
|
2260
|
-
source.log.append({ type: 'notice', level: 'info', text: `Created Agent Session ${sessionId}
|
|
2261
|
-
this.record(sessionId).log.append({ type: 'notice', level: 'info', text: `Created by Agent Session ${source.id}
|
|
3019
|
+
source.log.append({ type: 'notice', level: 'info', text: `Created Agent Session ${sessionId}`, sessionId });
|
|
3020
|
+
this.record(sessionId).log.append({ type: 'notice', level: 'info', text: `Created by Agent Session ${source.id}`, sessionId: source.id });
|
|
2262
3021
|
try {
|
|
2263
3022
|
check(signal);
|
|
2264
|
-
await this.send(sessionId, attributed(text), 'after_turn', undefined, () => check(signal), text);
|
|
3023
|
+
await this.send(sessionId, attributed(text), 'after_turn', undefined, () => check(signal), text, source.id);
|
|
2265
3024
|
return { sessionId, delivery: 'accepted' };
|
|
2266
3025
|
}
|
|
2267
3026
|
catch (error) {
|
|
@@ -2273,7 +3032,7 @@ export class SessionHost {
|
|
|
2273
3032
|
const { sessionId, text } = sessionSendInput.parse(input);
|
|
2274
3033
|
if (sessionId === source.id)
|
|
2275
3034
|
throw new CommandRefused('Use the current conversation instead of messaging yourself');
|
|
2276
|
-
await this.send(sessionId, attributed(text), 'after_turn', undefined, () => check(signal), text);
|
|
3035
|
+
await this.send(sessionId, attributed(text), 'after_turn', undefined, () => check(signal), text, source.id);
|
|
2277
3036
|
return { sessionId, delivery: 'accepted' };
|
|
2278
3037
|
}),
|
|
2279
3038
|
};
|
|
@@ -2288,13 +3047,14 @@ export class SessionHost {
|
|
|
2288
3047
|
const isolationMode = this.filesystemIsolationMode();
|
|
2289
3048
|
const mcp = isolationMode === "sandbox"
|
|
2290
3049
|
? new SandboxMcpSession(selected, record.scope, oauth, this.resolveSecret)
|
|
2291
|
-
: new McpSession(selected, record.scope, oauth, false, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode);
|
|
3050
|
+
: new McpSession(selected, record.scope, oauth, false, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode, undefined, undefined, record.readOnly === true);
|
|
2292
3051
|
record.mcp = mcp;
|
|
2293
3052
|
const openingMcp = mcp.open();
|
|
2294
3053
|
const autoCompaction = this.autoCompaction?.(backend.name);
|
|
2295
3054
|
const compactionModelId = this.compactionModel?.(backend.name);
|
|
2296
3055
|
let attached;
|
|
2297
3056
|
const session = await backend.create({
|
|
3057
|
+
isolationMode,
|
|
2298
3058
|
mcp,
|
|
2299
3059
|
onFailure: () => {
|
|
2300
3060
|
if (!attached || record.session !== attached)
|
|
@@ -2315,6 +3075,7 @@ export class SessionHost {
|
|
|
2315
3075
|
throw new Error('Workflow execution is unavailable'); return this.workflowOwner.parent(record.id).relayPermission(input, signal); },
|
|
2316
3076
|
},
|
|
2317
3077
|
scope: record.scope,
|
|
3078
|
+
...(record.readOnly ? { readOnly: this.readOnlyEnforcement(isolationMode) } : {}),
|
|
2318
3079
|
emit: (event) => {
|
|
2319
3080
|
if (!attached || record.session === attached)
|
|
2320
3081
|
this.onBackendEvent(record.id, event);
|
|
@@ -2325,6 +3086,7 @@ export class SessionHost {
|
|
|
2325
3086
|
...(record.effort === undefined ? {} : { effort: record.effort }),
|
|
2326
3087
|
permissionMode: record.permissionMode,
|
|
2327
3088
|
...(record.resumeToken === undefined ? {} : { resume: record.resumeToken }),
|
|
3089
|
+
...(record.resumeToken === undefined || record.rewindTo === undefined ? {} : { resumeBefore: record.rewindTo }),
|
|
2328
3090
|
...(record.spend === undefined ? {} : { priorSpend: record.spend }),
|
|
2329
3091
|
...(this.store ? { stateDir: this.store.backendDir(record.id) } : {}),
|
|
2330
3092
|
// Read here rather than held, so a Revive picks up every grant made since this Agent Session
|
|
@@ -2385,8 +3147,8 @@ export class SessionHost {
|
|
|
2385
3147
|
await abort();
|
|
2386
3148
|
};
|
|
2387
3149
|
const prompt = session.prompt.bind(session);
|
|
2388
|
-
session.prompt = (text, attachments) => {
|
|
2389
|
-
pendingTurn = waitForMcp(() => prompt(text, attachments));
|
|
3150
|
+
session.prompt = (text, attachments, messageId) => {
|
|
3151
|
+
pendingTurn = waitForMcp(() => prompt(text, attachments, messageId));
|
|
2390
3152
|
return pendingTurn;
|
|
2391
3153
|
};
|
|
2392
3154
|
if (session.compact) {
|
|
@@ -2532,7 +3294,7 @@ export class SessionHost {
|
|
|
2532
3294
|
}
|
|
2533
3295
|
record.initialEffortUnconfirmed = false;
|
|
2534
3296
|
}
|
|
2535
|
-
const { text, attachments } = message;
|
|
3297
|
+
const { text, attachments, fromSessionId } = message;
|
|
2536
3298
|
const note = record.pendingBranchNote;
|
|
2537
3299
|
record.pendingBranchNote = undefined;
|
|
2538
3300
|
/*
|
|
@@ -2549,11 +3311,14 @@ export class SessionHost {
|
|
|
2549
3311
|
const startingTurn = !record.turnInFlight;
|
|
2550
3312
|
const generation = record.turnGeneration = (record.turnGeneration ?? 0) + (startingTurn ? 1 : 0);
|
|
2551
3313
|
record.turnInFlight = true;
|
|
3314
|
+
const messageId = randomUUID();
|
|
2552
3315
|
record.log.append({
|
|
2553
3316
|
type: "user_message",
|
|
2554
|
-
id:
|
|
2555
|
-
text
|
|
3317
|
+
id: messageId,
|
|
3318
|
+
text,
|
|
3319
|
+
...(note === undefined ? {} : { note }),
|
|
2556
3320
|
...(attachments.length > 0 ? { attachments } : {}),
|
|
3321
|
+
...(fromSessionId === undefined ? {} : { fromSessionId }),
|
|
2557
3322
|
});
|
|
2558
3323
|
// Titled from the original instructions, never attribution or `sent`. A switch made before the first
|
|
2559
3324
|
// message would otherwise name the Agent Session after the note, and permanently: the rename
|
|
@@ -2584,7 +3349,7 @@ export class SessionHost {
|
|
|
2584
3349
|
this.recordDispatchFailure(record, error, startingTurn);
|
|
2585
3350
|
};
|
|
2586
3351
|
try {
|
|
2587
|
-
void session.prompt(workflowContext ? `${sent}\n\n${workflowContext}` : sent, this.loadAttachments(record.id, attachments)).catch(failed);
|
|
3352
|
+
void session.prompt(workflowContext ? `${sent}\n\n${workflowContext}` : sent, this.loadAttachments(record.id, attachments), messageId).catch(failed);
|
|
2588
3353
|
}
|
|
2589
3354
|
catch (error) {
|
|
2590
3355
|
failed(error);
|
|
@@ -2616,6 +3381,15 @@ export class SessionHost {
|
|
|
2616
3381
|
for (const event of buffered)
|
|
2617
3382
|
this.onBackendEvent(record.id, event);
|
|
2618
3383
|
}
|
|
3384
|
+
async diffExcerpts(sessionId, text) {
|
|
3385
|
+
const scope = this.record(sessionId).scope;
|
|
3386
|
+
return await messageExcerpts(text, scope, branch => this.gitStates.pullRequestBase(scope, branch));
|
|
3387
|
+
}
|
|
3388
|
+
async appendExcerpts(record, messageId, text) {
|
|
3389
|
+
const excerpts = await this.diffExcerpts(record.id, text);
|
|
3390
|
+
if (this.sessions.get(record.id) === record)
|
|
3391
|
+
record.log.append({ type: "diff_excerpts", messageId, excerpts });
|
|
3392
|
+
}
|
|
2619
3393
|
onBackendEvent(sessionId, event) {
|
|
2620
3394
|
const record = this.sessions.get(sessionId);
|
|
2621
3395
|
if (!record || record.lifecycle === "ended" || record.lifecycle === "settled")
|
|
@@ -2637,6 +3411,10 @@ export class SessionHost {
|
|
|
2637
3411
|
if (event.type === "turn_started" || (event.type === "permission" && event.state === "asked")) {
|
|
2638
3412
|
record.permissionActivityVersion = (record.permissionActivityVersion ?? 0) + 1;
|
|
2639
3413
|
}
|
|
3414
|
+
if (event.type === "turn_started" && record.rewindTo !== undefined) {
|
|
3415
|
+
record.rewindTo = undefined;
|
|
3416
|
+
this.persist(record);
|
|
3417
|
+
}
|
|
2640
3418
|
const before = this.activityOf(record);
|
|
2641
3419
|
const permissionWasOpen = event.type === "permission" && record.openPermissionAttention.has(event.callId);
|
|
2642
3420
|
const enquiryWasOpen = event.type === "enquiry" && record.openEnquiryAttention.has(event.askId);
|
|
@@ -2647,6 +3425,8 @@ export class SessionHost {
|
|
|
2647
3425
|
const preview = event.text.replace(/\s+/g, " ").trim();
|
|
2648
3426
|
record.outputPreview = preview ? preview.slice(0, 500) : undefined;
|
|
2649
3427
|
}
|
|
3428
|
+
if (event.type === "message" && event.final && hasDiffReference(event.text))
|
|
3429
|
+
void this.appendExcerpts(record, event.id, event.text);
|
|
2650
3430
|
let inputAttention;
|
|
2651
3431
|
if (event.type === "permission" && event.state === "asked" && !permissionWasOpen) {
|
|
2652
3432
|
inputAttention = this.markAttention(record, "Input needed", `backend:${record.backendEpoch}:permission:${event.callId}`, logged.at);
|
|
@@ -2669,8 +3449,10 @@ export class SessionHost {
|
|
|
2669
3449
|
void this.workflowOwner?.stop(sessionId).catch(() => { });
|
|
2670
3450
|
// Kept current so a Revive can hand the running total back to the next Backend Session, which
|
|
2671
3451
|
// counts only its own run.
|
|
2672
|
-
if (event.type === "context_usage" && event.spend)
|
|
3452
|
+
if (event.type === "context_usage" && event.spend) {
|
|
2673
3453
|
record.spend = event.spend;
|
|
3454
|
+
this.recordSpend("session", sessionId, this.spendScope(record), event.spend);
|
|
3455
|
+
}
|
|
2674
3456
|
/*
|
|
2675
3457
|
* Ordinarily redundant — `dispatch` and `compact` both set this before the adapter acknowledges,
|
|
2676
3458
|
* for the race the field's own comment describes. It matters for the turn nobody asked for: a
|
|
@@ -2683,6 +3465,8 @@ export class SessionHost {
|
|
|
2683
3465
|
record.turnGeneration = (record.turnGeneration ?? 0) + 1;
|
|
2684
3466
|
record.turnInFlight = true;
|
|
2685
3467
|
}
|
|
3468
|
+
if (event.type === "tool_ended" && record.turnInFlight)
|
|
3469
|
+
this.gitStates.touch(record.scope);
|
|
2686
3470
|
if (event.type === "turn_ended") {
|
|
2687
3471
|
record.turnGeneration = (record.turnGeneration ?? 0) + 1;
|
|
2688
3472
|
this.workflowOwner?.rearmInput?.(sessionId);
|
|
@@ -2865,6 +3649,7 @@ export class SessionHost {
|
|
|
2865
3649
|
return;
|
|
2866
3650
|
const meta = {
|
|
2867
3651
|
id: record.id,
|
|
3652
|
+
...(record.scheduledOccurrenceId ? { scheduledOccurrenceId: record.scheduledOccurrenceId } : {}),
|
|
2868
3653
|
scope: record.scope,
|
|
2869
3654
|
backend: record.backendName,
|
|
2870
3655
|
title: record.title,
|
|
@@ -2884,11 +3669,14 @@ export class SessionHost {
|
|
|
2884
3669
|
readAttentionVersion: record.readAttentionVersion,
|
|
2885
3670
|
mcpConnectionIds: record.mcpConnectionIds ?? [],
|
|
2886
3671
|
...(record.resumeToken === undefined ? {} : { resumeToken: record.resumeToken }),
|
|
3672
|
+
...(record.imported === undefined ? {} : { imported: record.imported }),
|
|
3673
|
+
...(record.rewindTo === undefined ? {} : { rewindTo: record.rewindTo }),
|
|
2887
3674
|
...(record.modelId === undefined ? {} : { modelId: record.modelId }),
|
|
2888
3675
|
...(record.effort === undefined ? {} : { effort: record.effort }),
|
|
2889
3676
|
permissionMode: record.permissionMode,
|
|
2890
3677
|
...(record.initialEffortUnconfirmed ? { initialEffortUnconfirmed: true } : {}),
|
|
2891
3678
|
...(record.worktree === undefined ? {} : { worktree: record.worktree }),
|
|
3679
|
+
...(record.readOnly ? { readOnly: true } : {}),
|
|
2892
3680
|
};
|
|
2893
3681
|
this.store.writeMeta(meta);
|
|
2894
3682
|
}
|
|
@@ -2902,6 +3690,9 @@ export function suggestedScope(scope, worktreesRoot) {
|
|
|
2902
3690
|
const candidate = join(worktreesRoot, scope.slice(at + marker.length));
|
|
2903
3691
|
return candidate !== scope && existsSync(candidate) ? candidate : undefined;
|
|
2904
3692
|
}
|
|
3693
|
+
function userMessage(entries, id) {
|
|
3694
|
+
return entries.find(({ event }) => event.type === "user_message" && event.id === id);
|
|
3695
|
+
}
|
|
2905
3696
|
/** The turn still open at the end of these entries, if any. */
|
|
2906
3697
|
function openTurnId(entries) {
|
|
2907
3698
|
let openTurn;
|
|
@@ -3095,12 +3886,18 @@ function openSubagents(entries) {
|
|
|
3095
3886
|
const event = entry.event;
|
|
3096
3887
|
if (event.type !== "subagent")
|
|
3097
3888
|
continue;
|
|
3098
|
-
if (event.state === "running" || event.state === "waiting")
|
|
3099
|
-
open.set(event.subagentId,
|
|
3889
|
+
if (event.state === "running" || event.state === "waiting") {
|
|
3890
|
+
open.set(event.subagentId, {
|
|
3891
|
+
name: event.name,
|
|
3892
|
+
...(event.model === undefined ? {} : { model: event.model }),
|
|
3893
|
+
...(event.effort === undefined ? {} : { effort: event.effort }),
|
|
3894
|
+
...(event.producer === undefined ? {} : { producer: event.producer }),
|
|
3895
|
+
});
|
|
3896
|
+
}
|
|
3100
3897
|
else
|
|
3101
3898
|
open.delete(event.subagentId);
|
|
3102
3899
|
}
|
|
3103
|
-
return [...open].map(([subagentId,
|
|
3900
|
+
return [...open].map(([subagentId, brief]) => ({ subagentId, ...brief }));
|
|
3104
3901
|
}
|
|
3105
3902
|
/** What the transcript last reported this Agent Session had spent, across every Backend Session. */
|
|
3106
3903
|
function spendFrom(entries) {
|
|
@@ -3109,9 +3906,28 @@ function spendFrom(entries) {
|
|
|
3109
3906
|
const event = entry.event;
|
|
3110
3907
|
if (event.type === "context_usage" && event.spend)
|
|
3111
3908
|
spend = event.spend;
|
|
3909
|
+
if (event.type === "forked")
|
|
3910
|
+
spend = undefined;
|
|
3112
3911
|
}
|
|
3113
3912
|
return spend;
|
|
3114
3913
|
}
|
|
3914
|
+
/**
|
|
3915
|
+
* The Capabilities an imported Agent Session opens with: none (ADR 0047).
|
|
3916
|
+
*
|
|
3917
|
+
* `create` refuses to return an Agent Session without confirmed models, so an empty model list can
|
|
3918
|
+
* only mean that no Backend Session has served this one yet — which is exactly what `reviveOnce`
|
|
3919
|
+
* checks for. Claiming the Capabilities of whatever the adapter would report today instead would put
|
|
3920
|
+
* a guess into an append-only transcript.
|
|
3921
|
+
*/
|
|
3922
|
+
const IMPORTED_CAPABILITIES = {
|
|
3923
|
+
providers: [],
|
|
3924
|
+
models: [],
|
|
3925
|
+
compaction: false,
|
|
3926
|
+
fork: false,
|
|
3927
|
+
subagents: false,
|
|
3928
|
+
enquiries: false,
|
|
3929
|
+
permissions: false,
|
|
3930
|
+
};
|
|
3115
3931
|
function capabilitiesFrom(entries) {
|
|
3116
3932
|
let capabilities;
|
|
3117
3933
|
for (const entry of entries) {
|
|
@@ -3137,6 +3953,11 @@ function firstLine(text) {
|
|
|
3137
3953
|
function errorMessage(error) {
|
|
3138
3954
|
return error instanceof Error ? error.message : String(error);
|
|
3139
3955
|
}
|
|
3956
|
+
const READ_ONLY_REFUSED = new Set([
|
|
3957
|
+
"switch_branch", "pull_branch", "change_pull_request", "comment_pull_request", "submit_pull_request_review", "resolve_pull_request_thread",
|
|
3958
|
+
"edit_pull_request", "set_pull_request_draft", "rerun_pull_request_checks", "prepare_stack", "change_stack",
|
|
3959
|
+
"assist_stack", "commit", "push", "create_pull_request", "start_tour",
|
|
3960
|
+
]);
|
|
3140
3961
|
function scopeKey(scope) {
|
|
3141
3962
|
try {
|
|
3142
3963
|
return realpathSync(scope);
|