@nathanstephenson/flow 0.1.9 → 0.1.10-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/README.md +60 -21
  2. package/build/backend-worker-chunks/chunk-3KDHJA5P.mjs +162 -0
  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-JG2FXYBQ.mjs +35859 -0
  7. package/build/backend-worker-chunks/{pi-M4OA2FGL.mjs → pi-KJSP23AO.mjs} +2138 -93
  8. package/build/backend-worker.mjs +77 -123
  9. package/build/workflow-runtime.cjs +12 -12
  10. package/dist/backend/claude/background-calls.js +7 -3
  11. package/dist/backend/claude/import.js +415 -0
  12. package/dist/backend/claude/index.js +201 -21
  13. package/dist/backend/claude/session-tools.js +14 -0
  14. package/dist/backend/claude/subagents.js +41 -9
  15. package/dist/backend/claude/todo-list.js +114 -0
  16. package/dist/backend/claude/workflow-parent.js +1 -1
  17. package/dist/backend/diff-excerpt-instructions.js +8 -0
  18. package/dist/backend/fake/index.js +54 -6
  19. package/dist/backend/mcp.js +4 -1
  20. package/dist/backend/pi/agent-permissions.js +1 -1
  21. package/dist/backend/pi/cache-warming.js +8 -0
  22. package/dist/backend/pi/canonical-json.js +120 -0
  23. package/dist/backend/pi/compaction-model.js +3 -2
  24. package/dist/backend/pi/host-auth.js +258 -0
  25. package/dist/backend/pi/import.js +269 -0
  26. package/dist/backend/pi/index.js +125 -21
  27. package/dist/backend/pi/model-auth.js +159 -0
  28. package/dist/backend/pi/model-catalog.js +120 -0
  29. package/dist/backend/pi/model-config.js +5 -0
  30. package/dist/backend/pi/model-selection.js +32 -0
  31. package/dist/backend/pi/plan-limits.js +41 -0
  32. package/dist/backend/pi/session-tools.js +21 -0
  33. package/dist/backend/pi/state.js +19 -1
  34. package/dist/backend/pi/subagents.js +7 -3
  35. package/dist/backend/pi/todo-list.js +23 -0
  36. package/dist/backend/pi/work.js +9 -1
  37. package/dist/backend/pi/workflow-parent.js +1 -1
  38. package/dist/backend/pi/workflow-subagent.js +4 -3
  39. package/dist/backend/plan-limits.js +17 -0
  40. package/dist/backend/session-tools.js +27 -0
  41. package/dist/backend/worker/claude-state.js +48 -0
  42. package/dist/backend/worker/entry.js +49 -8
  43. package/dist/backend/worker/index.js +155 -17
  44. package/dist/backend/worker/launcher.js +11 -4
  45. package/dist/backend/worker/protocol.js +2 -1
  46. package/dist/backend/worker/rpc.js +13 -0
  47. package/dist/backend/worker/sandbox-mcp.js +18 -7
  48. package/dist/backend/workflow-tools.js +9 -6
  49. package/dist/build-id +1 -1
  50. package/dist/cli/application.js +48 -42
  51. package/dist/cli/bootstrap.js +2 -2
  52. package/dist/cli/host-control.js +1 -1
  53. package/dist/cli/install-guard.js +2 -2
  54. package/dist/cli/main.js +4 -4
  55. package/dist/cli/systemd-update.js +3 -3
  56. package/dist/cli/update.js +6 -6
  57. package/dist/cli/web-update.js +6 -6
  58. package/dist/client/connection.js +46 -0
  59. package/dist/client/context-usage.js +3 -4
  60. package/dist/client/diff.js +40 -0
  61. package/dist/client/enquiry.js +0 -6
  62. package/dist/client/markdown.js +3 -2
  63. package/dist/client/model-choices.js +1 -1
  64. package/dist/client/permission.js +1 -2
  65. package/dist/client/project-name.js +3 -1
  66. package/dist/client/reduce.js +77 -3
  67. package/dist/client/relative-time.js +1 -1
  68. package/dist/client/scope-kind.js +6 -3
  69. package/dist/client/search.js +1 -1
  70. package/dist/client/status.js +1 -1
  71. package/dist/client/subagent-tree.js +49 -0
  72. package/dist/client/tool-chains.js +1 -1
  73. package/dist/client/tool-summary.js +28 -18
  74. package/dist/daemon/changes.js +128 -0
  75. package/dist/daemon/commit.js +84 -0
  76. package/dist/daemon/config-store.js +8 -3
  77. package/dist/daemon/config.js +105 -4
  78. package/dist/daemon/diff-excerpts.js +52 -0
  79. package/dist/daemon/git-state.js +197 -0
  80. package/dist/daemon/git.js +53 -10
  81. package/dist/daemon/github-image.js +18 -0
  82. package/dist/daemon/github.js +54 -0
  83. package/dist/daemon/host-control-routes.js +1 -1
  84. package/dist/daemon/host.js +1010 -116
  85. package/dist/daemon/http.js +4 -1
  86. package/dist/daemon/log.js +3 -0
  87. package/dist/daemon/mcp-auth.js +1 -1
  88. package/dist/daemon/models.js +2 -2
  89. package/dist/daemon/pi-model-cache.js +44 -0
  90. package/dist/daemon/pull-request.js +223 -138
  91. package/dist/daemon/push.js +43 -0
  92. package/dist/daemon/repository.js +123 -0
  93. package/dist/daemon/runtime.js +103 -22
  94. package/dist/daemon/secret-store.js +1 -1
  95. package/dist/daemon/server.js +111 -14
  96. package/dist/daemon/session-tool-views.js +22 -0
  97. package/dist/daemon/skills.js +24 -0
  98. package/dist/daemon/spend-ledger.js +118 -0
  99. package/dist/daemon/stack-metadata.js +12 -5
  100. package/dist/daemon/stack.js +162 -657
  101. package/dist/daemon/store.js +2 -0
  102. package/dist/daemon/summariser.js +30 -12
  103. package/dist/daemon/tour.js +56 -0
  104. package/dist/daemon/whisper.js +144 -0
  105. package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
  106. package/dist/daemon/workflow-authoring-scope.js +1 -1
  107. package/dist/daemon/workflow-builder-files.js +2 -2
  108. package/dist/daemon/workflow-builder-guidance.js +1 -1
  109. package/dist/daemon/workflow-builder-routes.js +2 -2
  110. package/dist/daemon/workflow-builder.js +44 -17
  111. package/dist/daemon/workflow-environment.js +193 -0
  112. package/dist/daemon/workflow-execution-launch.js +77 -0
  113. package/dist/daemon/workflow-execution-resources.js +76 -0
  114. package/dist/daemon/workflow-execution-routes.js +17 -8
  115. package/dist/daemon/workflow-execution-values.js +128 -0
  116. package/dist/daemon/workflow-executions.js +434 -305
  117. package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
  118. package/dist/daemon/workflow-mcp-authoring.js +4 -4
  119. package/dist/daemon/workflow-mcp.js +1 -1
  120. package/dist/daemon/workflow-routes.js +60 -2
  121. package/dist/daemon/workflow-schedule-driver.js +251 -0
  122. package/dist/daemon/workflow-schedule-routes.js +137 -0
  123. package/dist/daemon/workflow-schedules.js +342 -0
  124. package/dist/isolation/filesystem.js +6 -2
  125. package/dist/isolation/sandbox.js +61 -18
  126. package/dist/isolation/shared-sandbox.js +3 -3
  127. package/dist/isolation/toolchain-assets.js +1 -1
  128. package/dist/protocol/events.js +3 -0
  129. package/dist/protocol/plan-limits.js +1 -0
  130. package/dist/protocol/settings.js +1 -0
  131. package/dist/protocol/spend.js +2 -0
  132. package/dist/protocol/stack.js +12 -39
  133. package/dist/protocol/workflow-schedules.js +1 -0
  134. package/dist/workflows/calls.js +53 -0
  135. package/dist/workflows/errors.js +2 -0
  136. package/dist/workflows/executors.js +6 -5
  137. package/dist/workflows/graph.js +83 -9
  138. package/dist/workflows/invocations.js +23 -0
  139. package/dist/workflows/mcp.js +1 -1
  140. package/dist/workflows/owner.js +45 -0
  141. package/dist/workflows/records.js +150 -10
  142. package/dist/workflows/recovery.js +87 -2
  143. package/dist/workflows/runtime-settings.js +16 -16
  144. package/dist/workflows/runtime.js +2 -2
  145. package/dist/workflows/schedule-errors.js +2 -0
  146. package/dist/workflows/schedule-store.js +385 -0
  147. package/dist/workflows/scheduler.js +389 -98
  148. package/dist/workflows/schedules.js +130 -0
  149. package/dist/workflows/schema.js +3 -1
  150. package/dist/workflows/store.js +126 -13
  151. package/package.json +10 -6
  152. package/web/dist/assets/index-C76t-z4w.css +2 -0
  153. package/web/dist/assets/{index-DRfeO6GJ.js → index-WPfbYVQ4.js} +39 -23
  154. package/web/dist/assets/{switch-DIogWclb.js → select-C5Ly2OpB.js} +1 -1
  155. package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-BF-yqpeQ.js} +1 -1
  156. package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-WLarr2QP.js} +1 -1
  157. package/web/dist/assets/settings-workflows-DdcdRWFD.js +23 -0
  158. package/web/dist/assets/workflow-api-GjAmHc22.js +6 -0
  159. package/web/dist/assets/workflows-BhY3Uibo.js +149 -0
  160. package/web/dist/assets/workflows-pane-DElCcEpN.js +1 -0
  161. package/web/dist/index.html +6 -5
  162. package/build/backend-worker-chunks/chunk-J2DBNTL7.mjs +0 -94
  163. package/build/backend-worker-chunks/claude-GTW5KHY5.mjs +0 -30778
  164. package/dist/daemon/publish.js +0 -289
  165. package/dist/tui/app.js +0 -612
  166. package/dist/tui/keys.js +0 -90
  167. package/dist/tui/render.js +0 -411
  168. package/web/dist/assets/index-DgQFpKbn.css +0 -2
  169. package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
  170. package/web/dist/assets/workflow-api-BfExddae.js +0 -6
  171. package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
  172. package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
  173. package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
  174. /package/dist/protocol/{publish.js → imports.js} +0 -0
@@ -1,4 +1,7 @@
1
1
  export async function readBody(request, limit) {
2
+ return (await readBytes(request, limit)).toString('utf8') || '{}';
3
+ }
4
+ export async function readBytes(request, limit) {
2
5
  const chunks = [];
3
6
  let size = 0;
4
7
  for await (const chunk of request) {
@@ -7,7 +10,7 @@ export async function readBody(request, limit) {
7
10
  throw new Error('Request body too large');
8
11
  chunks.push(chunk);
9
12
  }
10
- return Buffer.concat(chunks).toString('utf8') || '{}';
13
+ return Buffer.concat(chunks);
11
14
  }
12
15
  export function send(response, status, body) {
13
16
  const payload = JSON.stringify(body);
@@ -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
+ }
@@ -1,108 +1,81 @@
1
- import { gh } from "./publish.js";
1
+ import { api, connection, gh, page } from "./github.js";
2
+ import { githubRepository, localRepository, mergeMethods, mergeSettingsFields, pullRequestByNumber, resolvePullRequest, resolveRepository, writers } from "./repository.js";
2
3
  import { cleanStack } from "./stack.js";
4
+ import { pushTarget, remoteHead } from "./push.js";
5
+ import { localStack, stackParent } from "./stack-metadata.js";
3
6
  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";
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{${mergeSettingsFields}} 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}}}}}}}}}`;
6
12
  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.");
13
+ function check(node) {
14
+ const url = node.detailsUrl || node.targetUrl || "";
15
+ const ids = /^https:\/\/github\.com\/[^/]+\/[^/]+\/actions\/runs\/(\d+)\/job\/(\d+)/.exec(url);
16
+ 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
17
  }
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
- });
18
+ async function details(scope, ref, github) {
19
+ const { id } = ref;
20
+ const { node } = await api(scope, github, detailsQuery, { id });
21
+ if (!node)
22
+ return undefined;
23
+ const { author, headRepository, locked, repository, comments, reviews, reviewThreads, commits, ...fields } = node;
24
+ const threads = [];
25
+ for (const { comments: entries, ...thread } of await connection(scope, github, reviewThreads, id, "PullRequest", "reviewThreads", `${threadFields} comments(first:100){nodes{${threadCommentFields}} ${page}}`)) {
26
+ const all = await connection(scope, github, entries, thread.id, "PullRequestReviewThread", "comments", threadCommentFields);
27
+ threads.push({ ...thread, diffHunk: all[0]?.diffHunk ?? "", comments: all.map(comment) });
28
+ }
29
+ const rollup = commits.nodes[0]?.commit.statusCheckRollup;
30
+ return { headRepositoryId: headRepository?.id, pr: {
31
+ ...fields, repo: ref.repo, author: author?.login ?? "[deleted]", mergeMethods: mergeMethods(repository),
32
+ ...(headRepository ? { headRepository: headRepository.nameWithOwner } : {}),
33
+ viewerCanComment: !repository.isArchived && (!locked || writers.includes(repository.viewerPermission ?? "")),
34
+ comments: (await connection(scope, github, comments, id, "PullRequest", "comments", commentFields)).map(comment),
35
+ reviews: (await connection(scope, github, reviews, id, "PullRequest", "reviews", `${commentFields} state`)).map(value => ({ ...comment(value), state: value.state })),
36
+ threads,
37
+ checks: rollup ? (await connection(scope, github, rollup.contexts, rollup.id, "StatusCheckRollup", "contexts", checkFields)).map(check) : [],
38
+ } };
39
39
  }
40
- async function select(scope, github) {
40
+ export async function pullRequest(scope, known, github = gh) {
41
41
  if (!isRepository(scope))
42
42
  return null;
43
43
  const branch = await head(scope);
44
44
  if (!branch.ok)
45
45
  throw new Error(branch.failure.message);
46
- if (branch.value.detached)
47
- 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)
46
+ if (branch.value.detached || !(await localRepository(scope, branch.value.name))?.github)
82
47
  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) });
48
+ const repository = await resolveRepository(scope, branch.value.name, github);
49
+ if (known?.repo === repository.base.repo) {
50
+ const read = await details(scope, known, github);
51
+ if (read && read.pr.headRefName === branch.value.name && read.headRepositoryId === repository.head.id)
52
+ return read.pr;
93
53
  }
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");
54
+ const resolved = await resolvePullRequest(scope, repository, branch.value.name, github);
55
+ return resolved ? (await details(scope, resolved, github))?.pr ?? null : null;
56
+ }
57
+ export async function projectPullRequest(scope, number, github = gh) {
58
+ if (!Number.isSafeInteger(number) || number < 1)
59
+ throw new Error("Invalid pull request number.");
60
+ const repository = await resolveRepository(scope, undefined, github);
61
+ const found = await pullRequestByNumber(scope, repository.base.repo, number, github);
62
+ return found ? (await details(scope, found, github))?.pr ?? null : null;
63
+ }
64
+ const listFields = "id number title state isDraft updatedAt author{login} reviewRequests(first:100){nodes{requestedReviewer{... on User{login}}}}";
65
+ /** Open Pull Requests of the base repository, or with `query`, all of them whose title matches. */
66
+ export async function listPullRequests(scope, github = gh, query) {
67
+ const repo = (await resolveRepository(scope, undefined, github)).base.repo;
68
+ const [owner, name] = repo.split("/");
69
+ const item = (viewer) => ({ author, reviewRequests, repository: _, ...node }) => ({
70
+ ...node, repo, author: author?.login ?? "[deleted]",
71
+ reviewRequested: reviewRequests.nodes.some(request => request.requestedReviewer?.login === viewer),
72
+ });
73
+ if (query) {
74
+ const data = await api(scope, github, `query($q:String!){viewer{login} search(type:ISSUE,first:50,query:$q){nodes{... on PullRequest{${listFields} repository{nameWithOwner}}}}}`, { q: `repo:${repo} is:pr in:title sort:updated-desc ${query}` });
75
+ return data.search.nodes.filter((node) => node.repository?.nameWithOwner.toLowerCase() === repo.toLowerCase()).map(item(data.viewer.login));
104
76
  }
105
- return { ...details, ...ref, mergeMethods, ...(headRepository ? { headRepository: headRepository.nameWithOwner } : {}), author: author?.login ?? "[deleted]", viewerCanComment, comments, reviews, threads, statusCheckRollup };
77
+ const data = await api(scope, github, `query($owner:String!,$name:String!){viewer{login} repository(owner:$owner,name:$name){pullRequests(states:OPEN,first:100,orderBy:{field:UPDATED_AT,direction:DESC}){nodes{${listFields}}}}}`, { owner: owner, name: name });
78
+ return data.repository.pullRequests.nodes.map(item(data.viewer.login)).sort((a, b) => Number(b.reviewRequested) - Number(a.reviewRequested));
106
79
  }
107
80
  async function git(scope, args) {
108
81
  const result = await run(scope, args, GIT_WRITE_TIMEOUT_MS);
@@ -117,39 +90,105 @@ export async function pullBranch(scope, branch) {
117
90
  throw new Error("The branch has changed. Refresh Git status before pulling.");
118
91
  await git(scope, ["pull", "--ff-only", "--no-rebase", "--no-autostash", "--no-squash"]);
119
92
  }
120
- export async function changePullRequest(scope, action, input, github = gh) {
93
+ export async function createPullRequest(scope, input, github = gh) {
94
+ if (typeof input.title !== "string" || !input.title.trim() || typeof input.body !== "string")
95
+ throw new Error("Enter a pull request title.");
96
+ const { branch, head, repository } = await pushTarget(scope, github);
97
+ if (head !== input.head)
98
+ throw new Error("HEAD moved after the branch was read. Read it again.");
99
+ if (await remoteHead(scope, repository.remote, branch) !== head)
100
+ throw new Error(`Push the branch first. ${repository.remote} does not have the current HEAD of ${branch}.`);
101
+ const existing = await resolvePullRequest(scope, repository, branch, github);
102
+ if (existing?.state === "OPEN")
103
+ throw new Error(`Pull request #${existing.number} is already open for ${branch}.`);
104
+ const stack = await localStack(scope, branch);
105
+ const base = stack ? stackParent(stack, branch) : repository.base.defaultBranch;
106
+ const owner = repository.head.repo.split("/")[0];
107
+ 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();
108
+ }
109
+ function validId(value) { return typeof value === "string" && /^[A-Za-z0-9_+/=-]+$/.test(value) && value.length <= 256; }
110
+ function validate(ref) {
111
+ 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))
112
+ throw new Error("Invalid pull request reference.");
113
+ }
114
+ export const projectTarget = async (scope, ref, github) => {
115
+ validate(ref);
116
+ const repository = await resolveRepository(scope, undefined, github);
117
+ const pr = ref.repo === repository.base.repo ? await pullRequestByNumber(scope, ref.repo, ref.number, github) : undefined;
118
+ if (!pr || pr.id !== ref.id)
119
+ throw new Error("The pull request has changed. Reload it before continuing.");
120
+ return pr;
121
+ };
122
+ export async function remoteUrl(scope, repo) {
123
+ for (const remote of (await git(scope, ["remote"])).split("\n").filter(Boolean)) {
124
+ const url = await git(scope, ["remote", "get-url", remote]);
125
+ if (githubRepository(url)?.toLowerCase() === repo.toLowerCase())
126
+ return { remote, url };
127
+ }
128
+ return { url: `https://github.com/${repo}.git` };
129
+ }
130
+ export async function fetchBranch(scope, remote, branch) {
131
+ await git(scope, ["check-ref-format", `refs/heads/${branch}`]);
132
+ await git(scope, ["fetch", "--no-tags", remote, `+refs/heads/${branch}:refs/remotes/${remote}/${branch}`]);
133
+ return await git(scope, ["rev-parse", `refs/remotes/${remote}/${branch}`]);
134
+ }
135
+ export async function dropUnchangedBranch(scope, branch, oid) {
136
+ const current = await run(scope, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`], GIT_READ_TIMEOUT_MS);
137
+ if (current.ok && current.value.trim() === oid)
138
+ await run(scope, ["branch", "-D", "--", branch], GIT_WRITE_TIMEOUT_MS);
139
+ }
140
+ const hasCommit = async (scope, oid) => (await run(scope, ["cat-file", "-e", `${oid}^{commit}`], GIT_READ_TIMEOUT_MS)).ok;
141
+ export async function pullRequestRange(scope, ref, github = gh) {
142
+ validate(ref);
143
+ const pr = await projectTarget(scope, ref, github);
144
+ if (!await hasCommit(scope, pr.headRefOid) || !await hasCommit(scope, pr.baseRefOid)) {
145
+ await git(scope, ["check-ref-format", `refs/heads/${pr.baseBranch}`]);
146
+ await git(scope, ["fetch", "--no-tags", "--no-write-fetch-head", (await remoteUrl(scope, pr.repo)).url, `refs/pull/${pr.number}/head`, `refs/heads/${pr.baseBranch}`]);
147
+ if (!await hasCommit(scope, pr.headRefOid) || !await hasCommit(scope, pr.baseRefOid))
148
+ throw new Error("The pull request has changed. Reload it before continuing.");
149
+ }
150
+ return { base: pr.baseRefOid, head: pr.headRefOid, pr };
151
+ }
152
+ async function target(scope, ref, github) {
153
+ const selected = await head(scope);
154
+ const branch = selected.ok && !selected.value.detached ? selected.value.name : undefined;
155
+ const pr = branch === undefined ? undefined : await resolvePullRequest(scope, await resolveRepository(scope, branch, github), branch, github);
156
+ if (!pr || pr.id !== ref.id || pr.number !== ref.number || pr.repo !== ref.repo)
157
+ throw new Error("The branch's pull request has changed. Reload it before continuing.");
158
+ return { ...pr, branch: branch };
159
+ }
160
+ export async function changePullRequest(scope, action, input, github = gh, find = target) {
121
161
  validate(input?.pr);
122
162
  if (action !== "rebase" && action !== "merge")
123
163
  throw new Error("Invalid pull request action.");
124
164
  if (!/^[0-9a-f]{40,64}$/.test(input.headOid) || typeof input.baseBranch !== "string")
125
165
  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)
166
+ if (action === "merge" && !["MERGE", "SQUASH", "REBASE"].includes(input.method ?? ""))
167
+ throw new Error("Invalid merge method.");
168
+ if (action === "rebase" && find !== target)
169
+ throw new Error("Rebase this pull request from an Agent Session on its branch.");
170
+ if (action === "rebase")
171
+ await cleanStack(scope);
172
+ const pr = await (action === "merge" ? find : target)(scope, input.pr, github);
173
+ if (pr.state !== "OPEN" || pr.headRefOid !== input.headOid || pr.baseBranch !== input.baseBranch)
128
174
  throw new Error("The pull request has changed. Reload it before continuing.");
129
175
  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.");
176
+ if (pr.isDraft)
177
+ throw new Error("Mark the pull request ready for review before you merge it.");
132
178
  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
179
  return;
134
180
  }
135
- await cleanStack(scope);
136
- await git(scope, ["check-ref-format", `refs/heads/${pr.baseRefName}`]);
181
+ await git(scope, ["check-ref-format", `refs/heads/${pr.baseBranch}`]);
137
182
  const before = await git(scope, ["rev-parse", "HEAD"]);
138
- let baseUrl = `https://github.com/${pr.repo}.git`;
139
- for (const remote of (await git(scope, ["remote"])).split("\n").filter(Boolean)) {
140
- 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];
142
- if (repo?.toLowerCase() === pr.repo.toLowerCase()) {
143
- baseUrl = url;
144
- break;
145
- }
146
- }
147
- await git(scope, ["fetch", "--no-tags", baseUrl, `refs/heads/${pr.baseRefName}`]);
183
+ const baseUrl = (await remoteUrl(scope, pr.repo)).url;
184
+ await git(scope, ["fetch", "--no-tags", baseUrl, `refs/heads/${pr.baseBranch}`]);
148
185
  const base = await git(scope, ["rev-parse", "FETCH_HEAD"]);
149
- const latest = await current(scope, input.pr, github);
186
+ const latest = await target(scope, input.pr, github);
187
+ if (latest.state !== "OPEN" || latest.headRefOid !== input.headOid || latest.baseBranch !== input.baseBranch)
188
+ throw new Error("The pull request has changed. Reload it before rebasing.");
150
189
  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.");
190
+ if (!branch.ok || branch.value.detached || branch.value.name !== pr.branch || await git(scope, ["rev-parse", "HEAD"]) !== before)
191
+ throw new Error("The branch has changed. Reload it before rebasing.");
153
192
  await cleanStack(scope);
154
193
  const rebased = await run(scope, ["-c", "rebase.autoStash=false", "-c", "rebase.updateRefs=false", "rebase", base], GIT_WRITE_TIMEOUT_MS);
155
194
  if (!rebased.ok) {
@@ -157,42 +196,88 @@ export async function changePullRequest(scope, action, input, github = gh) {
157
196
  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
197
  }
159
198
  }
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.");
199
+ async function requireThread(scope, pr, thread, github) {
200
+ const data = await api(scope, github, "query($thread:ID!){node(id:$thread){... on PullRequestReviewThread{pullRequest{id}}}}", { thread });
201
+ if (data.node?.pullRequest?.id !== pr.id)
202
+ throw new Error("This review thread is not on this pull request. Reload it before continuing.");
164
203
  }
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;
170
- }
171
- export async function commentPullRequest(scope, input, github = gh) {
204
+ export async function commentPullRequest(scope, input, github = gh, find = target) {
172
205
  validate(input?.pr);
173
206
  if (typeof input.body !== "string" || !input.body.trim() || (input.threadId !== undefined && !validId(input.threadId)))
174
207
  throw new Error("Invalid comment input.");
175
- const pr = await current(scope, input.pr, github);
208
+ const pr = await find(scope, input.pr, github);
176
209
  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 });
210
+ await requireThread(scope, pr, input.threadId, github);
211
+ await api(scope, github, "mutation($id:ID!,$body:String!){addPullRequestReviewThreadReply(input:{pullRequestReviewThreadId:$id,body:$body}){comment{id}}}", { id: input.threadId, body: input.body });
181
212
  }
182
- else {
183
- if (!pr.viewerCanComment)
184
- throw new Error("Cannot comment on this pull request.");
213
+ else
185
214
  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
215
  }
188
- export async function resolvePullRequestThread(scope, input, github = gh) {
216
+ export async function resolvePullRequestThread(scope, input, github = gh, find = target) {
189
217
  validate(input?.pr);
190
218
  if (!validId(input.threadId) || typeof input.resolved !== "boolean")
191
219
  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.");
220
+ await requireThread(scope, await find(scope, input.pr, github), input.threadId, github);
196
221
  const operation = input.resolved ? "resolveReviewThread" : "unresolveReviewThread";
197
- await api(scope, github, `mutation($id:ID!){${operation}(input:{threadId:$id}){thread{id}}}`, { id: thread.id });
222
+ await api(scope, github, `mutation($id:ID!){${operation}(input:{threadId:$id}){thread{id}}}`, { id: input.threadId });
223
+ }
224
+ export async function editPullRequest(scope, input, github = gh, find = target) {
225
+ validate(input?.pr);
226
+ if (typeof input.title !== "string" || !input.title.trim() || typeof input.body !== "string")
227
+ throw new Error("Enter a pull request title.");
228
+ const pr = await find(scope, input.pr, github);
229
+ 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 });
230
+ }
231
+ export async function setPullRequestDraft(scope, input, github = gh, find = target) {
232
+ validate(input?.pr);
233
+ if (typeof input.draft !== "boolean")
234
+ throw new Error("Invalid draft input.");
235
+ const pr = await find(scope, input.pr, github);
236
+ const operation = input.draft ? "convertPullRequestToDraft" : "markPullRequestReadyForReview";
237
+ await api(scope, github, `mutation($id:ID!){${operation}(input:{pullRequestId:$id}){pullRequest{id}}}`, { id: pr.id });
238
+ }
239
+ export async function rerunPullRequestChecks(scope, input, github = gh, find = target) {
240
+ validate(input?.pr);
241
+ if (!Number.isSafeInteger(input.runId) || input.runId < 1)
242
+ throw new Error("Invalid run ID.");
243
+ const pr = await find(scope, input.pr, github);
244
+ const run = JSON.parse(await github(scope, ["api", `repos/${pr.repo}/actions/runs/${input.runId}`]));
245
+ if (run.head_sha !== pr.headRefOid)
246
+ throw new Error("This run is not for the current head of the pull request. Reload it before you re-run checks.");
247
+ await github(scope, ["run", "rerun", String(input.runId), "--failed", "--repo", pr.repo]);
248
+ }
249
+ const checkLogLines = 80;
250
+ export async function checkLog(scope, ref, jobId, github = gh, find = target) {
251
+ validate(ref);
252
+ if (!Number.isSafeInteger(jobId) || jobId < 1)
253
+ throw new Error("Invalid job ID.");
254
+ const pr = await find(scope, ref, github);
255
+ const job = JSON.parse(await github(scope, ["api", `repos/${pr.repo}/actions/jobs/${jobId}`]));
256
+ if (job.head_sha !== pr.headRefOid)
257
+ throw new Error("This job is not for the current head of the pull request. Reload it before you add its log.");
258
+ let log;
259
+ try {
260
+ log = await github(scope, ["api", `repos/${pr.repo}/actions/jobs/${jobId}/logs`, "--allow-escape-sequences"]);
261
+ }
262
+ catch {
263
+ return null;
264
+ }
265
+ const lines = log.replace(/\s+$/, "").split(/\r\n?|\n/).map(line => line
266
+ .replaceAll("\ufeff", "")
267
+ .replace(/^\d{4}-\d\d-\d\dT[\d:.]+Z ?/, "")
268
+ .replace(/\u001b(?:\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|\[[0-?]*[ -/]*[@-~]|[ -/]*[0-~])/g, "")
269
+ .replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, ""));
270
+ const end = lines.findLastIndex(line => line.startsWith("##[error]")) + 1 || lines.length;
271
+ const start = Math.max(0, end - checkLogLines);
272
+ return { text: lines.slice(start, end).join("\n"), truncated: start > 0 || end < lines.length };
273
+ }
274
+ const reviewEvents = ["APPROVE", "REQUEST_CHANGES", "COMMENT"];
275
+ export async function submitReview(scope, input, github = gh, find = target) {
276
+ validate(input?.pr);
277
+ if (!reviewEvents.includes(input.event) || typeof input.body !== "string")
278
+ throw new Error("Invalid review input.");
279
+ if (input.event !== "APPROVE" && !input.body.trim())
280
+ throw new Error("Enter a comment for this review.");
281
+ const pr = await find(scope, input.pr, github);
282
+ await api(scope, github, "mutation($id:ID!,$event:PullRequestReviewEvent!,$body:String){addPullRequestReview(input:{pullRequestId:$id,event:$event,body:$body}){pullRequestReview{id}}}", { id: pr.id, event: input.event, body: input.body });
198
283
  }
@@ -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
+ }