@nathanstephenson/flow 0.1.10-beta.4 → 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 (82) hide show
  1. package/README.md +2 -2
  2. package/build/workflow-runtime.cjs +12 -12
  3. package/dist/backend/claude/workflow-parent.js +1 -1
  4. package/dist/backend/pi/model-auth.js +2 -2
  5. package/dist/backend/pi/workflow-parent.js +1 -1
  6. package/dist/backend/worker/index.js +4 -3
  7. package/dist/backend/worker/launcher.js +11 -4
  8. package/dist/build-id +1 -1
  9. package/dist/cli/application.js +5 -5
  10. package/dist/cli/bootstrap.js +1 -1
  11. package/dist/cli/host-control.js +1 -1
  12. package/dist/cli/install-guard.js +1 -1
  13. package/dist/cli/main.js +4 -4
  14. package/dist/cli/systemd-update.js +3 -3
  15. package/dist/cli/update.js +6 -6
  16. package/dist/cli/web-update.js +6 -6
  17. package/dist/daemon/changes.js +116 -0
  18. package/dist/daemon/commit.js +84 -0
  19. package/dist/daemon/config-store.js +3 -3
  20. package/dist/daemon/git-state.js +197 -0
  21. package/dist/daemon/github.js +54 -0
  22. package/dist/daemon/host-control-routes.js +1 -1
  23. package/dist/daemon/host.js +134 -76
  24. package/dist/daemon/log.js +3 -0
  25. package/dist/daemon/mcp-auth.js +1 -1
  26. package/dist/daemon/pi-model-cache.js +1 -1
  27. package/dist/daemon/pull-request.js +156 -129
  28. package/dist/daemon/push.js +43 -0
  29. package/dist/daemon/repository.js +106 -0
  30. package/dist/daemon/runtime.js +27 -20
  31. package/dist/daemon/secret-store.js +1 -1
  32. package/dist/daemon/server.js +11 -10
  33. package/dist/daemon/stack-metadata.js +12 -5
  34. package/dist/daemon/stack.js +127 -656
  35. package/dist/daemon/summariser.js +19 -8
  36. package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
  37. package/dist/daemon/workflow-authoring-scope.js +1 -1
  38. package/dist/daemon/workflow-builder-files.js +2 -2
  39. package/dist/daemon/workflow-builder-routes.js +2 -2
  40. package/dist/daemon/workflow-builder.js +5 -5
  41. package/dist/daemon/workflow-environment.js +5 -5
  42. package/dist/daemon/workflow-execution-launch.js +5 -5
  43. package/dist/daemon/workflow-execution-resources.js +3 -3
  44. package/dist/daemon/workflow-execution-routes.js +3 -3
  45. package/dist/daemon/workflow-execution-values.js +5 -5
  46. package/dist/daemon/workflow-executions.js +19 -19
  47. package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
  48. package/dist/daemon/workflow-mcp-authoring.js +4 -4
  49. package/dist/daemon/workflow-mcp.js +1 -1
  50. package/dist/daemon/workflow-routes.js +3 -3
  51. package/dist/daemon/workflow-schedule-driver.js +8 -8
  52. package/dist/daemon/workflow-schedule-routes.js +5 -5
  53. package/dist/daemon/workflow-schedules.js +3 -3
  54. package/dist/isolation/toolchain-assets.js +1 -1
  55. package/dist/protocol/stack.js +1 -41
  56. package/dist/workflows/calls.js +2 -2
  57. package/dist/workflows/executors.js +3 -3
  58. package/dist/workflows/graph.js +6 -6
  59. package/dist/workflows/invocations.js +1 -1
  60. package/dist/workflows/mcp.js +1 -1
  61. package/dist/workflows/records.js +6 -6
  62. package/dist/workflows/recovery.js +2 -2
  63. package/dist/workflows/runtime-settings.js +1 -1
  64. package/dist/workflows/runtime.js +2 -2
  65. package/dist/workflows/schedule-store.js +2 -2
  66. package/dist/workflows/scheduler.js +9 -9
  67. package/dist/workflows/schema.js +1 -1
  68. package/dist/workflows/store.js +3 -3
  69. package/package.json +3 -2
  70. package/web/dist/assets/index-BqZ_iUmY.css +2 -0
  71. package/web/dist/assets/index-CxdSb7k0.js +51 -0
  72. package/web/dist/assets/{settings-mcp-bcNKV147.js → settings-mcp-BwOPXAfH.js} +1 -1
  73. package/web/dist/assets/settings-workflows-DocTa31_.js +23 -0
  74. package/web/dist/assets/{switch-DIogWclb.js → switch-B00FEUA7.js} +1 -1
  75. package/web/dist/assets/{workflows-DHG-CIo3.js → workflows-DJqUuGyg.js} +31 -31
  76. package/web/dist/assets/{workflows-pane-9u_hJvgQ.js → workflows-pane-oM1fO_BC.js} +1 -1
  77. package/web/dist/index.html +4 -4
  78. package/dist/daemon/publish.js +0 -289
  79. package/dist/protocol/publish.js +0 -1
  80. package/web/dist/assets/index-BWKZK5HD.css +0 -2
  81. package/web/dist/assets/index-nIc09tKZ.js +0 -40
  82. package/web/dist/assets/settings-workflows-C_TKOhVa.js +0 -23
@@ -0,0 +1,197 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstat } from "node:fs/promises";
3
+ import { resolve } from "node:path";
4
+ import { head, isRepository, run, GIT_READ_TIMEOUT_MS } from "./git.js";
5
+ import { gh } from "./github.js";
6
+ import { localRepository, releaseRepositories, resolvePullRequest, resolveRepository } from "./repository.js";
7
+ const READ_INTERVAL_MS = 3_000;
8
+ const WATCHED_POLL_MS = 30_000;
9
+ const UNWATCHED_POLL_MS = 5 * 60_000;
10
+ const POLL_JITTER_MS = 5_000;
11
+ const pathOffsets = { "1": 8, u: 10, "?": 1 };
12
+ export async function readStatus(scope) {
13
+ const status = await run(scope, ["status", "--porcelain=v2", "--branch", "-z", "--untracked-files=all", "--no-renames"], GIT_READ_TIMEOUT_MS);
14
+ if (!status.ok)
15
+ throw new Error(status.failure.message.includes("ENOENT") ? "Git is missing. Install git on the Session Host." : status.failure.message);
16
+ const records = status.value.split("\0").filter(Boolean);
17
+ const revision = createHash("sha256");
18
+ const fingerprint = createHash("sha256");
19
+ const state = { changed: 0, ahead: 0, behind: 0, upstream: false };
20
+ const files = [];
21
+ for (const record of records) {
22
+ revision.update(`${record}\0`);
23
+ if (!/^# branch\.(head|upstream|ab) /.test(record))
24
+ fingerprint.update(`${record}\0`);
25
+ const counts = /^# branch\.ab \+(\d+) -(\d+)$/.exec(record);
26
+ if (counts)
27
+ Object.assign(state, { upstream: true, ahead: Number(counts[1]), behind: Number(counts[2]) });
28
+ const branch = /^# branch\.head (.+)$/.exec(record)?.[1];
29
+ if (branch && branch !== "(detached)")
30
+ state.branch = branch;
31
+ const oid = /^# branch\.oid ([0-9a-f]+)$/.exec(record)?.[1];
32
+ if (oid)
33
+ state.head = oid;
34
+ const offset = pathOffsets[record[0] ?? ""];
35
+ if (offset === undefined || record[1] !== " ")
36
+ continue;
37
+ const path = record.split(" ").slice(offset).join(" ");
38
+ state.changed += 1;
39
+ files.push({ status: record[0] === "?" ? "??" : record.slice(2, 4).replaceAll(".", " "), path });
40
+ const stat = await lstat(resolve(scope, path)).catch(() => undefined);
41
+ revision.update(`\0${stat?.mtimeMs}\0${stat?.size}`);
42
+ fingerprint.update(`\0${stat?.mtimeMs}\0${stat?.size}`);
43
+ }
44
+ return { local: { revision: revision.digest("hex").slice(0, 16), ...state }, fingerprint: fingerprint.digest("hex"), files };
45
+ }
46
+ export async function readLocal(scope) {
47
+ const read = await readStatus(scope).catch(() => undefined);
48
+ if (!read)
49
+ return undefined;
50
+ const repository = await localRepository(scope, read.local.branch).catch(() => undefined);
51
+ const defaultBranch = repository?.defaultBranches[0];
52
+ return { ...read.local, ...(repository?.github ? { github: true } : {}), ...(defaultBranch ? { defaultBranch } : {}) };
53
+ }
54
+ function due(elapsed, watched) {
55
+ return elapsed >= (watched ? WATCHED_POLL_MS : UNWATCHED_POLL_MS) - POLL_JITTER_MS;
56
+ }
57
+ export class GitStates {
58
+ entries = new Map();
59
+ polledAt = new Map();
60
+ results = new Map();
61
+ bases = new Map();
62
+ refs = new Map();
63
+ targets = new Map();
64
+ github;
65
+ read;
66
+ constructor(github = gh, read = readLocal) {
67
+ this.github = github;
68
+ this.read = read;
69
+ }
70
+ entry(scope) {
71
+ let entry = this.entries.get(scope);
72
+ if (!entry)
73
+ this.entries.set(scope, entry = { local: undefined, pr: undefined, prRef: undefined, prBase: undefined, prBranch: undefined, lastRead: -Infinity, generation: 0, trailing: undefined });
74
+ return entry;
75
+ }
76
+ async refresh(scope) {
77
+ const entry = this.entry(scope);
78
+ entry.lastRead = Date.now();
79
+ const generation = (entry.generation += 1);
80
+ const local = await this.read(scope);
81
+ if (generation !== entry.generation)
82
+ return;
83
+ entry.local = local;
84
+ if (local?.branch !== entry.prBranch)
85
+ entry.pr = undefined;
86
+ }
87
+ touch(scope) {
88
+ const entry = this.entry(scope);
89
+ if (entry.trailing)
90
+ return;
91
+ const wait = entry.lastRead + READ_INTERVAL_MS - Date.now();
92
+ if (wait <= 0) {
93
+ void this.refresh(scope);
94
+ return;
95
+ }
96
+ entry.trailing = setTimeout(() => {
97
+ entry.trailing = undefined;
98
+ void this.refresh(scope);
99
+ }, wait);
100
+ entry.trailing.unref();
101
+ }
102
+ summary(scope) {
103
+ const entry = this.entries.get(scope);
104
+ if (!entry?.local)
105
+ return undefined;
106
+ return { ...entry.local, ...(entry.pr ? { pr: entry.pr } : {}) };
107
+ }
108
+ hasPullRequest(scope, branch) {
109
+ const entry = this.entries.get(scope);
110
+ return Boolean(entry?.pr && entry.prBranch === branch);
111
+ }
112
+ pullRequestRef(scope) {
113
+ return this.entries.get(scope)?.prRef;
114
+ }
115
+ pullRequestBase(scope, branch) {
116
+ const entry = this.entries.get(scope);
117
+ return entry?.pr && entry.prBranch === branch ? entry.prBase : undefined;
118
+ }
119
+ async poll(sessions, forced) {
120
+ const now = Date.now();
121
+ const scopes = new Map();
122
+ for (const session of sessions) {
123
+ if (session.lifecycle === "live" || session.lifecycle === "dormant")
124
+ scopes.set(session.scope, scopes.get(session.scope) || session.watched);
125
+ }
126
+ const groups = new Map();
127
+ for (const [scope, watched] of scopes) {
128
+ const cached = this.targets.get(scope);
129
+ const target = cached && !watched && scope !== forced && !due(now - cached.readAt, false) && this.entries.get(scope)?.local?.branch === cached.localBranch ? cached : await this.target(scope, watched, now);
130
+ const entry = this.entry(scope);
131
+ const { branch: name, repository } = target;
132
+ if (!name || !repository) {
133
+ entry.pr = undefined;
134
+ continue;
135
+ }
136
+ const key = `${repository.base.repo}\0${repository.head.repo}\0${name}`;
137
+ const group = groups.get(key) ?? { scopes: [], repository, branch: name, watched: false, forced: false };
138
+ group.scopes.push(scope);
139
+ group.watched ||= watched;
140
+ group.forced ||= scope === forced;
141
+ groups.set(key, group);
142
+ }
143
+ for (const key of this.polledAt.keys())
144
+ if (!groups.has(key))
145
+ this.polledAt.delete(key);
146
+ for (const key of this.results.keys())
147
+ if (!groups.has(key))
148
+ this.results.delete(key);
149
+ for (const key of this.bases.keys())
150
+ if (!groups.has(key))
151
+ this.bases.delete(key);
152
+ for (const key of this.refs.keys())
153
+ if (!groups.has(key))
154
+ this.refs.delete(key);
155
+ for (const [key, group] of groups) {
156
+ if (group.forced || due(now - (this.polledAt.get(key) ?? -Infinity), group.watched)) {
157
+ this.polledAt.set(key, now);
158
+ const found = await resolvePullRequest(group.scopes[0], group.repository, group.branch, this.github).then(pr => ({ pr }), () => undefined);
159
+ if (found) {
160
+ this.bases.set(key, found.pr?.state === "OPEN" ? found.pr.baseBranch : undefined);
161
+ this.refs.set(key, found.pr && { repo: found.pr.repo, number: found.pr.number, id: found.pr.id });
162
+ this.results.set(key, found.pr && { number: found.pr.number, url: found.pr.url, state: found.pr.state, isDraft: found.pr.isDraft, checks: found.pr.checks, checksCompleted: found.pr.checksCompleted, reviewDecision: found.pr.reviewDecision, unresolvedThreads: found.pr.unresolvedThreads, updatedAt: found.pr.updatedAt });
163
+ }
164
+ }
165
+ if (!this.results.has(key))
166
+ continue;
167
+ for (const scope of group.scopes)
168
+ Object.assign(this.entry(scope), { pr: this.results.get(key), prRef: this.refs.get(key), prBase: this.bases.get(key), prBranch: group.branch });
169
+ }
170
+ this.release(new Set(sessions.map(session => session.scope)));
171
+ }
172
+ release(kept) {
173
+ for (const [scope, entry] of this.entries) {
174
+ if (kept.has(scope))
175
+ continue;
176
+ clearTimeout(entry.trailing);
177
+ this.entries.delete(scope);
178
+ }
179
+ for (const scope of this.targets.keys())
180
+ if (!kept.has(scope))
181
+ this.targets.delete(scope);
182
+ releaseRepositories(kept);
183
+ }
184
+ async target(scope, watched, now) {
185
+ const target = { readAt: now, localBranch: undefined, branch: undefined, repository: undefined };
186
+ this.targets.set(scope, target);
187
+ if (!isRepository(scope))
188
+ return target;
189
+ if (watched || !this.entries.get(scope)?.local)
190
+ await this.refresh(scope);
191
+ target.localBranch = this.entries.get(scope)?.local?.branch;
192
+ const branch = await head(scope);
193
+ target.branch = branch.ok && !branch.value.detached ? branch.value.name : undefined;
194
+ target.repository = target.branch === undefined ? undefined : await resolveRepository(scope, target.branch, this.github).catch(() => undefined);
195
+ return target;
196
+ }
197
+ }
@@ -0,0 +1,54 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ import { GIT_WRITE_TIMEOUT_MS } from "./git.js";
4
+ const exec = promisify(execFile);
5
+ export const gh = async (scope, args) => {
6
+ try {
7
+ return (await exec("gh", args, {
8
+ cwd: scope,
9
+ timeout: GIT_WRITE_TIMEOUT_MS,
10
+ maxBuffer: 2 << 20,
11
+ env: { ...process.env, GH_PROMPT_DISABLED: "1", GIT_TERMINAL_PROMPT: "0", ...(args[0] === "stack" ? { GIT_EDITOR: "true", GIT_SEQUENCE_EDITOR: "true" } : {}) },
12
+ })).stdout;
13
+ }
14
+ catch (error) {
15
+ const failure = error;
16
+ if (failure.code === "ENOENT")
17
+ throw new Error("GitHub CLI is missing. Install gh on the Session Host.");
18
+ const detail = (args[0] === "stack" ? [failure.stdout, failure.stderr].filter(Boolean).join("\n").trim() : failure.stderr?.trim()) || failure.message || "Unknown error";
19
+ const requestFailed = /HTTP (?:429|5\d\d)|connection|timed? out|network|TLS|certificate|could not resolve/i.test(detail);
20
+ if ((failure.code === 4 && args[0] !== "stack") || (args[0] === "auth" && !requestFailed)) {
21
+ throw new Error(`GitHub authentication failed. Run gh auth login on the Session Host. ${detail}`);
22
+ }
23
+ throw new Error(`GitHub request failed: ${detail}`);
24
+ }
25
+ };
26
+ export const page = "pageInfo { hasNextPage endCursor }";
27
+ export async function api(scope, github, query, variables) {
28
+ const args = ["api", "graphql", "-f", `query=${query}`];
29
+ for (const [key, value] of Object.entries(variables)) {
30
+ if (value !== null)
31
+ args.push(typeof value === "string" ? "-f" : "-F", `${key}=${value}`);
32
+ }
33
+ const result = JSON.parse(await github(scope, args));
34
+ if (result.errors?.length || !result.data)
35
+ throw new Error(result.errors?.map(error => error.message).join("; ") || "GitHub returned no data.");
36
+ return result.data;
37
+ }
38
+ export async function connection(scope, github, first, id, type, field, fields) {
39
+ const result = [...first.nodes];
40
+ const seen = new Set();
41
+ let current = first;
42
+ for (let count = 0; count < 1000; count++) {
43
+ if (!current.pageInfo.hasNextPage)
44
+ return result;
45
+ const cursor = current.pageInfo.endCursor;
46
+ if (!cursor || seen.has(cursor))
47
+ throw new Error("GitHub returned an invalid page cursor.");
48
+ seen.add(cursor);
49
+ const data = await api(scope, github, `query($id:ID!,$cursor:String){node(id:$id){... on ${type}{${field}(first:100,after:$cursor){nodes{${fields}} ${page}}}}}`, { id, cursor });
50
+ current = data.node[field];
51
+ result.push(...current.nodes);
52
+ }
53
+ throw new Error("GitHub pagination limit exceeded.");
54
+ }
@@ -1,4 +1,4 @@
1
- import { readBody, send } from "./http.js";
1
+ import { readBody, send } from './http.js';
2
2
  export async function hostControlRoute(request, response, path, control, admission) {
3
3
  if (path === '/api/host' && request.method === 'GET') {
4
4
  const { token: _token, ...status } = control.identity;
@@ -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";
@@ -22,7 +25,7 @@ import { ScheduleValidationError } from "../workflows/schedule-errors.js";
22
25
  import { probeSkills } from "./skills.js";
23
26
  import { recordTiming } from "./timings.js";
24
27
  import { SharedSandbox } from "../isolation/shared-sandbox.js";
25
- import { nameInput, summarisePublish, suggestedBranch, SummaryModelSpare } from "./summariser.js";
28
+ import { nameInput, suggestGitText, SummaryModelSpare } from "./summariser.js";
26
29
  /**
27
30
  * A command the Session Host will not carry out in the state the thing is in — a turn in flight, a
28
31
  * Scope that is not a repository, a checkout git itself refused.
@@ -65,8 +68,8 @@ export class SessionHost {
65
68
  summarySpare = new SummaryModelSpare();
66
69
  stackReviews = new Map();
67
70
  gitOperations = new Set();
71
+ gitStates = new GitStates();
68
72
  closingScopes = new Set();
69
- publishReviews = new Map();
70
73
  refuseGitOperation(scope) {
71
74
  if (this.gitOperations.has(scopeKey(scope)))
72
75
  throw new CommandRefused("A Git operation is in progress in this Scope. Wait for it to finish.");
@@ -103,6 +106,7 @@ export class SessionHost {
103
106
  }
104
107
  finally {
105
108
  this.gitOperations.delete(key);
109
+ void this.gitStates.refresh(scope);
106
110
  }
107
111
  }
108
112
  async prepareStack(sessionId, action) {
@@ -112,9 +116,9 @@ export class SessionHost {
112
116
  return this.withGitOperation(record.scope, async () => {
113
117
  this.stackReviews.delete(sessionId);
114
118
  await cleanStack(record.scope);
115
- const status = await actionStackStatus(record.scope);
119
+ const status = await stackStatus(record.scope);
116
120
  if (!status.view)
117
- throw new Error(status.problem ?? "No stack found.");
121
+ throw new Error(status.notice ?? "This branch is not in a stack.");
118
122
  const review = { token: randomUUID(), action, view: status.view };
119
123
  this.stackReviews.set(sessionId, { review, fingerprint: await stackFingerprint(record.scope, status.view, action === "sync"), expires: Date.now() + 15 * 60_000 });
120
124
  return review;
@@ -129,19 +133,18 @@ export class SessionHost {
129
133
  if (!saved || saved.expires < Date.now() || saved.review.token !== input.token || saved.review.action !== input.action)
130
134
  throw new Error("This Stack review expired. Review again.");
131
135
  await cleanStack(record.scope);
132
- const status = await actionStackStatus(record.scope);
136
+ const status = await stackStatus(record.scope);
133
137
  if (!status.view || await stackFingerprint(record.scope, status.view, input.action === "sync") !== saved.fingerprint)
134
138
  throw new Error("The reviewed stack changed. Review again.");
135
139
  }
136
140
  try {
137
- return await changeStack(record.scope, input);
141
+ return await this.afterPullRequestWrite(record.scope, changeStack(record.scope, input));
138
142
  }
139
143
  finally {
140
144
  for (const other of this.sessions.values()) {
141
145
  if (scopeKey(other.scope) !== scopeKey(record.scope))
142
146
  continue;
143
147
  this.stackReviews.delete(other.id);
144
- this.publishReviews.delete(other.id);
145
148
  await this.refreshBranch(other);
146
149
  other.pendingBranchNote = "[Flow] A Stack operation was attempted in this Scope. Re-read the branch and changed files before relying on earlier reads.";
147
150
  }
@@ -151,67 +154,91 @@ export class SessionHost {
151
154
  async assistStack(sessionId) {
152
155
  const record = this.record(sessionId);
153
156
  await this.withGitOperation(record.scope, async () => {
154
- const status = await actionStackStatus(record.scope);
157
+ const status = await stackStatus(record.scope);
155
158
  if (!status.rebasing)
156
- 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.");
157
160
  });
158
161
  await this.send(sessionId, stackConflictMessage, "now");
159
162
  }
160
- async gitStatus(sessionId) {
161
- 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);
162
165
  }
163
- async preparePublish(sessionId) {
164
- const record = this.record(sessionId);
165
- return this.withGitOperation(record.scope, async () => {
166
- this.publishReviews.delete(sessionId);
167
- for (const [id, review] of this.publishReviews)
168
- if (review.expires < Date.now())
169
- this.publishReviews.delete(id);
170
- const { input: changes, ...reviewed } = await snapshot(record.scope);
171
- const destination = await target(record.scope, reviewed.branch);
172
- const committed = await branchChanges(record.scope, destination);
173
- if (reviewed.files.length === 0 && committed.commits.length === 0 && !destination.pr)
174
- throw new CommandRefused("There are no changes to publish.");
175
- let text = { commitMessage: "", title: destination.pr?.title ?? "", body: "" };
176
- let warning;
177
- const model = this.summaryModel?.(record.backendName);
178
- try {
179
- if (!model)
180
- throw new Error("No Summary Model is configured. Choose one in Settings, or enter publish text below.");
181
- text = await summarisePublish({ backend: this.backendFor(model.backend), modelId: model.modelId, text: `${changes}\nCommitted branch changes:\n${committed.input}` });
182
- }
183
- catch (error) {
184
- warning = `Enter publish text manually. ${error instanceof Error ? error.message : String(error)}`;
185
- }
186
- const suggestion = await canNameBranch(record.scope, reviewed.branch, destination)
187
- ? text.suggestedBranch ?? suggestedBranch((record.titleSource !== "scope" ? record.title : "") || text.commitMessage || committed.commits[0]?.replace(/^[a-f0-9]+ /, "") || record.title)
188
- : undefined;
189
- delete text.suggestedBranch;
190
- const token = randomUUID();
191
- this.publishReviews.set(sessionId, { token, expires: Date.now() + 15 * 60_000, snapshot: reviewed, target: destination });
192
- 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;
193
189
  });
194
190
  }
195
- 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);
196
211
  const record = this.record(sessionId);
197
212
  return this.withGitOperation(record.scope, async () => {
198
- const review = this.publishReviews.get(sessionId);
199
- if (!review || review.token !== input.token || review.expires < Date.now())
200
- throw new CommandRefused("This Publish review expired. Open Publish again.");
201
- this.publishReviews.delete(sessionId);
213
+ const before = await head(record.scope);
202
214
  try {
203
- return await publish(record.scope, review.snapshot, review.target, input);
215
+ return await commit(record.scope, input);
204
216
  }
205
217
  finally {
206
- for (const other of this.sessions.values()) {
207
- if (scopeKey(other.scope) !== scopeKey(record.scope))
208
- continue;
209
- await this.refreshBranch(other);
210
- 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
+ }
211
226
  }
212
227
  }
213
228
  });
214
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
+ }
215
242
  store;
216
243
  retention;
217
244
  standingAuthorisations;
@@ -471,6 +498,7 @@ export class SessionHost {
471
498
  // lifting an Ended row back out of Filed away.
472
499
  const input = record.lifecycle === "live" ? newestAt(parentInput, workflowInput) : undefined;
473
500
  const outcome = record.latestOutcome;
501
+ const git = this.gitStates.summary(record.scope);
474
502
  const unread = outcome !== undefined && outcome.version > record.readAttentionVersion;
475
503
  const attention = input
476
504
  ? {
@@ -506,6 +534,7 @@ export class SessionHost {
506
534
  lastSeq: record.log.lastSeq,
507
535
  ...(record.capabilities ? { capabilities: record.capabilities } : {}),
508
536
  ...(record.branch ? { branch: record.branch } : {}),
537
+ ...(git ? { git } : {}),
509
538
  ...(record.worktree ? { worktree: true } : {}),
510
539
  ...(record.session || existsSync(record.scope) ? {} : {
511
540
  scopeMissing: true,
@@ -1553,7 +1582,7 @@ export class SessionHost {
1553
1582
  if (!isRepository(record.scope))
1554
1583
  return;
1555
1584
  const generation = (record.branchGeneration += 1);
1556
- const found = await head(record.scope);
1585
+ const [found] = await Promise.all([head(record.scope), this.gitStates.refresh(record.scope)]);
1557
1586
  // A repository git cannot answer about is left as it was: this runs off the critical path, and
1558
1587
  // there is no reader to tell.
1559
1588
  if (!found.ok)
@@ -1981,7 +2010,6 @@ export class SessionHost {
1981
2010
  await this.releaseWorktree(record);
1982
2011
  record.log.closeSubscribers();
1983
2012
  this.sessions.delete(record.id);
1984
- this.publishReviews.delete(record.id);
1985
2013
  this.store?.deleteSession(record.id);
1986
2014
  reaped.push(record.id);
1987
2015
  }
@@ -2191,27 +2219,55 @@ export class SessionHost {
2191
2219
  case "pull_branch":
2192
2220
  return await this.withGitOperation(this.record(command.sessionId).scope, () => pullBranch(this.record(command.sessionId).scope, command.branch));
2193
2221
  case "change_pull_request":
2194
- return await this.withGitOperation(this.record(command.sessionId).scope, () => changePullRequest(this.record(command.sessionId).scope, command.action, command.input));
2195
- case "pull_request":
2196
- 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
+ }
2197
2227
  case "comment_pull_request":
2198
- 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));
2199
2229
  case "resolve_pull_request_thread":
2200
- 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);
2201
2239
  case "stack_status":
2202
- return await this.withGitOperation(this.record(command.sessionId).scope, () => stackStatus(this.record(command.sessionId).scope));
2240
+ return await this.readStack(command.sessionId);
2203
2241
  case "prepare_stack":
2204
2242
  return await this.prepareStack(command.sessionId, command.action);
2205
2243
  case "change_stack":
2206
2244
  return await this.changeStack(command.sessionId, command.input);
2207
2245
  case "assist_stack":
2208
2246
  return await this.assistStack(command.sessionId);
2209
- case "git_status":
2210
- return await this.gitStatus(command.sessionId);
2211
- case "prepare_publish":
2212
- return await this.preparePublish(command.sessionId);
2213
- case "publish":
2214
- 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);
2215
2271
  case "switch_branch":
2216
2272
  return await this.switchBranch(command.sessionId, command.branch);
2217
2273
  case "switch_scope_branch":
@@ -2290,10 +2346,10 @@ export class SessionHost {
2290
2346
  scheduledMcp(scope, ids, mode) {
2291
2347
  const connections = this.scheduledConnections(ids);
2292
2348
  const oauth = this.mcpAuth ? (connection) => this.mcpAuth.provider(connection) : undefined;
2293
- 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));
2294
2350
  }
2295
2351
  scheduledSandboxMcp(scope, ids) {
2296
- 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));
2297
2353
  }
2298
2354
  /** Include an SDK-supplied owning root in every local execution's filesystem policy. */
2299
2355
  filesystemStateRoot() { return this.store?.root; }
@@ -2320,7 +2376,7 @@ export class SessionHost {
2320
2376
  const connection = this.workflowMcpConnections(id).find(connection => connection.id === connectionId);
2321
2377
  if (!connection)
2322
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.');
2323
- const { McpSession } = await import("../backend/mcp.js");
2379
+ const { McpSession } = await import('../backend/mcp.js');
2324
2380
  const scope = this.workflowSession(id).scope;
2325
2381
  signal?.throwIfAborted();
2326
2382
  return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode);
@@ -2330,7 +2386,7 @@ export class SessionHost {
2330
2386
  const connection = (this.mcpConnections?.() ?? []).find(connection => connection.id === connectionId);
2331
2387
  if (!connection)
2332
2388
  throw new Error('MCP connection removed. Refresh the workflow editor.');
2333
- const { McpSession } = await import("../backend/mcp.js");
2389
+ const { McpSession } = await import('../backend/mcp.js');
2334
2390
  return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode, expectedScopeIdentity);
2335
2391
  }
2336
2392
  mcpStatus(id) {
@@ -2883,6 +2939,8 @@ export class SessionHost {
2883
2939
  record.turnGeneration = (record.turnGeneration ?? 0) + 1;
2884
2940
  record.turnInFlight = true;
2885
2941
  }
2942
+ if (event.type === "tool_ended" && record.turnInFlight)
2943
+ this.gitStates.touch(record.scope);
2886
2944
  if (event.type === "turn_ended") {
2887
2945
  record.turnGeneration = (record.turnGeneration ?? 0) + 1;
2888
2946
  this.workflowOwner?.rearmInput?.(sessionId);
@@ -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";
@@ -1,6 +1,6 @@
1
1
  import { closeSync, fstatSync, mkdirSync, mkdtempSync, openSync, readSync, rmSync, writeFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { workflowBuilderFolder } from "../isolation/shared-sandbox.js";
3
+ import { workflowBuilderFolder } from '../isolation/shared-sandbox.js';
4
4
  export class PiModelProbeCache {
5
5
  catalog;
6
6
  generation = 0;