@nathanstephenson/flow 0.1.10-beta.3 → 0.1.10-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +11 -3
  2. package/build/backend-worker-chunks/{chunk-LO7O6NAM.mjs → chunk-JOI2POLP.mjs} +1 -1
  3. package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
  4. package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
  5. package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
  6. package/build/backend-worker-chunks/claude-GY27HBAY.mjs +35739 -0
  7. package/build/backend-worker-chunks/{pi-QNU2YE4G.mjs → pi-JV6MWPW7.mjs} +1891 -35
  8. package/build/backend-worker.mjs +25 -126
  9. package/build/workflow-runtime.cjs +12 -12
  10. package/dist/backend/claude/index.js +69 -11
  11. package/dist/backend/claude/subagents.js +11 -0
  12. package/dist/backend/claude/workflow-parent.js +1 -1
  13. package/dist/backend/fake/index.js +8 -2
  14. package/dist/backend/pi/cache-warming.js +8 -0
  15. package/dist/backend/pi/canonical-json.js +120 -0
  16. package/dist/backend/pi/compaction-model.js +3 -2
  17. package/dist/backend/pi/host-auth.js +258 -0
  18. package/dist/backend/pi/index.js +37 -12
  19. package/dist/backend/pi/model-auth.js +159 -0
  20. package/dist/backend/pi/model-catalog.js +120 -0
  21. package/dist/backend/pi/model-config.js +5 -0
  22. package/dist/backend/pi/model-selection.js +32 -0
  23. package/dist/backend/pi/work.js +9 -1
  24. package/dist/backend/pi/workflow-parent.js +1 -1
  25. package/dist/backend/pi/workflow-subagent.js +4 -3
  26. package/dist/backend/worker/entry.js +13 -1
  27. package/dist/backend/worker/index.js +69 -7
  28. package/dist/backend/worker/launcher.js +11 -4
  29. package/dist/build-id +1 -1
  30. package/dist/cli/application.js +5 -5
  31. package/dist/cli/bootstrap.js +1 -1
  32. package/dist/cli/host-control.js +1 -1
  33. package/dist/cli/install-guard.js +1 -1
  34. package/dist/cli/main.js +4 -4
  35. package/dist/cli/systemd-update.js +3 -3
  36. package/dist/cli/update.js +6 -6
  37. package/dist/cli/web-update.js +6 -6
  38. package/dist/client/reduce.js +2 -0
  39. package/dist/client/tool-summary.js +26 -15
  40. package/dist/daemon/changes.js +116 -0
  41. package/dist/daemon/commit.js +84 -0
  42. package/dist/daemon/config-store.js +3 -3
  43. package/dist/daemon/git-state.js +197 -0
  44. package/dist/daemon/github.js +54 -0
  45. package/dist/daemon/host-control-routes.js +1 -1
  46. package/dist/daemon/host.js +147 -78
  47. package/dist/daemon/log.js +3 -0
  48. package/dist/daemon/mcp-auth.js +1 -1
  49. package/dist/daemon/models.js +2 -2
  50. package/dist/daemon/pi-model-cache.js +44 -0
  51. package/dist/daemon/pull-request.js +156 -129
  52. package/dist/daemon/push.js +43 -0
  53. package/dist/daemon/repository.js +106 -0
  54. package/dist/daemon/runtime.js +27 -20
  55. package/dist/daemon/secret-store.js +1 -1
  56. package/dist/daemon/server.js +11 -10
  57. package/dist/daemon/stack-metadata.js +12 -5
  58. package/dist/daemon/stack.js +127 -656
  59. package/dist/daemon/summariser.js +19 -8
  60. package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
  61. package/dist/daemon/workflow-authoring-scope.js +1 -1
  62. package/dist/daemon/workflow-builder-files.js +2 -2
  63. package/dist/daemon/workflow-builder-routes.js +2 -2
  64. package/dist/daemon/workflow-builder.js +5 -5
  65. package/dist/daemon/workflow-environment.js +5 -5
  66. package/dist/daemon/workflow-execution-launch.js +5 -5
  67. package/dist/daemon/workflow-execution-resources.js +3 -3
  68. package/dist/daemon/workflow-execution-routes.js +3 -3
  69. package/dist/daemon/workflow-execution-values.js +5 -5
  70. package/dist/daemon/workflow-executions.js +19 -19
  71. package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
  72. package/dist/daemon/workflow-mcp-authoring.js +4 -4
  73. package/dist/daemon/workflow-mcp.js +1 -1
  74. package/dist/daemon/workflow-routes.js +3 -3
  75. package/dist/daemon/workflow-schedule-driver.js +8 -8
  76. package/dist/daemon/workflow-schedule-routes.js +5 -5
  77. package/dist/daemon/workflow-schedules.js +3 -3
  78. package/dist/isolation/filesystem.js +5 -1
  79. package/dist/isolation/sandbox.js +31 -4
  80. package/dist/isolation/toolchain-assets.js +1 -1
  81. package/dist/protocol/stack.js +1 -41
  82. package/dist/workflows/calls.js +2 -2
  83. package/dist/workflows/executors.js +3 -3
  84. package/dist/workflows/graph.js +6 -6
  85. package/dist/workflows/invocations.js +1 -1
  86. package/dist/workflows/mcp.js +1 -1
  87. package/dist/workflows/records.js +6 -6
  88. package/dist/workflows/recovery.js +2 -2
  89. package/dist/workflows/runtime-settings.js +1 -1
  90. package/dist/workflows/runtime.js +2 -2
  91. package/dist/workflows/schedule-store.js +2 -2
  92. package/dist/workflows/scheduler.js +9 -9
  93. package/dist/workflows/schema.js +1 -1
  94. package/dist/workflows/store.js +3 -3
  95. package/package.json +9 -6
  96. package/web/dist/assets/index-BqZ_iUmY.css +2 -0
  97. package/web/dist/assets/index-CxdSb7k0.js +51 -0
  98. package/web/dist/assets/{settings-mcp-Vf_fCXyE.js → settings-mcp-BwOPXAfH.js} +1 -1
  99. package/web/dist/assets/settings-workflows-DocTa31_.js +23 -0
  100. package/web/dist/assets/{switch-DIogWclb.js → switch-B00FEUA7.js} +1 -1
  101. package/web/dist/assets/{workflows-Dobqzjg-.js → workflows-DJqUuGyg.js} +41 -41
  102. package/web/dist/assets/{workflows-pane-KB-Q76KZ.js → workflows-pane-oM1fO_BC.js} +1 -1
  103. package/web/dist/index.html +4 -4
  104. package/build/backend-worker-chunks/claude-6L5KCQWJ.mjs +0 -30894
  105. package/dist/daemon/publish.js +0 -289
  106. package/dist/protocol/publish.js +0 -1
  107. package/web/dist/assets/index-BGu3YSP7.css +0 -2
  108. package/web/dist/assets/index-Miy2nveb.js +0 -40
  109. package/web/dist/assets/settings-workflows-DVKxJWQm.js +0 -23
@@ -1,14 +1,17 @@
1
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";
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';
5
5
  import { randomUUID } from "node:crypto";
6
6
  import { copyFileSync, existsSync, mkdirSync, realpathSync } from "node:fs";
7
7
  import { isAbsolute, join, resolve } from "node:path";
8
8
  import { validateFilesystemScope } from "../isolation/filesystem.js";
9
- import { pullRequest, commentPullRequest, resolvePullRequestThread, pullBranch, changePullRequest } from "./pull-request.js";
10
- import { stackStatus, actionStackStatus, cleanStack, stackFingerprint, changeStack, stackConflictMessage } from "./stack.js";
11
- import { gitStatus, snapshot, target, branchChanges, canNameBranch, publish } from "./publish.js";
9
+ import { pullRequest, commentPullRequest, resolvePullRequestThread, pullBranch, changePullRequest, createPullRequest, editPullRequest, setPullRequestDraft, rerunPullRequestChecks, checkLog } from "./pull-request.js";
10
+ import { otherWorktreeRebase, stackStatus, stackTitles, cleanStack, stackFingerprint, changeStack, stackConflictMessage } from "./stack.js";
11
+ import { changes, changesText, commitContext, diff } from "./changes.js";
12
+ import { commit } from "./commit.js";
13
+ import { push, pushState } from "./push.js";
14
+ import { GitStates, readStatus } from "./git-state.js";
12
15
  import { resolveDefaultBackend } from "../protocol/settings.js";
13
16
  import { isAttachmentMediaType, mediaTypeOf, MAX_ATTACHMENTS_PER_MESSAGE, MAX_ATTACHMENT_BASE64_BYTES, } from "../protocol/attachments.js";
14
17
  import { deriveStatus, railGroupRank } from "../client/status.js";
@@ -17,11 +20,12 @@ import { deriveStatus, railGroupRank } from "../client/status.js";
17
20
  import { createWorktree, head, isClean, isRepository, removeMergedBranch, removeWorktree, repairWorktree, switchBranch as gitSwitchBranch, } from "./git.js";
18
21
  import { SessionLog } from "./log.js";
19
22
  import { probeModels } from "./models.js";
23
+ import { PiModelProbeCache } from "./pi-model-cache.js";
20
24
  import { ScheduleValidationError } from "../workflows/schedule-errors.js";
21
25
  import { probeSkills } from "./skills.js";
22
26
  import { recordTiming } from "./timings.js";
23
27
  import { SharedSandbox } from "../isolation/shared-sandbox.js";
24
- import { nameInput, summarisePublish, suggestedBranch, SummaryModelSpare } from "./summariser.js";
28
+ import { nameInput, suggestGitText, SummaryModelSpare } from "./summariser.js";
25
29
  /**
26
30
  * A command the Session Host will not carry out in the state the thing is in — a turn in flight, a
27
31
  * Scope that is not a repository, a checkout git itself refused.
@@ -44,6 +48,7 @@ export class SessionHost {
44
48
  backends = new Map();
45
49
  /** Model probes by backend name, held in flight rather than resolved — see `models`. */
46
50
  modelProbes = new Map();
51
+ piModelProbeCache = new PiModelProbeCache();
47
52
  /** One warm Skills session per Backend Adapter, for the last Scope asked — see `skillsFor` (ADR 0035). */
48
53
  skillSessions = new Map();
49
54
  /**
@@ -63,8 +68,8 @@ export class SessionHost {
63
68
  summarySpare = new SummaryModelSpare();
64
69
  stackReviews = new Map();
65
70
  gitOperations = new Set();
71
+ gitStates = new GitStates();
66
72
  closingScopes = new Set();
67
- publishReviews = new Map();
68
73
  refuseGitOperation(scope) {
69
74
  if (this.gitOperations.has(scopeKey(scope)))
70
75
  throw new CommandRefused("A Git operation is in progress in this Scope. Wait for it to finish.");
@@ -101,6 +106,7 @@ export class SessionHost {
101
106
  }
102
107
  finally {
103
108
  this.gitOperations.delete(key);
109
+ void this.gitStates.refresh(scope);
104
110
  }
105
111
  }
106
112
  async prepareStack(sessionId, action) {
@@ -110,9 +116,9 @@ export class SessionHost {
110
116
  return this.withGitOperation(record.scope, async () => {
111
117
  this.stackReviews.delete(sessionId);
112
118
  await cleanStack(record.scope);
113
- const status = await actionStackStatus(record.scope);
119
+ const status = await stackStatus(record.scope);
114
120
  if (!status.view)
115
- throw new Error(status.problem ?? "No stack found.");
121
+ throw new Error(status.notice ?? "This branch is not in a stack.");
116
122
  const review = { token: randomUUID(), action, view: status.view };
117
123
  this.stackReviews.set(sessionId, { review, fingerprint: await stackFingerprint(record.scope, status.view, action === "sync"), expires: Date.now() + 15 * 60_000 });
118
124
  return review;
@@ -127,19 +133,18 @@ export class SessionHost {
127
133
  if (!saved || saved.expires < Date.now() || saved.review.token !== input.token || saved.review.action !== input.action)
128
134
  throw new Error("This Stack review expired. Review again.");
129
135
  await cleanStack(record.scope);
130
- const status = await actionStackStatus(record.scope);
136
+ const status = await stackStatus(record.scope);
131
137
  if (!status.view || await stackFingerprint(record.scope, status.view, input.action === "sync") !== saved.fingerprint)
132
138
  throw new Error("The reviewed stack changed. Review again.");
133
139
  }
134
140
  try {
135
- return await changeStack(record.scope, input);
141
+ return await this.afterPullRequestWrite(record.scope, changeStack(record.scope, input));
136
142
  }
137
143
  finally {
138
144
  for (const other of this.sessions.values()) {
139
145
  if (scopeKey(other.scope) !== scopeKey(record.scope))
140
146
  continue;
141
147
  this.stackReviews.delete(other.id);
142
- this.publishReviews.delete(other.id);
143
148
  await this.refreshBranch(other);
144
149
  other.pendingBranchNote = "[Flow] A Stack operation was attempted in this Scope. Re-read the branch and changed files before relying on earlier reads.";
145
150
  }
@@ -149,67 +154,91 @@ export class SessionHost {
149
154
  async assistStack(sessionId) {
150
155
  const record = this.record(sessionId);
151
156
  await this.withGitOperation(record.scope, async () => {
152
- const status = await actionStackStatus(record.scope);
157
+ const status = await stackStatus(record.scope);
153
158
  if (!status.rebasing)
154
- throw new Error("No Stack rebase is in progress. Use Rebase first after a Sync conflict.");
159
+ throw new Error(status.notice === otherWorktreeRebase ? otherWorktreeRebase : "No Stack rebase is in progress. Use Rebase first after a Sync conflict.");
155
160
  });
156
161
  await this.send(sessionId, stackConflictMessage, "now");
157
162
  }
158
- async gitStatus(sessionId) {
159
- return gitStatus(this.record(sessionId).scope);
163
+ pollGitState(forced) {
164
+ return this.gitStates.poll([...this.sessions.values()].map(record => ({ scope: record.scope, lifecycle: record.lifecycle, watched: record.log.watched })), forced);
160
165
  }
161
- async preparePublish(sessionId) {
162
- const record = this.record(sessionId);
163
- return this.withGitOperation(record.scope, async () => {
164
- this.publishReviews.delete(sessionId);
165
- for (const [id, review] of this.publishReviews)
166
- if (review.expires < Date.now())
167
- this.publishReviews.delete(id);
168
- const { input: changes, ...reviewed } = await snapshot(record.scope);
169
- const destination = await target(record.scope, reviewed.branch);
170
- const committed = await branchChanges(record.scope, destination);
171
- if (reviewed.files.length === 0 && committed.commits.length === 0 && !destination.pr)
172
- throw new CommandRefused("There are no changes to publish.");
173
- let text = { commitMessage: "", title: destination.pr?.title ?? "", body: "" };
174
- let warning;
175
- const model = this.summaryModel?.(record.backendName);
176
- try {
177
- if (!model)
178
- throw new Error("No Summary Model is configured. Choose one in Settings, or enter publish text below.");
179
- text = await summarisePublish({ backend: this.backendFor(model.backend), modelId: model.modelId, text: `${changes}\nCommitted branch changes:\n${committed.input}` });
180
- }
181
- catch (error) {
182
- warning = `Enter publish text manually. ${error instanceof Error ? error.message : String(error)}`;
183
- }
184
- const suggestion = await canNameBranch(record.scope, reviewed.branch, destination)
185
- ? text.suggestedBranch ?? suggestedBranch((record.titleSource !== "scope" ? record.title : "") || text.commitMessage || committed.commits[0]?.replace(/^[a-f0-9]+ /, "") || record.title)
186
- : undefined;
187
- delete text.suggestedBranch;
188
- const token = randomUUID();
189
- this.publishReviews.set(sessionId, { token, expires: Date.now() + 15 * 60_000, snapshot: reviewed, target: destination });
190
- 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 } : {}) };
166
+ async afterPullRequestWrite(scope, write) {
167
+ try {
168
+ return await write;
169
+ }
170
+ finally {
171
+ await this.pollGitState(scope);
172
+ }
173
+ }
174
+ async readGit(read) {
175
+ try {
176
+ return await read();
177
+ }
178
+ catch (error) {
179
+ throw new CommandRefused(error instanceof Error ? error.message : String(error));
180
+ }
181
+ }
182
+ readStack(sessionId) {
183
+ const scope = this.gitScope(sessionId);
184
+ return this.readGit(async () => {
185
+ const status = await stackStatus(scope);
186
+ if (status.view && !await stackTitles(scope, status.view))
187
+ status.notice = "Pull request titles could not be read. Copy uses the links.";
188
+ return status;
191
189
  });
192
190
  }
193
- async publish(sessionId, input) {
191
+ gitScope(sessionId) {
192
+ const scope = this.record(sessionId).scope;
193
+ if (!isRepository(scope))
194
+ throw new CommandRefused("This Scope is not a Git repository.");
195
+ return scope;
196
+ }
197
+ async readChanges(command) {
198
+ const scope = this.gitScope(command.sessionId);
199
+ const base = (branch) => this.gitStates.pullRequestBase(scope, branch);
200
+ return this.readGit(async () => {
201
+ if (command.type === "git_diff")
202
+ return await diff(scope, command.view, command.path, base);
203
+ if (command.view === "branch")
204
+ return await changes(scope, command.view, base);
205
+ const read = await readStatus(scope);
206
+ return { files: read.files, commits: [], fingerprint: read.fingerprint, ...await commitContext(scope, read.local.branch, branch => this.gitStates.hasPullRequest(scope, branch)) };
207
+ });
208
+ }
209
+ async commit(sessionId, input) {
210
+ this.gitScope(sessionId);
194
211
  const record = this.record(sessionId);
195
212
  return this.withGitOperation(record.scope, async () => {
196
- const review = this.publishReviews.get(sessionId);
197
- if (!review || review.token !== input.token || review.expires < Date.now())
198
- throw new CommandRefused("This Publish review expired. Open Publish again.");
199
- this.publishReviews.delete(sessionId);
213
+ const before = await head(record.scope);
200
214
  try {
201
- return await publish(record.scope, review.snapshot, review.target, input);
215
+ return await commit(record.scope, input);
202
216
  }
203
217
  finally {
204
- for (const other of this.sessions.values()) {
205
- if (scopeKey(other.scope) !== scopeKey(record.scope))
206
- continue;
207
- await this.refreshBranch(other);
208
- other.pendingBranchNote = "[Flow] Git publishing was attempted in this Scope. Re-read the branch and changed files before relying on earlier reads.";
218
+ const after = await head(record.scope);
219
+ if (after.ok && before.ok && after.value.name !== before.value.name) {
220
+ for (const other of this.sessions.values()) {
221
+ if (scopeKey(other.scope) !== scopeKey(record.scope))
222
+ continue;
223
+ await this.refreshBranch(other);
224
+ 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.`;
225
+ }
209
226
  }
210
227
  }
211
228
  });
212
229
  }
230
+ async suggestGitText(sessionId, kind, paths) {
231
+ const record = this.record(sessionId);
232
+ if (!["commit", "pull_request", "branch"].includes(kind) || (paths !== undefined && (!Array.isArray(paths) || paths.some(path => typeof path !== "string"))))
233
+ throw new CommandRefused("Invalid suggestion request.");
234
+ const model = this.summaryModel?.(record.backendName);
235
+ if (!model)
236
+ throw new CommandRefused("No Summary Model is configured. Choose one in Settings, or enter the text.");
237
+ return this.readGit(async () => {
238
+ const text = await changesText(record.scope, kind === "pull_request" ? "branch" : "uncommitted", paths, branch => this.gitStates.pullRequestBase(record.scope, branch));
239
+ return await suggestGitText({ backend: this.backendFor(model.backend), modelId: model.modelId, text, kind });
240
+ });
241
+ }
213
242
  store;
214
243
  retention;
215
244
  standingAuthorisations;
@@ -308,7 +337,7 @@ export class SessionHost {
308
337
  const held = this.modelProbes.get(backend.name);
309
338
  if (held)
310
339
  return held;
311
- const probe = this.timed("models", backend, false, (timed) => probeModels(timed, scope, false, (held) => this.holdSkillSession(backend.name, held, false)));
340
+ 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));
312
341
  this.modelProbes.set(backend.name, probe);
313
342
  return probe;
314
343
  });
@@ -469,6 +498,7 @@ export class SessionHost {
469
498
  // lifting an Ended row back out of Filed away.
470
499
  const input = record.lifecycle === "live" ? newestAt(parentInput, workflowInput) : undefined;
471
500
  const outcome = record.latestOutcome;
501
+ const git = this.gitStates.summary(record.scope);
472
502
  const unread = outcome !== undefined && outcome.version > record.readAttentionVersion;
473
503
  const attention = input
474
504
  ? {
@@ -504,6 +534,7 @@ export class SessionHost {
504
534
  lastSeq: record.log.lastSeq,
505
535
  ...(record.capabilities ? { capabilities: record.capabilities } : {}),
506
536
  ...(record.branch ? { branch: record.branch } : {}),
537
+ ...(git ? { git } : {}),
507
538
  ...(record.worktree ? { worktree: true } : {}),
508
539
  ...(record.session || existsSync(record.scope) ? {} : {
509
540
  scopeMissing: true,
@@ -1551,7 +1582,7 @@ export class SessionHost {
1551
1582
  if (!isRepository(record.scope))
1552
1583
  return;
1553
1584
  const generation = (record.branchGeneration += 1);
1554
- const found = await head(record.scope);
1585
+ const [found] = await Promise.all([head(record.scope), this.gitStates.refresh(record.scope)]);
1555
1586
  // A repository git cannot answer about is left as it was: this runs off the critical path, and
1556
1587
  // there is no reader to tell.
1557
1588
  if (!found.ok)
@@ -1979,7 +2010,6 @@ export class SessionHost {
1979
2010
  await this.releaseWorktree(record);
1980
2011
  record.log.closeSubscribers();
1981
2012
  this.sessions.delete(record.id);
1982
- this.publishReviews.delete(record.id);
1983
2013
  this.store?.deleteSession(record.id);
1984
2014
  reaped.push(record.id);
1985
2015
  }
@@ -2145,6 +2175,10 @@ export class SessionHost {
2145
2175
  this.persist(record);
2146
2176
  }
2147
2177
  await this.shared?.close().catch((error) => console.error(`Shared sandbox removal failed: ${error.message}`));
2178
+ const stopped = await Promise.allSettled([...this.backends.values()].map(async (backend) => backend.shutdown?.()));
2179
+ const failures = stopped.filter(result => result.status === "rejected").map(result => result.reason);
2180
+ if (failures.length)
2181
+ throw new AggregateError(failures, "Backend Adapter shutdown failed");
2148
2182
  }
2149
2183
  async execute(command) {
2150
2184
  switch (command.type) {
@@ -2185,27 +2219,55 @@ export class SessionHost {
2185
2219
  case "pull_branch":
2186
2220
  return await this.withGitOperation(this.record(command.sessionId).scope, () => pullBranch(this.record(command.sessionId).scope, command.branch));
2187
2221
  case "change_pull_request":
2188
- return await this.withGitOperation(this.record(command.sessionId).scope, () => changePullRequest(this.record(command.sessionId).scope, command.action, command.input));
2189
- case "pull_request":
2190
- return await pullRequest(this.record(command.sessionId).scope);
2222
+ return await this.withGitOperation(this.record(command.sessionId).scope, () => this.afterPullRequestWrite(this.record(command.sessionId).scope, changePullRequest(this.record(command.sessionId).scope, command.action, command.input)));
2223
+ case "pull_request": {
2224
+ const scope = this.record(command.sessionId).scope;
2225
+ return await this.readGit(() => pullRequest(scope, this.gitStates.pullRequestRef(scope)));
2226
+ }
2191
2227
  case "comment_pull_request":
2192
- return await commentPullRequest(this.record(command.sessionId).scope, command.input);
2228
+ return await this.afterPullRequestWrite(this.record(command.sessionId).scope, commentPullRequest(this.record(command.sessionId).scope, command.input));
2193
2229
  case "resolve_pull_request_thread":
2194
- return await resolvePullRequestThread(this.record(command.sessionId).scope, command.input);
2230
+ return await this.afterPullRequestWrite(this.record(command.sessionId).scope, resolvePullRequestThread(this.record(command.sessionId).scope, command.input));
2231
+ case "edit_pull_request":
2232
+ return await this.afterPullRequestWrite(this.record(command.sessionId).scope, editPullRequest(this.record(command.sessionId).scope, command.input));
2233
+ case "set_pull_request_draft":
2234
+ return await this.afterPullRequestWrite(this.record(command.sessionId).scope, setPullRequestDraft(this.record(command.sessionId).scope, command.input));
2235
+ case "rerun_pull_request_checks":
2236
+ return await this.afterPullRequestWrite(this.record(command.sessionId).scope, rerunPullRequestChecks(this.record(command.sessionId).scope, command.input));
2237
+ case "pull_request_check_log":
2238
+ return await checkLog(this.record(command.sessionId).scope, command.pr, command.jobId);
2195
2239
  case "stack_status":
2196
- return await this.withGitOperation(this.record(command.sessionId).scope, () => stackStatus(this.record(command.sessionId).scope));
2240
+ return await this.readStack(command.sessionId);
2197
2241
  case "prepare_stack":
2198
2242
  return await this.prepareStack(command.sessionId, command.action);
2199
2243
  case "change_stack":
2200
2244
  return await this.changeStack(command.sessionId, command.input);
2201
2245
  case "assist_stack":
2202
2246
  return await this.assistStack(command.sessionId);
2203
- case "git_status":
2204
- return await this.gitStatus(command.sessionId);
2205
- case "prepare_publish":
2206
- return await this.preparePublish(command.sessionId);
2207
- case "publish":
2208
- return await this.publish(command.sessionId, command.input);
2247
+ case "refresh_git": {
2248
+ const scope = this.record(command.sessionId).scope;
2249
+ if (!isRepository(scope)) {
2250
+ await this.gitStates.refresh(scope);
2251
+ return { repository: false };
2252
+ }
2253
+ await Promise.all([...this.sessions.values()].filter(other => scopeKey(other.scope) === scopeKey(scope)).map(other => this.refreshBranch(other)));
2254
+ if (command.pullRequest === true)
2255
+ await this.pollGitState(scope);
2256
+ return { repository: true };
2257
+ }
2258
+ case "git_changes":
2259
+ case "git_diff":
2260
+ return await this.readChanges(command);
2261
+ case "commit":
2262
+ return await this.commit(command.sessionId, { fingerprint: command.fingerprint, paths: command.paths, message: command.message, ...(command.branch === undefined ? {} : { branch: command.branch }) });
2263
+ case "push_state":
2264
+ return await this.readGit(() => pushState(this.gitScope(command.sessionId)));
2265
+ case "push":
2266
+ 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 }) })));
2267
+ case "create_pull_request":
2268
+ 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 })));
2269
+ case "suggest_git_text":
2270
+ return await this.suggestGitText(command.sessionId, command.kind, command.paths);
2209
2271
  case "switch_branch":
2210
2272
  return await this.switchBranch(command.sessionId, command.branch);
2211
2273
  case "switch_scope_branch":
@@ -2284,10 +2346,10 @@ export class SessionHost {
2284
2346
  scheduledMcp(scope, ids, mode) {
2285
2347
  const connections = this.scheduledConnections(ids);
2286
2348
  const oauth = this.mcpAuth ? (connection) => this.mcpAuth.provider(connection) : undefined;
2287
- return import("../backend/mcp.js").then(({ McpSession }) => new McpSession(connections, scope, oauth, true, this.resolveSecret, undefined, this.filesystemStateRoot(), mode));
2349
+ return import('../backend/mcp.js').then(({ McpSession }) => new McpSession(connections, scope, oauth, true, this.resolveSecret, undefined, this.filesystemStateRoot(), mode));
2288
2350
  }
2289
2351
  scheduledSandboxMcp(scope, ids) {
2290
- 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));
2352
+ 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));
2291
2353
  }
2292
2354
  /** Include an SDK-supplied owning root in every local execution's filesystem policy. */
2293
2355
  filesystemStateRoot() { return this.store?.root; }
@@ -2314,7 +2376,7 @@ export class SessionHost {
2314
2376
  const connection = this.workflowMcpConnections(id).find(connection => connection.id === connectionId);
2315
2377
  if (!connection)
2316
2378
  throw new Error('MCP connection is removed or disabled for this Agent Session. Enable it in the Agent Session settings and reconfigure the step.');
2317
- const { McpSession } = await import("../backend/mcp.js");
2379
+ const { McpSession } = await import('../backend/mcp.js');
2318
2380
  const scope = this.workflowSession(id).scope;
2319
2381
  signal?.throwIfAborted();
2320
2382
  return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode);
@@ -2324,7 +2386,7 @@ export class SessionHost {
2324
2386
  const connection = (this.mcpConnections?.() ?? []).find(connection => connection.id === connectionId);
2325
2387
  if (!connection)
2326
2388
  throw new Error('MCP connection removed. Refresh the workflow editor.');
2327
- const { McpSession } = await import("../backend/mcp.js");
2389
+ const { McpSession } = await import('../backend/mcp.js');
2328
2390
  return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode, expectedScopeIdentity);
2329
2391
  }
2330
2392
  mcpStatus(id) {
@@ -2877,6 +2939,8 @@ export class SessionHost {
2877
2939
  record.turnGeneration = (record.turnGeneration ?? 0) + 1;
2878
2940
  record.turnInFlight = true;
2879
2941
  }
2942
+ if (event.type === "tool_ended" && record.turnInFlight)
2943
+ this.gitStates.touch(record.scope);
2880
2944
  if (event.type === "turn_ended") {
2881
2945
  record.turnGeneration = (record.turnGeneration ?? 0) + 1;
2882
2946
  this.workflowOwner?.rearmInput?.(sessionId);
@@ -3295,7 +3359,12 @@ function openSubagents(entries) {
3295
3359
  if (event.type !== "subagent")
3296
3360
  continue;
3297
3361
  if (event.state === "running" || event.state === "waiting") {
3298
- open.set(event.subagentId, { name: event.name, ...(event.producer === undefined ? {} : { producer: event.producer }) });
3362
+ open.set(event.subagentId, {
3363
+ name: event.name,
3364
+ ...(event.model === undefined ? {} : { model: event.model }),
3365
+ ...(event.effort === undefined ? {} : { effort: event.effort }),
3366
+ ...(event.producer === undefined ? {} : { producer: event.producer }),
3367
+ });
3299
3368
  }
3300
3369
  else
3301
3370
  open.delete(event.subagentId);
@@ -92,6 +92,9 @@ export class SessionLog {
92
92
  const start = Math.max(0, end - limit);
93
93
  return { seq: this.lastSeq, entries: this.indexedRange(view.entries, start, end), start, total };
94
94
  }
95
+ get watched() {
96
+ return this.listeners.size > 0 || this.presentationListeners.size > 0;
97
+ }
95
98
  subscribePresentation(listener) {
96
99
  this.presentationView();
97
100
  this.presentationListeners.add(listener);
@@ -1,4 +1,4 @@
1
- import { credentialKey } from "./credential-redaction.js";
1
+ import { credentialKey } from './credential-redaction.js';
2
2
  import { randomBytes, createHash } from "node:crypto";
3
3
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
4
4
  import { join } from "node:path";
@@ -29,7 +29,7 @@ const PROBE_TIMEOUT_MS = 45_000;
29
29
  * Never throws: a backend that cannot answer reports a `problem`, and its section of the Settings
30
30
  * offers a text field instead of a list. A refusal here must not make the whole page unreachable.
31
31
  */
32
- export async function probeModels(backend, scope, workflowBuilder = false, keep) {
32
+ export async function probeModels(backend, scope, workflowBuilder = false, keep, refresh = false) {
33
33
  let models = [];
34
34
  let settle;
35
35
  // Claude reports a provisional Capabilities at create and the real list moments later, over
@@ -47,7 +47,7 @@ export async function probeModels(backend, scope, workflowBuilder = false, keep)
47
47
  let session;
48
48
  try {
49
49
  const refuseTool = async () => { throw new Error("Model discovery cannot use workflow builder tools"); };
50
- session = await backend.create({ ...options, ...(workflowBuilder ? { workflowBuilder: {
50
+ session = await backend.create({ ...options, ...(refresh ? { refreshModels: true } : {}), ...(workflowBuilder ? { workflowBuilder: {
51
51
  instructions: "List available models only.", read: refuseTool, list: refuseTool, write: refuseTool,
52
52
  } } : {}) });
53
53
  }
@@ -0,0 +1,44 @@
1
+ import { closeSync, fstatSync, mkdirSync, mkdtempSync, openSync, readSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { workflowBuilderFolder } from '../isolation/shared-sandbox.js';
4
+ export class PiModelProbeCache {
5
+ catalog;
6
+ generation = 0;
7
+ wrap(backend) {
8
+ return { name: backend.name, create: async (options) => {
9
+ const generation = ++this.generation;
10
+ const root = mkdtempSync(join(workflowBuilderFolder(), 'flow-model-probe-'));
11
+ const stateDir = join(root, 'backend');
12
+ const path = join(stateDir, 'models-store.json');
13
+ let session;
14
+ let fd;
15
+ try {
16
+ mkdirSync(stateDir, { mode: 0o700 });
17
+ fd = openSync(path, 'wx+', 0o600);
18
+ writeFileSync(fd, this.catalog ?? '{}');
19
+ session = await backend.create({ ...options, stateDir });
20
+ const stat = fstatSync(fd);
21
+ if (generation === this.generation && stat.nlink === 1 && stat.size <= 16 * 1024 * 1024) {
22
+ const bytes = Buffer.alloc(stat.size);
23
+ const size = readSync(fd, bytes, 0, bytes.length, 0);
24
+ this.catalog = bytes.subarray(0, size);
25
+ }
26
+ const dispose = session.dispose.bind(session);
27
+ session.dispose = async () => {
28
+ await dispose();
29
+ rmSync(root, { recursive: true, force: true });
30
+ };
31
+ return session;
32
+ }
33
+ catch (error) {
34
+ await session?.dispose();
35
+ rmSync(root, { recursive: true, force: true });
36
+ throw error;
37
+ }
38
+ finally {
39
+ if (fd !== undefined)
40
+ closeSync(fd);
41
+ }
42
+ } };
43
+ }
44
+ }