@nathanstephenson/flow 0.1.10-beta.4 → 0.1.10-beta.6

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 (101) hide show
  1. package/README.md +2 -2
  2. package/build/backend-worker-chunks/{chunk-JOI2POLP.mjs → chunk-U73G6KK4.mjs} +18 -0
  3. package/build/backend-worker-chunks/{claude-GY27HBAY.mjs → claude-THGSOTC2.mjs} +7 -1
  4. package/build/backend-worker-chunks/{pi-JV6MWPW7.mjs → pi-5LAWIJNE.mjs} +82 -3
  5. package/build/backend-worker.mjs +7 -3
  6. package/build/workflow-runtime.cjs +12 -12
  7. package/dist/backend/claude/index.js +6 -0
  8. package/dist/backend/claude/workflow-parent.js +1 -1
  9. package/dist/backend/fake/index.js +6 -0
  10. package/dist/backend/pi/index.js +34 -2
  11. package/dist/backend/pi/model-auth.js +2 -2
  12. package/dist/backend/pi/plan-limits.js +41 -0
  13. package/dist/backend/pi/workflow-parent.js +1 -1
  14. package/dist/backend/plan-limits.js +17 -0
  15. package/dist/backend/worker/entry.js +4 -1
  16. package/dist/backend/worker/index.js +9 -3
  17. package/dist/backend/worker/launcher.js +11 -4
  18. package/dist/backend/worker/protocol.js +2 -1
  19. package/dist/build-id +1 -1
  20. package/dist/cli/application.js +5 -5
  21. package/dist/cli/bootstrap.js +1 -1
  22. package/dist/cli/host-control.js +1 -1
  23. package/dist/cli/install-guard.js +1 -1
  24. package/dist/cli/main.js +4 -4
  25. package/dist/cli/systemd-update.js +3 -3
  26. package/dist/cli/update.js +6 -6
  27. package/dist/cli/web-update.js +6 -6
  28. package/dist/client/context-usage.js +1 -1
  29. package/dist/client/markdown.js +3 -2
  30. package/dist/daemon/changes.js +116 -0
  31. package/dist/daemon/commit.js +84 -0
  32. package/dist/daemon/config-store.js +4 -3
  33. package/dist/daemon/config.js +31 -2
  34. package/dist/daemon/git-state.js +197 -0
  35. package/dist/daemon/github-image.js +18 -0
  36. package/dist/daemon/github.js +54 -0
  37. package/dist/daemon/host-control-routes.js +1 -1
  38. package/dist/daemon/host.js +280 -81
  39. package/dist/daemon/log.js +3 -0
  40. package/dist/daemon/mcp-auth.js +1 -1
  41. package/dist/daemon/pi-model-cache.js +1 -1
  42. package/dist/daemon/pull-request.js +156 -129
  43. package/dist/daemon/push.js +43 -0
  44. package/dist/daemon/repository.js +106 -0
  45. package/dist/daemon/runtime.js +28 -21
  46. package/dist/daemon/secret-store.js +1 -1
  47. package/dist/daemon/server.js +37 -10
  48. package/dist/daemon/skills.js +24 -0
  49. package/dist/daemon/spend-ledger.js +118 -0
  50. package/dist/daemon/stack-metadata.js +12 -5
  51. package/dist/daemon/stack.js +127 -656
  52. package/dist/daemon/summariser.js +30 -12
  53. package/dist/daemon/tour.js +42 -0
  54. package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
  55. package/dist/daemon/workflow-authoring-scope.js +1 -1
  56. package/dist/daemon/workflow-builder-files.js +2 -2
  57. package/dist/daemon/workflow-builder-routes.js +2 -2
  58. package/dist/daemon/workflow-builder.js +8 -6
  59. package/dist/daemon/workflow-environment.js +5 -5
  60. package/dist/daemon/workflow-execution-launch.js +5 -5
  61. package/dist/daemon/workflow-execution-resources.js +4 -4
  62. package/dist/daemon/workflow-execution-routes.js +3 -3
  63. package/dist/daemon/workflow-execution-values.js +5 -5
  64. package/dist/daemon/workflow-executions.js +19 -19
  65. package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
  66. package/dist/daemon/workflow-mcp-authoring.js +4 -4
  67. package/dist/daemon/workflow-mcp.js +1 -1
  68. package/dist/daemon/workflow-routes.js +22 -3
  69. package/dist/daemon/workflow-schedule-driver.js +8 -8
  70. package/dist/daemon/workflow-schedule-routes.js +5 -5
  71. package/dist/daemon/workflow-schedules.js +9 -8
  72. package/dist/isolation/toolchain-assets.js +1 -1
  73. package/dist/protocol/spend.js +2 -0
  74. package/dist/protocol/stack.js +1 -41
  75. package/dist/workflows/calls.js +2 -2
  76. package/dist/workflows/executors.js +3 -3
  77. package/dist/workflows/graph.js +6 -6
  78. package/dist/workflows/invocations.js +1 -1
  79. package/dist/workflows/mcp.js +1 -1
  80. package/dist/workflows/records.js +6 -6
  81. package/dist/workflows/recovery.js +2 -2
  82. package/dist/workflows/runtime-settings.js +1 -1
  83. package/dist/workflows/runtime.js +2 -2
  84. package/dist/workflows/schedule-store.js +2 -2
  85. package/dist/workflows/scheduler.js +35 -23
  86. package/dist/workflows/schema.js +1 -1
  87. package/dist/workflows/store.js +19 -5
  88. package/package.json +3 -2
  89. package/web/dist/assets/index-BhfJhrVJ.js +51 -0
  90. package/web/dist/assets/index-BvkM2cWL.css +2 -0
  91. package/web/dist/assets/{settings-mcp-bcNKV147.js → settings-mcp-3cgqQB28.js} +1 -1
  92. package/web/dist/assets/settings-workflows-Cutm8isB.js +23 -0
  93. package/web/dist/assets/{switch-DIogWclb.js → switch-B00FEUA7.js} +1 -1
  94. package/web/dist/assets/{workflows-DHG-CIo3.js → workflows-D6oEUUhj.js} +31 -31
  95. package/web/dist/assets/{workflows-pane-9u_hJvgQ.js → workflows-pane-KIdSDKJB.js} +1 -1
  96. package/web/dist/index.html +4 -4
  97. package/dist/daemon/publish.js +0 -289
  98. package/web/dist/assets/index-BWKZK5HD.css +0 -2
  99. package/web/dist/assets/index-nIc09tKZ.js +0 -40
  100. package/web/dist/assets/settings-workflows-C_TKOhVa.js +0 -23
  101. /package/dist/protocol/{publish.js → plan-limits.js} +0 -0
@@ -1,108 +1,65 @@
1
- import { gh } from "./publish.js";
1
+ import { api, connection, gh, page } from "./github.js";
2
+ import { githubRepository, localRepository, resolvePullRequest, resolveRepository } from "./repository.js";
2
3
  import { cleanStack } from "./stack.js";
3
- import { head, isRepository, run, GIT_READ_TIMEOUT_MS, GIT_WRITE_TIMEOUT_MS } from "./git.js";
4
- const page = "pageInfo { hasNextPage endCursor }";
5
- const commentFields = "id author { login } body url createdAt";
4
+ import { pushTarget, remoteHead } from "./push.js";
5
+ import { localStack, stackParent } from "./stack-metadata.js";
6
+ import { head, isRepository, run, GIT_WRITE_TIMEOUT_MS } from "./git.js";
7
+ const commentFields = "id author{login} body url createdAt";
8
+ const threadFields = "id path line isOutdated isResolved viewerCanReply viewerCanResolve viewerCanUnresolve";
9
+ const threadCommentFields = `${commentFields} diffHunk`;
10
+ const checkFields = "... on CheckRun{name status conclusion detailsUrl} ... on StatusContext{context state targetUrl}";
11
+ const detailsQuery = `query($id:ID!){node(id:$id){... on PullRequest{id number url title body state isDraft reviewDecision updatedAt author{login} headRefName headRefOid headRepository{id nameWithOwner} baseRefName mergeable mergeStateStatus locked repository{isArchived viewerPermission mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed} comments(first:100){nodes{${commentFields}} ${page}} reviews(first:100){nodes{${commentFields} state} ${page}} reviewThreads(first:100){nodes{${threadFields} comments(first:100){nodes{${threadCommentFields}} ${page}}} ${page}} commits(last:1){nodes{commit{statusCheckRollup{id contexts(first:100){nodes{${checkFields}} ${page}}}}}}}}}`;
12
+ const writers = ["ADMIN", "MAINTAIN", "WRITE"];
6
13
  const comment = (value) => ({ ...value, author: value.author?.login ?? "[deleted]" });
7
- async function api(scope, github, query, variables) {
8
- const args = ["api", "graphql", "-f", `query=${query}`];
9
- for (const [key, value] of Object.entries(variables)) {
10
- if (value !== null)
11
- args.push(typeof value === "string" ? "-f" : "-F", `${key}=${value}`);
12
- }
13
- const result = JSON.parse(await github(scope, args));
14
- if (result.errors?.length || !result.data)
15
- throw new Error(result.errors?.map(error => error.message).join("; ") || "GitHub returned no data.");
16
- return result.data;
17
- }
18
- async function pages(load) {
19
- const result = [];
20
- let cursor = null;
21
- const seen = new Set();
22
- for (let count = 0; count < 1000; count++) {
23
- const connection = await load(cursor);
24
- result.push(...connection.nodes);
25
- if (!connection.pageInfo.hasNextPage)
26
- return result;
27
- cursor = connection.pageInfo.endCursor;
28
- if (!cursor || seen.has(cursor))
29
- throw new Error("GitHub returned an invalid page cursor.");
30
- seen.add(cursor);
31
- }
32
- throw new Error("GitHub pagination limit exceeded.");
14
+ function check(node) {
15
+ const url = node.detailsUrl || node.targetUrl || "";
16
+ const ids = /^https:\/\/github\.com\/[^/]+\/[^/]+\/actions\/runs\/(\d+)\/job\/(\d+)/.exec(url);
17
+ return { name: node.name || node.context || "Check", status: node.conclusion || node.state || node.status || "UNKNOWN", url, ...(ids ? { runId: Number(ids[1]), jobId: Number(ids[2]) } : {}) };
33
18
  }
34
- async function connection(scope, github, id, type, field, fields) {
35
- return pages(async (cursor) => {
36
- 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 });
37
- return data.node[field];
38
- });
19
+ async function details(scope, ref, github) {
20
+ const { id } = ref;
21
+ const { node } = await api(scope, github, detailsQuery, { id });
22
+ if (!node)
23
+ return undefined;
24
+ const { author, headRepository, locked, repository, comments, reviews, reviewThreads, commits, ...fields } = node;
25
+ const threads = [];
26
+ for (const { comments: entries, ...thread } of await connection(scope, github, reviewThreads, id, "PullRequest", "reviewThreads", `${threadFields} comments(first:100){nodes{${threadCommentFields}} ${page}}`)) {
27
+ const all = await connection(scope, github, entries, thread.id, "PullRequestReviewThread", "comments", threadCommentFields);
28
+ threads.push({ ...thread, diffHunk: all[0]?.diffHunk ?? "", comments: all.map(comment) });
29
+ }
30
+ const rollup = commits.nodes[0]?.commit.statusCheckRollup;
31
+ const writer = !repository.isArchived && writers.includes(repository.viewerPermission ?? "");
32
+ const mergeMethods = !writer ? [] : [
33
+ ...(repository.mergeCommitAllowed ? ["MERGE"] : []),
34
+ ...(repository.squashMergeAllowed ? ["SQUASH"] : []),
35
+ ...(repository.rebaseMergeAllowed ? ["REBASE"] : []),
36
+ ];
37
+ return { headRepositoryId: headRepository?.id, pr: {
38
+ ...fields, repo: ref.repo, author: author?.login ?? "[deleted]", mergeMethods,
39
+ ...(headRepository ? { headRepository: headRepository.nameWithOwner } : {}),
40
+ viewerCanComment: !repository.isArchived && (!locked || writers.includes(repository.viewerPermission ?? "")),
41
+ comments: (await connection(scope, github, comments, id, "PullRequest", "comments", commentFields)).map(comment),
42
+ reviews: (await connection(scope, github, reviews, id, "PullRequest", "reviews", `${commentFields} state`)).map(value => ({ ...comment(value), state: value.state })),
43
+ threads,
44
+ checks: rollup ? (await connection(scope, github, rollup.contexts, rollup.id, "StatusCheckRollup", "contexts", checkFields)).map(check) : [],
45
+ } };
39
46
  }
40
- async function select(scope, github) {
47
+ export async function pullRequest(scope, known, github = gh) {
41
48
  if (!isRepository(scope))
42
49
  return null;
43
50
  const branch = await head(scope);
44
51
  if (!branch.ok)
45
52
  throw new Error(branch.failure.message);
46
- if (branch.value.detached)
53
+ if (branch.value.detached || !(await localRepository(scope, branch.value.name))?.github)
47
54
  return null;
48
- const base = JSON.parse(await github(scope, ["repo", "view", "--json", "nameWithOwner"]));
49
- const remoteNames = await run(scope, ["remote"], GIT_READ_TIMEOUT_MS);
50
- if (!remoteNames.ok)
51
- throw new Error(remoteNames.failure.message);
52
- const names = remoteNames.value.trim().split("\n").filter(Boolean);
53
- const configured = await run(scope, ["config", "--get", `branch.${branch.value.name}.pushRemote`], GIT_READ_TIMEOUT_MS);
54
- const pushDefault = await run(scope, ["config", "--get", "remote.pushDefault"], GIT_READ_TIMEOUT_MS);
55
- const upstream = await run(scope, ["config", "--get", `branch.${branch.value.name}.remote`], GIT_READ_TIMEOUT_MS);
56
- const preferred = [configured, pushDefault, upstream].find(value => value.ok && value.value.trim() !== ".");
57
- const remote = preferred?.ok ? preferred.value.trim() : names.includes("origin") ? "origin" : names.length === 1 ? names[0] : undefined;
58
- if (!remote)
59
- throw new Error("Cannot identify this branch's source remote.");
60
- const url = await run(scope, ["remote", "get-url", "--push", remote], GIT_READ_TIMEOUT_MS);
61
- if (!url.ok)
62
- throw new Error(url.failure.message);
63
- const source = /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([^/]+\/[^/]+?)(?:\.git)?$/.exec(url.value.trim())?.[1];
64
- if (!source)
65
- throw new Error("Cannot identify the GitHub source repository.");
66
- const sourceRepo = JSON.parse(await github(scope, ["repo", "view", source, "--json", "id"]));
67
- if (!sourceRepo.id)
68
- throw new Error("Cannot verify the source repository: GitHub did not return its ID.");
69
- const [owner, name] = base.nameWithOwner.split("/");
70
- const candidates = await pages(async (cursor) => {
71
- const data = await api(scope, github, `query($owner:String!,$name:String!,$branch:String!,$cursor:String){repository(owner:$owner,name:$name){pullRequests(headRefName:$branch,first:100,after:$cursor,orderBy:{field:UPDATED_AT,direction:DESC}){nodes{id number state updatedAt closedAt headRepository{id}} ${page}}}}`, { owner: owner, name: name, branch: branch.value.name, cursor });
72
- return data.repository.pullRequests;
73
- });
74
- const matches = candidates.filter(pr => pr.headRepository?.id === sourceRepo.id);
75
- matches.sort((a, b) => Number(b.state === "OPEN") - Number(a.state === "OPEN") || (b.closedAt ?? b.updatedAt).localeCompare(a.closedAt ?? a.updatedAt));
76
- const chosen = matches[0];
77
- return chosen ? { repo: base.nameWithOwner, number: chosen.number, id: chosen.id } : null;
78
- }
79
- export async function pullRequest(scope, github = gh) {
80
- const ref = await select(scope, github);
81
- if (!ref)
82
- return null;
83
- const data = await api(scope, github, `query($id:ID!){node(id:$id){... on PullRequest{id number url title body state isDraft reviewDecision author{login} headRefName headRefOid headRepository{nameWithOwner} baseRefName createdAt updatedAt mergeable mergeStateStatus locked repository{isArchived viewerPermission mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed} commits(last:1){nodes{commit{statusCheckRollup{id}}}}}}}`, ref);
84
- const { commits, author, headRepository, locked, repository, ...details } = data.node;
85
- const viewerCanComment = !repository.isArchived && (!locked || ["ADMIN", "MAINTAIN", "WRITE"].includes(repository.viewerPermission ?? ""));
86
- const comments = (await connection(scope, github, ref.id, "PullRequest", "comments", commentFields)).map(comment);
87
- const reviews = (await connection(scope, github, ref.id, "PullRequest", "reviews", `${commentFields} state`)).map(value => ({ ...comment(value), state: value.state }));
88
- const rawThreads = await connection(scope, github, ref.id, "PullRequest", "reviewThreads", "id path line isOutdated isResolved viewerCanReply viewerCanResolve viewerCanUnresolve");
89
- const threads = [];
90
- for (const thread of rawThreads) {
91
- const entries = await connection(scope, github, thread.id, "PullRequestReviewThread", "comments", `${commentFields} diffHunk`);
92
- threads.push({ ...thread, diffHunk: entries[0]?.diffHunk ?? "", comments: entries.map(comment) });
55
+ const repository = await resolveRepository(scope, branch.value.name, github);
56
+ if (known?.repo === repository.base.repo) {
57
+ const read = await details(scope, known, github);
58
+ if (read && read.pr.headRefName === branch.value.name && read.headRepositoryId === repository.head.id)
59
+ return read.pr;
93
60
  }
94
- const rollup = commits.nodes[0]?.commit.statusCheckRollup;
95
- const statusCheckRollup = rollup ? await connection(scope, github, rollup.id, "StatusCheckRollup", "contexts", "... on CheckRun { name status conclusion detailsUrl } ... on StatusContext { context state targetUrl }") : [];
96
- const mergeMethods = [];
97
- if (!repository.isArchived && ["ADMIN", "MAINTAIN", "WRITE"].includes(repository.viewerPermission ?? "")) {
98
- if (repository.mergeCommitAllowed)
99
- mergeMethods.push("MERGE");
100
- if (repository.squashMergeAllowed)
101
- mergeMethods.push("SQUASH");
102
- if (repository.rebaseMergeAllowed)
103
- mergeMethods.push("REBASE");
104
- }
105
- return { ...details, ...ref, mergeMethods, ...(headRepository ? { headRepository: headRepository.nameWithOwner } : {}), author: author?.login ?? "[deleted]", viewerCanComment, comments, reviews, threads, statusCheckRollup };
61
+ const resolved = await resolvePullRequest(scope, repository, branch.value.name, github);
62
+ return resolved ? (await details(scope, resolved, github))?.pr ?? null : null;
106
63
  }
107
64
  async function git(scope, args) {
108
65
  const result = await run(scope, args, GIT_WRITE_TIMEOUT_MS);
@@ -117,39 +74,73 @@ export async function pullBranch(scope, branch) {
117
74
  throw new Error("The branch has changed. Refresh Git status before pulling.");
118
75
  await git(scope, ["pull", "--ff-only", "--no-rebase", "--no-autostash", "--no-squash"]);
119
76
  }
77
+ export async function createPullRequest(scope, input, github = gh) {
78
+ if (typeof input.title !== "string" || !input.title.trim() || typeof input.body !== "string")
79
+ throw new Error("Enter a pull request title.");
80
+ const { branch, head, repository } = await pushTarget(scope, github);
81
+ if (head !== input.head)
82
+ throw new Error("HEAD moved after the branch was read. Read it again.");
83
+ if (await remoteHead(scope, repository.remote, branch) !== head)
84
+ throw new Error(`Push the branch first. ${repository.remote} does not have the current HEAD of ${branch}.`);
85
+ const existing = await resolvePullRequest(scope, repository, branch, github);
86
+ if (existing?.state === "OPEN")
87
+ throw new Error(`Pull request #${existing.number} is already open for ${branch}.`);
88
+ const stack = await localStack(scope, branch);
89
+ const base = stack ? stackParent(stack, branch) : repository.base.defaultBranch;
90
+ const owner = repository.head.repo.split("/")[0];
91
+ return (await github(scope, ["pr", "create", "--repo", repository.base.repo, "--head", `${owner}:${branch}`, "--base", base, "--title", input.title, "--body", input.body, ...(input.draft ? ["--draft"] : [])])).trim();
92
+ }
93
+ function validId(value) { return typeof value === "string" && /^[A-Za-z0-9_+/=-]+$/.test(value) && value.length <= 256; }
94
+ function validate(ref) {
95
+ if (!ref || typeof ref.repo !== "string" || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(ref.repo) || !Number.isSafeInteger(ref.number) || ref.number < 1 || !validId(ref.id))
96
+ throw new Error("Invalid pull request reference.");
97
+ }
98
+ async function target(scope, ref, github) {
99
+ const selected = await head(scope);
100
+ const branch = selected.ok && !selected.value.detached ? selected.value.name : undefined;
101
+ const pr = branch === undefined ? undefined : await resolvePullRequest(scope, await resolveRepository(scope, branch, github), branch, github);
102
+ if (!pr || pr.id !== ref.id || pr.number !== ref.number || pr.repo !== ref.repo)
103
+ throw new Error("The branch's pull request has changed. Reload it before continuing.");
104
+ return { ...pr, branch: branch };
105
+ }
120
106
  export async function changePullRequest(scope, action, input, github = gh) {
121
107
  validate(input?.pr);
122
108
  if (action !== "rebase" && action !== "merge")
123
109
  throw new Error("Invalid pull request action.");
124
110
  if (!/^[0-9a-f]{40,64}$/.test(input.headOid) || typeof input.baseBranch !== "string")
125
111
  throw new Error("Invalid pull request action.");
126
- const pr = await current(scope, input.pr, github);
127
- if (pr.state !== "OPEN" || pr.headRefOid !== input.headOid || pr.baseRefName !== input.baseBranch)
112
+ if (action === "merge" && !["MERGE", "SQUASH", "REBASE"].includes(input.method ?? ""))
113
+ throw new Error("Invalid merge method.");
114
+ if (action === "rebase")
115
+ await cleanStack(scope);
116
+ const pr = await target(scope, input.pr, github);
117
+ if (pr.state !== "OPEN" || pr.headRefOid !== input.headOid || pr.baseBranch !== input.baseBranch)
128
118
  throw new Error("The pull request has changed. Reload it before continuing.");
129
119
  if (action === "merge") {
130
- if (pr.isDraft || !input.method || !pr.mergeMethods?.includes(input.method))
131
- throw new Error("This merge method is not permitted for this pull request.");
120
+ if (pr.isDraft)
121
+ throw new Error("Mark the pull request ready for review before you merge it.");
132
122
  await api(scope, github, "mutation($id:ID!,$head:GitObjectID!,$method:PullRequestMergeMethod!){mergePullRequest(input:{pullRequestId:$id,expectedHeadOid:$head,mergeMethod:$method}){pullRequest{id state}}}", { id: pr.id, head: input.headOid, method: input.method });
133
123
  return;
134
124
  }
135
- await cleanStack(scope);
136
- await git(scope, ["check-ref-format", `refs/heads/${pr.baseRefName}`]);
125
+ await git(scope, ["check-ref-format", `refs/heads/${pr.baseBranch}`]);
137
126
  const before = await git(scope, ["rev-parse", "HEAD"]);
138
127
  let baseUrl = `https://github.com/${pr.repo}.git`;
139
128
  for (const remote of (await git(scope, ["remote"])).split("\n").filter(Boolean)) {
140
129
  const url = await git(scope, ["remote", "get-url", remote]);
141
- const repo = /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([^/]+\/[^/]+?)(?:\.git)?$/.exec(url)?.[1];
130
+ const repo = githubRepository(url);
142
131
  if (repo?.toLowerCase() === pr.repo.toLowerCase()) {
143
132
  baseUrl = url;
144
133
  break;
145
134
  }
146
135
  }
147
- await git(scope, ["fetch", "--no-tags", baseUrl, `refs/heads/${pr.baseRefName}`]);
136
+ await git(scope, ["fetch", "--no-tags", baseUrl, `refs/heads/${pr.baseBranch}`]);
148
137
  const base = await git(scope, ["rev-parse", "FETCH_HEAD"]);
149
- const latest = await current(scope, input.pr, github);
138
+ const latest = await target(scope, input.pr, github);
139
+ if (latest.state !== "OPEN" || latest.headRefOid !== input.headOid || latest.baseBranch !== input.baseBranch)
140
+ throw new Error("The pull request has changed. Reload it before rebasing.");
150
141
  const branch = await head(scope);
151
- if (latest.state !== "OPEN" || latest.headRefOid !== input.headOid || latest.baseRefName !== input.baseBranch || !branch.ok || branch.value.detached || branch.value.name !== pr.headRefName || await git(scope, ["rev-parse", "HEAD"]) !== before)
152
- throw new Error("The branch or pull request has changed. Reload it before rebasing.");
142
+ if (!branch.ok || branch.value.detached || branch.value.name !== pr.branch || await git(scope, ["rev-parse", "HEAD"]) !== before)
143
+ throw new Error("The branch has changed. Reload it before rebasing.");
153
144
  await cleanStack(scope);
154
145
  const rebased = await run(scope, ["-c", "rebase.autoStash=false", "-c", "rebase.updateRefs=false", "rebase", base], GIT_WRITE_TIMEOUT_MS);
155
146
  if (!rebased.ok) {
@@ -157,42 +148,78 @@ export async function changePullRequest(scope, action, input, github = gh) {
157
148
  throw new Error(`${rebased.failure.message}\n${aborted.ok ? "Rebase aborted. Local changes were not pushed." : `Rebase did not complete. Check Git status in the Shell; if a rebase remains, run git rebase --abort. ${aborted.failure.message}`}`);
158
149
  }
159
150
  }
160
- function validId(value) { return typeof value === "string" && /^[A-Za-z0-9_+/=-]+$/.test(value) && value.length <= 256; }
161
- function validate(ref) {
162
- if (!ref || typeof ref.repo !== "string" || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(ref.repo) || !Number.isSafeInteger(ref.number) || ref.number < 1 || !validId(ref.id))
163
- throw new Error("Invalid pull request reference.");
164
- }
165
- async function current(scope, ref, github) {
166
- const pr = await pullRequest(scope, github);
167
- if (!pr || pr.id !== ref.id || pr.number !== ref.number || pr.repo !== ref.repo)
168
- throw new Error("The branch's pull request has changed. Reload it before continuing.");
169
- return pr;
151
+ async function requireThread(scope, pr, thread, github) {
152
+ const data = await api(scope, github, "query($thread:ID!){node(id:$thread){... on PullRequestReviewThread{pullRequest{id}}}}", { thread });
153
+ if (data.node?.pullRequest?.id !== pr.id)
154
+ throw new Error("This review thread is not on this pull request. Reload it before continuing.");
170
155
  }
171
156
  export async function commentPullRequest(scope, input, github = gh) {
172
157
  validate(input?.pr);
173
158
  if (typeof input.body !== "string" || !input.body.trim() || (input.threadId !== undefined && !validId(input.threadId)))
174
159
  throw new Error("Invalid comment input.");
175
- const pr = await current(scope, input.pr, github);
160
+ const pr = await target(scope, input.pr, github);
176
161
  if (input.threadId !== undefined) {
177
- const thread = pr.threads.find(value => value.id === input.threadId);
178
- if (!thread?.viewerCanReply)
179
- throw new Error("Cannot reply to this thread.");
180
- await api(scope, github, "mutation($id:ID!,$body:String!){addPullRequestReviewThreadReply(input:{pullRequestReviewThreadId:$id,body:$body}){comment{id}}}", { id: thread.id, body: input.body });
162
+ await requireThread(scope, pr, input.threadId, github);
163
+ await api(scope, github, "mutation($id:ID!,$body:String!){addPullRequestReviewThreadReply(input:{pullRequestReviewThreadId:$id,body:$body}){comment{id}}}", { id: input.threadId, body: input.body });
181
164
  }
182
- else {
183
- if (!pr.viewerCanComment)
184
- throw new Error("Cannot comment on this pull request.");
165
+ else
185
166
  await api(scope, github, "mutation($id:ID!,$body:String!){addComment(input:{subjectId:$id,body:$body}){commentEdge{node{id}}}}", { id: pr.id, body: input.body });
186
- }
187
167
  }
188
168
  export async function resolvePullRequestThread(scope, input, github = gh) {
189
169
  validate(input?.pr);
190
170
  if (!validId(input.threadId) || typeof input.resolved !== "boolean")
191
171
  throw new Error("Invalid thread input.");
192
- const pr = await current(scope, input.pr, github);
193
- const thread = pr.threads.find(value => value.id === input.threadId);
194
- if (!thread || !(input.resolved ? thread.viewerCanResolve : thread.viewerCanUnresolve))
195
- throw new Error("Cannot change this thread's resolved state.");
172
+ await requireThread(scope, await target(scope, input.pr, github), input.threadId, github);
196
173
  const operation = input.resolved ? "resolveReviewThread" : "unresolveReviewThread";
197
- await api(scope, github, `mutation($id:ID!){${operation}(input:{threadId:$id}){thread{id}}}`, { id: thread.id });
174
+ await api(scope, github, `mutation($id:ID!){${operation}(input:{threadId:$id}){thread{id}}}`, { id: input.threadId });
175
+ }
176
+ export async function editPullRequest(scope, input, github = gh) {
177
+ validate(input?.pr);
178
+ if (typeof input.title !== "string" || !input.title.trim() || typeof input.body !== "string")
179
+ throw new Error("Enter a pull request title.");
180
+ const pr = await target(scope, input.pr, github);
181
+ await api(scope, github, "mutation($id:ID!,$title:String!,$body:String!){updatePullRequest(input:{pullRequestId:$id,title:$title,body:$body}){pullRequest{id}}}", { id: pr.id, title: input.title, body: input.body });
182
+ }
183
+ export async function setPullRequestDraft(scope, input, github = gh) {
184
+ validate(input?.pr);
185
+ if (typeof input.draft !== "boolean")
186
+ throw new Error("Invalid draft input.");
187
+ const pr = await target(scope, input.pr, github);
188
+ const operation = input.draft ? "convertPullRequestToDraft" : "markPullRequestReadyForReview";
189
+ await api(scope, github, `mutation($id:ID!){${operation}(input:{pullRequestId:$id}){pullRequest{id}}}`, { id: pr.id });
190
+ }
191
+ export async function rerunPullRequestChecks(scope, input, github = gh) {
192
+ validate(input?.pr);
193
+ if (!Number.isSafeInteger(input.runId) || input.runId < 1)
194
+ throw new Error("Invalid run ID.");
195
+ const pr = await target(scope, input.pr, github);
196
+ const run = JSON.parse(await github(scope, ["api", `repos/${pr.repo}/actions/runs/${input.runId}`]));
197
+ if (run.head_sha !== pr.headRefOid)
198
+ throw new Error("This run is not for the current head of the pull request. Reload it before you re-run checks.");
199
+ await github(scope, ["run", "rerun", String(input.runId), "--failed", "--repo", pr.repo]);
200
+ }
201
+ const checkLogLines = 80;
202
+ export async function checkLog(scope, ref, jobId, github = gh) {
203
+ validate(ref);
204
+ if (!Number.isSafeInteger(jobId) || jobId < 1)
205
+ throw new Error("Invalid job ID.");
206
+ const pr = await target(scope, ref, github);
207
+ const job = JSON.parse(await github(scope, ["api", `repos/${pr.repo}/actions/jobs/${jobId}`]));
208
+ if (job.head_sha !== pr.headRefOid)
209
+ throw new Error("This job is not for the current head of the pull request. Reload it before you add its log.");
210
+ let log;
211
+ try {
212
+ log = await github(scope, ["api", `repos/${pr.repo}/actions/jobs/${jobId}/logs`, "--allow-escape-sequences"]);
213
+ }
214
+ catch {
215
+ return null;
216
+ }
217
+ const lines = log.replace(/\s+$/, "").split(/\r\n?|\n/).map(line => line
218
+ .replaceAll("\ufeff", "")
219
+ .replace(/^\d{4}-\d\d-\d\dT[\d:.]+Z ?/, "")
220
+ .replace(/\u001b(?:\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|\[[0-?]*[ -/]*[@-~]|[ -/]*[0-~])/g, "")
221
+ .replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, ""));
222
+ const end = lines.findLastIndex(line => line.startsWith("##[error]")) + 1 || lines.length;
223
+ const start = Math.max(0, end - checkLogLines);
224
+ return { text: lines.slice(start, end).join("\n"), truncated: start > 0 || end < lines.length };
198
225
  }
@@ -0,0 +1,43 @@
1
+ import { head, run, GIT_READ_TIMEOUT_MS } from "./git.js";
2
+ import { gh } from "./github.js";
3
+ import { git, resolveRepository } from "./repository.js";
4
+ const credentials = ["-c", "credential.helper=", "-c", "credential.helper=!gh auth git-credential"];
5
+ export async function remoteHead(scope, remote, branch) {
6
+ const listed = await git(scope, [...credentials, "ls-remote", "--heads", remote, `refs/heads/${branch}`], true);
7
+ return listed.split("\n").map(line => line.split("\t")).find(([, ref]) => ref === `refs/heads/${branch}`)?.[0];
8
+ }
9
+ export async function pushTarget(scope, github) {
10
+ const current = await head(scope);
11
+ if (!current.ok)
12
+ throw new Error(current.failure.message);
13
+ if (current.value.detached)
14
+ throw new Error("HEAD is detached. Commit on a new branch first.");
15
+ const branch = current.value.name;
16
+ const repository = await resolveRepository(scope, branch, github);
17
+ if (branch === repository.base.defaultBranch)
18
+ throw new Error(`${branch} is the default branch. Flow does not push or open pull requests from it.`);
19
+ const commit = await run(scope, ["rev-parse", "--verify", "--quiet", "HEAD"], GIT_READ_TIMEOUT_MS);
20
+ if (!commit.ok)
21
+ throw new Error("This branch has no commits. Commit first.");
22
+ return { branch, head: commit.value.trim(), repository };
23
+ }
24
+ export async function pushState(scope, github = gh) {
25
+ const { branch, head, repository } = await pushTarget(scope, github);
26
+ const remote = await remoteHead(scope, repository.remote, branch);
27
+ if (!remote)
28
+ return { branch, head, replaced: [] };
29
+ if (!(await run(scope, ["cat-file", "-e", `${remote}^{commit}`], GIT_READ_TIMEOUT_MS)).ok) {
30
+ await git(scope, [...credentials, "fetch", "--quiet", "--no-tags", repository.remote, `refs/heads/${branch}`], true);
31
+ }
32
+ const replaced = (await git(scope, ["log", "--no-color", "--format=%h %s", `HEAD..${remote}`, "--"])).split("\n").filter(Boolean);
33
+ return { branch, head, remote, replaced };
34
+ }
35
+ export async function push(scope, input, github = gh) {
36
+ if (input.replace !== undefined && !/^[0-9a-f]{40,64}$/.test(input.replace))
37
+ throw new Error("Invalid remote commit ID.");
38
+ const { branch, head, repository } = await pushTarget(scope, github);
39
+ if (head !== input.head)
40
+ throw new Error("HEAD moved after the push state was read. Read it again.");
41
+ const lease = input.replace ? [`--force-with-lease=refs/heads/${branch}:${input.replace}`] : [];
42
+ await git(scope, [...credentials, "push", "--quiet", "--no-follow-tags", "--set-upstream", ...lease, repository.remote, `refs/heads/${branch}:refs/heads/${branch}`], true);
43
+ }
@@ -0,0 +1,106 @@
1
+ import { run, GIT_READ_TIMEOUT_MS, GIT_WRITE_TIMEOUT_MS } from "./git.js";
2
+ import { api, gh } from "./github.js";
3
+ const unfinished = ["IN_PROGRESS", "PENDING", "QUEUED", "WAITING", "REQUESTED", "EXPECTED"];
4
+ function completed(counts) {
5
+ return [...counts?.checkRunCountsByState ?? [], ...counts?.statusContextCountsByState ?? []].filter(entry => !unfinished.includes(entry.state)).reduce((sum, entry) => sum + entry.count, 0);
6
+ }
7
+ const identities = new Map();
8
+ export async function git(scope, args, write = false) {
9
+ const result = await run(scope, args, write ? GIT_WRITE_TIMEOUT_MS : GIT_READ_TIMEOUT_MS);
10
+ if (!result.ok) {
11
+ if (result.failure.message.includes("ENOENT"))
12
+ throw new Error("Git is missing. Install git on the Session Host.");
13
+ throw new Error(`Git ${result.failure.attempted} failed: ${result.failure.message}`);
14
+ }
15
+ return result.value;
16
+ }
17
+ async function config(scope, key) {
18
+ const result = await run(scope, ["config", "--get", key], GIT_READ_TIMEOUT_MS);
19
+ const value = result.ok ? result.value.trim() : "";
20
+ return value && value !== "." ? value : undefined;
21
+ }
22
+ async function pushRemote(scope, branch) {
23
+ const remotes = (await git(scope, ["remote"])).trim().split("\n").filter(Boolean);
24
+ if (remotes.length === 0)
25
+ return undefined;
26
+ const keys = branch ? [`branch.${branch}.pushRemote`, "remote.pushDefault", `branch.${branch}.remote`] : ["remote.pushDefault"];
27
+ for (const key of keys) {
28
+ const configured = await config(scope, key);
29
+ if (configured)
30
+ return configured;
31
+ }
32
+ if (remotes.includes("origin"))
33
+ return "origin";
34
+ if (remotes.length === 1)
35
+ return remotes[0];
36
+ throw new Error("Cannot identify the push remote for this branch. Set branch.<name>.pushRemote or remote.pushDefault.");
37
+ }
38
+ async function view(scope, repo, github) {
39
+ const info = JSON.parse(await github(scope, ["repo", "view", repo, "--json", "id,defaultBranchRef,isFork,parent"]));
40
+ if (!info.id)
41
+ throw new Error(`GitHub did not return the ID of ${repo}.`);
42
+ if (!info.defaultBranchRef?.name)
43
+ throw new Error(`GitHub has no default branch for ${repo}. Create it first.`);
44
+ return { ...info, id: info.id, defaultBranch: info.defaultBranchRef.name };
45
+ }
46
+ export function githubRepository(url) {
47
+ return /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?$/.exec(url)?.[1];
48
+ }
49
+ export async function localRepository(scope, branch) {
50
+ const remote = await pushRemote(scope, branch);
51
+ if (!remote)
52
+ return undefined;
53
+ const url = (await git(scope, ["remote", "get-url", "--push", remote])).trim();
54
+ const cached = identities.get(`${scope}\0${remote}\0${url}`)?.base.defaultBranch;
55
+ const head = await run(scope, ["symbolic-ref", "--quiet", "--short", `refs/remotes/${remote}/HEAD`], GIT_READ_TIMEOUT_MS);
56
+ const local = head.ok ? head.value.trim().slice(remote.length + 1) : undefined;
57
+ return { remote, github: githubRepository(url) !== undefined, defaultBranches: [...new Set([cached, local].filter((name) => Boolean(name)))] };
58
+ }
59
+ export async function resolveRepository(scope, branch, github = gh) {
60
+ const remote = await pushRemote(scope, branch);
61
+ if (!remote)
62
+ throw new Error("No remote is configured. Add a GitHub remote.");
63
+ const url = (await git(scope, ["remote", "get-url", "--push", remote])).trim();
64
+ const repo = githubRepository(url);
65
+ if (!repo)
66
+ throw new Error("This remote is not a supported github.com repository URL.");
67
+ const key = `${scope}\0${remote}\0${url}`;
68
+ let identity = identities.get(key);
69
+ if (!identity) {
70
+ await github(scope, ["auth", "status", "--hostname", "github.com"]);
71
+ const head = await view(scope, repo, github);
72
+ const parent = head.isFork && head.parent ? `${head.parent.owner.login}/${head.parent.name}` : undefined;
73
+ const base = parent ? await view(scope, parent, github) : head;
74
+ identity = { head: { repo, id: head.id }, base: { repo: parent ?? repo, id: base.id, defaultBranch: base.defaultBranch } };
75
+ identities.set(key, identity);
76
+ }
77
+ return { remote, url, ...identity };
78
+ }
79
+ export function releaseRepositories(kept) {
80
+ for (const key of identities.keys())
81
+ if (!kept.has(key.split("\0")[0]))
82
+ identities.delete(key);
83
+ }
84
+ function checks(rollup) {
85
+ if (!rollup)
86
+ return "none";
87
+ if (rollup.state === "SUCCESS")
88
+ return "passing";
89
+ if (rollup.state === "FAILURE" || rollup.state === "ERROR")
90
+ return "failing";
91
+ return "pending";
92
+ }
93
+ export async function resolvePullRequest(scope, repository, branch, github = gh) {
94
+ const [owner, name] = repository.base.repo.split("/");
95
+ const data = await api(scope, github, "query($owner:String!,$name:String!,$branch:String!){repository(owner:$owner,name:$name){pullRequests(headRefName:$branch,first:100,orderBy:{field:UPDATED_AT,direction:DESC}){nodes{id number url title baseRefName headRefOid state isDraft reviewDecision updatedAt closedAt headRepository{id} commits(last:1){nodes{commit{statusCheckRollup{state contexts(first:0){checkRunCountsByState{state count} statusContextCountsByState{state count}}}}}} reviewThreads(first:100){nodes{isResolved}}}}}}", { owner: owner, name: name, branch });
96
+ const matches = data.repository.pullRequests.nodes.filter(pr => pr.headRepository?.id === repository.head.id);
97
+ matches.sort((a, b) => Number(b.state === "OPEN") - Number(a.state === "OPEN") || (b.closedAt ?? b.updatedAt).localeCompare(a.closedAt ?? a.updatedAt));
98
+ const pr = matches[0];
99
+ if (!pr)
100
+ return undefined;
101
+ return {
102
+ repo: repository.base.repo, id: pr.id, number: pr.number, url: pr.url, title: pr.title, baseBranch: pr.baseRefName, headRefOid: pr.headRefOid, state: pr.state, isDraft: pr.isDraft,
103
+ checks: checks(pr.commits.nodes[0]?.commit.statusCheckRollup), checksCompleted: completed(pr.commits.nodes[0]?.commit.statusCheckRollup?.contexts), reviewDecision: pr.reviewDecision,
104
+ unresolvedThreads: pr.reviewThreads.nodes.filter(thread => !thread.isResolved).length, updatedAt: pr.updatedAt,
105
+ };
106
+ }
@@ -1,23 +1,23 @@
1
- import { registerBackends } from "../backend/registry.js";
2
- import { createOidcGateFromEnv, readOrCreateToken } from "./auth.js";
3
- import { ConfigStore } from "./config-store.js";
4
- import { SecretStore } from "./secret-store.js";
5
- import { WorkflowStore } from "../workflows/store.js";
6
- import { WorkflowExecutionService } from "./workflow-executions.js";
7
- import { WorkflowScheduleStore } from "../workflows/schedule-store.js";
8
- import { WorkflowScheduleService } from "./workflow-schedules.js";
9
- import { scheduleDriver } from "./workflow-schedule-driver.js";
10
- import { WorkflowBuilderService } from "./workflow-builder.js";
11
- import { workflowCatalogue } from "./workflow-routes.js";
12
- import { WorkflowMcpAuthoringService } from "./workflow-mcp-authoring.js";
13
- import { SessionHost } from "./host.js";
14
- import { McpAuth } from "./mcp-auth.js";
15
- import { serve } from "./server.js";
16
- import { ShellRegistry } from "./shell.js";
17
- import { TranscriptStore } from "./store.js";
18
- import { acquireHost, readHost, oidcFingerprint } from "./ownership.js";
19
- import { WebUpdateController } from "../cli/web-update.js";
20
- import { trimTimings } from "./timings.js";
1
+ import { registerBackends } from '../backend/registry.js';
2
+ import { createOidcGateFromEnv, readOrCreateToken } from './auth.js';
3
+ import { ConfigStore } from './config-store.js';
4
+ import { SecretStore } from './secret-store.js';
5
+ import { WorkflowStore } from '../workflows/store.js';
6
+ import { WorkflowExecutionService } from './workflow-executions.js';
7
+ import { WorkflowScheduleStore } from '../workflows/schedule-store.js';
8
+ import { WorkflowScheduleService } from './workflow-schedules.js';
9
+ import { scheduleDriver } from './workflow-schedule-driver.js';
10
+ import { WorkflowBuilderService } from './workflow-builder.js';
11
+ import { workflowCatalogue } from './workflow-routes.js';
12
+ import { WorkflowMcpAuthoringService } from './workflow-mcp-authoring.js';
13
+ import { SessionHost } from './host.js';
14
+ import { McpAuth } from './mcp-auth.js';
15
+ import { serve } from './server.js';
16
+ import { ShellRegistry } from './shell.js';
17
+ import { TranscriptStore } from './store.js';
18
+ import { acquireHost, readHost, oidcFingerprint } from './ownership.js';
19
+ import { WebUpdateController } from '../cli/web-update.js';
20
+ import { trimTimings } from './timings.js';
21
21
  export async function startRuntime(options) {
22
22
  const ownership = acquireHost(options.root);
23
23
  const root = ownership.root;
@@ -52,7 +52,7 @@ export async function startRuntime(options) {
52
52
  sandboxSharing: config.sandboxSharing, projectRoot: config.projectRoot,
53
53
  standingAuthorisations: config.standingAuthorisations, allowTool: config.allowTool,
54
54
  defaultBackend: config.defaultBackend, defaultModel: config.defaultModel,
55
- defaultEffort: config.defaultEffort, defaultPermissionMode: config.defaultPermissionMode, autoCompaction: config.autoCompaction, compactionModel: config.compactionModel, summaryModel: config.summaryModel,
55
+ defaultEffort: config.defaultEffort, defaultPermissionMode: config.defaultPermissionMode, autoCompaction: config.autoCompaction, compactionModel: config.compactionModel, summaryModel: config.summaryModel, tourModel: config.tourModel,
56
56
  });
57
57
  const shells = new ShellRegistry();
58
58
  let workflowSchedules;
@@ -62,10 +62,13 @@ export async function startRuntime(options) {
62
62
  let running;
63
63
  let oidc;
64
64
  let sweep;
65
+ let gitPoll;
66
+ let gitPolling;
65
67
  let reaping = Promise.resolve();
66
68
  let stopping;
67
69
  const stop = () => stopping ??= (async () => {
68
70
  clearInterval(sweep);
71
+ clearInterval(gitPoll);
69
72
  const scheduledErrors = [];
70
73
  try {
71
74
  await workflowSchedules?.stopAdmission();
@@ -162,6 +165,10 @@ export async function startRuntime(options) {
162
165
  });
163
166
  }, 60 * 60 * 1000);
164
167
  sweep.unref();
168
+ gitPoll = setInterval(() => {
169
+ gitPolling ??= host.pollGitState().finally(() => { gitPolling = undefined; });
170
+ }, 30_000);
171
+ gitPoll.unref();
165
172
  host.onSessionClosed(sessionId => shells.killFor(sessionId));
166
173
  const token = readOrCreateToken(root);
167
174
  oidc = await createOidcGateFromEnv(root);
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
- import { validSecretName } from "../protocol/secrets.js";
4
+ import { validSecretName } from '../protocol/secrets.js';
5
5
  export class SecretStore {
6
6
  directory;
7
7
  constructor(stateRoot) {