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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +11 -3
  2. package/build/backend-worker-chunks/{chunk-LO7O6NAM.mjs → chunk-JOI2POLP.mjs} +1 -1
  3. package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
  4. package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
  5. package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
  6. package/build/backend-worker-chunks/claude-GY27HBAY.mjs +35739 -0
  7. package/build/backend-worker-chunks/{pi-QNU2YE4G.mjs → pi-JV6MWPW7.mjs} +1891 -35
  8. package/build/backend-worker.mjs +25 -126
  9. package/build/workflow-runtime.cjs +12 -12
  10. package/dist/backend/claude/index.js +69 -11
  11. package/dist/backend/claude/subagents.js +11 -0
  12. package/dist/backend/claude/workflow-parent.js +1 -1
  13. package/dist/backend/fake/index.js +8 -2
  14. package/dist/backend/pi/cache-warming.js +8 -0
  15. package/dist/backend/pi/canonical-json.js +120 -0
  16. package/dist/backend/pi/compaction-model.js +3 -2
  17. package/dist/backend/pi/host-auth.js +258 -0
  18. package/dist/backend/pi/index.js +37 -12
  19. package/dist/backend/pi/model-auth.js +159 -0
  20. package/dist/backend/pi/model-catalog.js +120 -0
  21. package/dist/backend/pi/model-config.js +5 -0
  22. package/dist/backend/pi/model-selection.js +32 -0
  23. package/dist/backend/pi/work.js +9 -1
  24. package/dist/backend/pi/workflow-parent.js +1 -1
  25. package/dist/backend/pi/workflow-subagent.js +4 -3
  26. package/dist/backend/worker/entry.js +13 -1
  27. package/dist/backend/worker/index.js +69 -7
  28. package/dist/backend/worker/launcher.js +11 -4
  29. package/dist/build-id +1 -1
  30. package/dist/cli/application.js +5 -5
  31. package/dist/cli/bootstrap.js +1 -1
  32. package/dist/cli/host-control.js +1 -1
  33. package/dist/cli/install-guard.js +1 -1
  34. package/dist/cli/main.js +4 -4
  35. package/dist/cli/systemd-update.js +3 -3
  36. package/dist/cli/update.js +6 -6
  37. package/dist/cli/web-update.js +6 -6
  38. package/dist/client/reduce.js +2 -0
  39. package/dist/client/tool-summary.js +26 -15
  40. package/dist/daemon/changes.js +116 -0
  41. package/dist/daemon/commit.js +84 -0
  42. package/dist/daemon/config-store.js +3 -3
  43. package/dist/daemon/git-state.js +197 -0
  44. package/dist/daemon/github.js +54 -0
  45. package/dist/daemon/host-control-routes.js +1 -1
  46. package/dist/daemon/host.js +147 -78
  47. package/dist/daemon/log.js +3 -0
  48. package/dist/daemon/mcp-auth.js +1 -1
  49. package/dist/daemon/models.js +2 -2
  50. package/dist/daemon/pi-model-cache.js +44 -0
  51. package/dist/daemon/pull-request.js +156 -129
  52. package/dist/daemon/push.js +43 -0
  53. package/dist/daemon/repository.js +106 -0
  54. package/dist/daemon/runtime.js +27 -20
  55. package/dist/daemon/secret-store.js +1 -1
  56. package/dist/daemon/server.js +11 -10
  57. package/dist/daemon/stack-metadata.js +12 -5
  58. package/dist/daemon/stack.js +127 -656
  59. package/dist/daemon/summariser.js +19 -8
  60. package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
  61. package/dist/daemon/workflow-authoring-scope.js +1 -1
  62. package/dist/daemon/workflow-builder-files.js +2 -2
  63. package/dist/daemon/workflow-builder-routes.js +2 -2
  64. package/dist/daemon/workflow-builder.js +5 -5
  65. package/dist/daemon/workflow-environment.js +5 -5
  66. package/dist/daemon/workflow-execution-launch.js +5 -5
  67. package/dist/daemon/workflow-execution-resources.js +3 -3
  68. package/dist/daemon/workflow-execution-routes.js +3 -3
  69. package/dist/daemon/workflow-execution-values.js +5 -5
  70. package/dist/daemon/workflow-executions.js +19 -19
  71. package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
  72. package/dist/daemon/workflow-mcp-authoring.js +4 -4
  73. package/dist/daemon/workflow-mcp.js +1 -1
  74. package/dist/daemon/workflow-routes.js +3 -3
  75. package/dist/daemon/workflow-schedule-driver.js +8 -8
  76. package/dist/daemon/workflow-schedule-routes.js +5 -5
  77. package/dist/daemon/workflow-schedules.js +3 -3
  78. package/dist/isolation/filesystem.js +5 -1
  79. package/dist/isolation/sandbox.js +31 -4
  80. package/dist/isolation/toolchain-assets.js +1 -1
  81. package/dist/protocol/stack.js +1 -41
  82. package/dist/workflows/calls.js +2 -2
  83. package/dist/workflows/executors.js +3 -3
  84. package/dist/workflows/graph.js +6 -6
  85. package/dist/workflows/invocations.js +1 -1
  86. package/dist/workflows/mcp.js +1 -1
  87. package/dist/workflows/records.js +6 -6
  88. package/dist/workflows/recovery.js +2 -2
  89. package/dist/workflows/runtime-settings.js +1 -1
  90. package/dist/workflows/runtime.js +2 -2
  91. package/dist/workflows/schedule-store.js +2 -2
  92. package/dist/workflows/scheduler.js +9 -9
  93. package/dist/workflows/schema.js +1 -1
  94. package/dist/workflows/store.js +3 -3
  95. package/package.json +9 -6
  96. package/web/dist/assets/index-BqZ_iUmY.css +2 -0
  97. package/web/dist/assets/index-CxdSb7k0.js +51 -0
  98. package/web/dist/assets/{settings-mcp-Vf_fCXyE.js → settings-mcp-BwOPXAfH.js} +1 -1
  99. package/web/dist/assets/settings-workflows-DocTa31_.js +23 -0
  100. package/web/dist/assets/{switch-DIogWclb.js → switch-B00FEUA7.js} +1 -1
  101. package/web/dist/assets/{workflows-Dobqzjg-.js → workflows-DJqUuGyg.js} +41 -41
  102. package/web/dist/assets/{workflows-pane-KB-Q76KZ.js → workflows-pane-oM1fO_BC.js} +1 -1
  103. package/web/dist/index.html +4 -4
  104. package/build/backend-worker-chunks/claude-6L5KCQWJ.mjs +0 -30894
  105. package/dist/daemon/publish.js +0 -289
  106. package/dist/protocol/publish.js +0 -1
  107. package/web/dist/assets/index-BGu3YSP7.css +0 -2
  108. package/web/dist/assets/index-Miy2nveb.js +0 -40
  109. package/web/dist/assets/settings-workflows-DVKxJWQm.js +0 -23
@@ -13,17 +13,18 @@
13
13
  const MAX = 60;
14
14
  /**
15
15
  * Ordered, because a tool's input usually carries several of these and the first is the one the
16
- * question is about: a Bash call's `command` before its `description`, a Grep's `pattern` before the
17
- * directory it searched.
16
+ * question is about: the `description` a model wrote for a call before the `command` or `prompt` it
17
+ * describes, a Grep's `pattern` before the directory it searched.
18
18
  *
19
19
  * Keyed on the shape of the arguments rather than on the tool's name, because the name is the part
20
20
  * that varies: Claude's `Edit` and a pi tool that edits a file are not called the same thing, while
21
21
  * `file_path` means the same in both. An unrecognised tool with a recognisable argument still reads.
22
22
  */
23
23
  const ARGUMENTS = [
24
+ { key: "description", shape: "text" },
24
25
  { key: "command", shape: "text" },
25
- // Ahead of `description` and `prompt`, which an AskUserQuestion call does not carry but a future
26
- // asking tool might. Keyed on the argument rather than the tool's name, which is this list's rule.
26
+ // Ahead of `prompt`, which an AskUserQuestion call does not carry but a future asking tool might.
27
+ // Keyed on the argument rather than the tool's name, which is this list's rule.
27
28
  { key: "questions", shape: "questions" },
28
29
  { key: "file_path", shape: "path" },
29
30
  { key: "notebook_path", shape: "path" },
@@ -31,36 +32,46 @@ const ARGUMENTS = [
31
32
  { key: "url", shape: "text" },
32
33
  { key: "query", shape: "text" },
33
34
  { key: "path", shape: "path" },
34
- { key: "description", shape: "text" },
35
35
  { key: "prompt", shape: "text" },
36
36
  ];
37
+ const MAIN_ARGUMENTS = ARGUMENTS.filter(({ key }) => key !== "description");
37
38
  /**
38
39
  * Returns undefined when there is nothing worth saying, so a caller renders the tool's name alone
39
40
  * rather than a padded blank. `input` is `unknown` on the wire (`events.ts` — a Backend Adapter
40
41
  * passes its backend's arguments through), so every access is narrowed rather than trusted.
41
42
  */
42
43
  export function toolSummary(input) {
44
+ return summarise(input, MAX);
45
+ }
46
+ /**
47
+ * The first argument after `description`, unclipped — the command or prompt the description
48
+ * stands for — for a card that has room to wrap it.
49
+ */
50
+ export function fullToolSummary(input) {
51
+ return summarise(input, Infinity, MAIN_ARGUMENTS);
52
+ }
53
+ function summarise(input, max, args = ARGUMENTS) {
43
54
  if (!input || typeof input !== "object")
44
55
  return undefined;
45
56
  const record = input;
46
- for (const argument of ARGUMENTS) {
57
+ for (const argument of args) {
47
58
  const value = record[argument.key];
48
59
  if (argument.shape === "questions") {
49
- const asked = clipQuestions(value);
60
+ const asked = clipQuestions(value, max);
50
61
  if (asked !== undefined)
51
62
  return asked;
52
63
  continue;
53
64
  }
54
65
  if (typeof value !== "string" || value.trim() === "")
55
66
  continue;
56
- return argument.shape === "path" ? clipPath(value.trim()) : clipText(value);
67
+ return argument.shape === "path" ? clipPath(value.trim(), max) : clipText(value, max);
57
68
  }
58
69
  // The fallback: a tool nobody here has heard of, whose input is a single string, is describing
59
70
  // itself with that string. Two or more and there is no way to know which one matters, so say
60
71
  // nothing rather than pick.
61
72
  const strings = Object.values(record).filter((value) => typeof value === "string");
62
73
  const only = strings.length === 1 ? strings[0] : undefined;
63
- return only && only.trim() !== "" ? clipText(only) : undefined;
74
+ return only && only.trim() !== "" ? clipText(only, max) : undefined;
64
75
  }
65
76
  /**
66
77
  * The first question asked, and how many others came with it.
@@ -72,7 +83,7 @@ export function toolSummary(input) {
72
83
  * The front-ends suppress this row where an Enquiry Entry stands beside it, so what this actually
73
84
  * serves is the case where one does not: a Subagent's Enquiry, seen from the Agents tab.
74
85
  */
75
- function clipQuestions(value) {
86
+ function clipQuestions(value, max) {
76
87
  if (!Array.isArray(value) || value.length === 0)
77
88
  return undefined;
78
89
  const first = value[0];
@@ -84,15 +95,15 @@ function clipQuestions(value) {
84
95
  const rest = value.length - 1;
85
96
  // Clipped after the count is appended, not before, so the whole précis obeys MAX rather than
86
97
  // MAX-plus-however-long-the-suffix-turned-out-to-be.
87
- return clipText(rest > 0 ? `${asked} (+${rest} more)` : asked);
98
+ return clipText(rest > 0 ? `${asked} (+${rest} more)` : asked, max);
88
99
  }
89
100
  /** Whitespace collapsed so a heredoc or a multi-line prompt still occupies one line. */
90
- function clipText(value) {
101
+ function clipText(value, max) {
91
102
  const text = value.replace(/\s+/g, " ").trim();
92
- return text.length <= MAX ? text : `${text.slice(0, MAX - 1)}…`;
103
+ return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
93
104
  }
94
- function clipPath(path) {
105
+ function clipPath(path, max) {
95
106
  // The tail of a path is what identifies the file; the leading directories are what a reader can
96
107
  // afford to lose, which is the opposite of how everything else here truncates.
97
- return path.length <= MAX ? path : `…${path.slice(-(MAX - 1))}`;
108
+ return path.length <= max ? path : `…${path.slice(-(max - 1))}`;
98
109
  }
@@ -0,0 +1,116 @@
1
+ import { lstat, readFile, readlink } from "node:fs/promises";
2
+ import { resolve } from "node:path";
3
+ import { head, run, GIT_READ_TIMEOUT_MS } from "./git.js";
4
+ import { gh } from "./github.js";
5
+ import { git, localRepository, resolveRepository } from "./repository.js";
6
+ import { readStatus } from "./git-state.js";
7
+ import { localStack, localStacks, stackParent } from "./stack-metadata.js";
8
+ const SIDE_LIMIT = 250_000;
9
+ const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
10
+ async function files(scope) {
11
+ return (await readStatus(scope)).files;
12
+ }
13
+ async function baseRef(scope, remote, branch, preferLocal) {
14
+ const refs = [`refs/heads/${branch}`, `refs/remotes/${remote}/${branch}`];
15
+ for (const ref of preferLocal ? refs : refs.reverse()) {
16
+ if ((await run(scope, ["rev-parse", "--verify", "--quiet", ref], GIT_READ_TIMEOUT_MS)).ok)
17
+ return ref;
18
+ }
19
+ return undefined;
20
+ }
21
+ async function rangeFiles(scope, base) {
22
+ const raw = (await git(scope, ["diff", "--name-status", "-z", "--no-renames", `${base}...HEAD`, "--"])).split("\0").filter(Boolean);
23
+ const files = [];
24
+ for (let index = 0; index < raw.length; index += 2)
25
+ files.push({ status: raw[index], path: raw[index + 1] });
26
+ return files;
27
+ }
28
+ async function rangeCommits(scope, base) {
29
+ return (await git(scope, ["log", "--format=%h %s", `${base}..HEAD`, "--"])).trim().split("\n").filter(Boolean);
30
+ }
31
+ async function branchBase(scope, pullRequestBase, github) {
32
+ const current = await head(scope);
33
+ const branch = current.ok && !current.value.detached ? current.value.name : undefined;
34
+ const repository = await resolveRepository(scope, branch, github);
35
+ const stack = branch === undefined ? undefined : await localStack(scope, branch);
36
+ const parent = stack && stackParent(stack, branch);
37
+ const name = (branch === undefined ? undefined : pullRequestBase?.(branch)) ?? parent ?? repository.base.defaultBranch;
38
+ const ref = await baseRef(scope, repository.remote, name, name === parent);
39
+ if (!ref)
40
+ throw new Error(`The base branch ${name} is not known locally. Fetch ${name} from ${repository.remote} to show the branch changes.`);
41
+ return ref;
42
+ }
43
+ export async function changes(scope, view, pullRequestBase, github = gh) {
44
+ if (view !== "branch")
45
+ return { files: await files(scope), commits: [] };
46
+ const base = await branchBase(scope, pullRequestBase, github);
47
+ return { files: await rangeFiles(scope, base), commits: await rangeCommits(scope, base), base: base.replace(/^refs\/(heads|remotes)\//, "") };
48
+ }
49
+ function added(path, content) {
50
+ const lines = content.match(/[^\n]*\n|[^\n]+$/g) ?? [];
51
+ const hunk = lines.length === 0 ? "" : `@@ -0,0 +1,${lines.length} @@\n${lines.map(line => `+${line}`).join("")}${content.endsWith("\n") ? "" : "\n\\n"}`;
52
+ return `--- /dev/null\n+++ b/${path}\n${hunk}`;
53
+ }
54
+ async function untracked(scope, path) {
55
+ const full = resolve(scope, path);
56
+ const stat = await lstat(full);
57
+ if (stat.isSymbolicLink())
58
+ return { text: added(path, await readlink(full)) };
59
+ if (!stat.isFile())
60
+ return { binary: true };
61
+ if (stat.size > SIDE_LIMIT)
62
+ return { tooLarge: true };
63
+ const content = await readFile(full);
64
+ if (content.includes(0))
65
+ return { binary: true };
66
+ return { text: added(path, content.toString("utf8")) };
67
+ }
68
+ async function blobSize(scope, object) {
69
+ const size = await run(scope, ["cat-file", "-s", object], GIT_READ_TIMEOUT_MS);
70
+ return size.ok ? Number(size.value) : 0;
71
+ }
72
+ export async function diff(scope, view, path, pullRequestBase, github = gh) {
73
+ const base = view === "branch" ? await branchBase(scope, pullRequestBase, github) : undefined;
74
+ const listed = base ? await rangeFiles(scope, base) : await files(scope);
75
+ const file = listed.find(item => item.path === path);
76
+ if (!file)
77
+ throw new Error("This file is not in the list of changes. Read the list again.");
78
+ if (file.status === "??")
79
+ return untracked(scope, path);
80
+ const from = base ? (await git(scope, ["merge-base", base, "HEAD"])).trim() : (await run(scope, ["rev-parse", "--verify", "--quiet", "HEAD"], GIT_READ_TIMEOUT_MS)).ok ? "HEAD" : EMPTY_TREE;
81
+ const oldSize = await blobSize(scope, `${from}:${path}`);
82
+ const newSize = base ? await blobSize(scope, `HEAD:${path}`) : (await lstat(resolve(scope, path)).catch(() => undefined))?.size ?? 0;
83
+ if (oldSize > SIDE_LIMIT || newSize > SIDE_LIMIT)
84
+ return { tooLarge: true };
85
+ const range = base ? [from, "HEAD"] : [from];
86
+ const numstat = await git(scope, ["--literal-pathspecs", "diff", "--numstat", ...range, "--", path]);
87
+ if (numstat.startsWith("-\t-\t"))
88
+ return { binary: true };
89
+ return { text: await git(scope, ["--literal-pathspecs", "diff", "--no-color", "--no-ext-diff", "--no-relative", "--src-prefix=a/", "--dst-prefix=b/", ...range, "--", path]) };
90
+ }
91
+ export async function canNameBranch(scope, branch, remote, pullRequest) {
92
+ if (pullRequest)
93
+ return false;
94
+ if ((await localStacks(scope)).some(stack => stack.trunk.branch === branch || stack.branches.some(item => item.branch === branch)))
95
+ return false;
96
+ return !(await run(scope, ["show-ref", "--verify", "--quiet", `refs/remotes/${remote}/${branch}`], GIT_READ_TIMEOUT_MS)).ok;
97
+ }
98
+ export async function commitContext(scope, branch, pullRequest) {
99
+ const repository = await localRepository(scope, branch).catch(() => undefined);
100
+ const defaultBranch = repository?.defaultBranches[0];
101
+ const canRename = Boolean(branch && repository?.github && defaultBranch && !repository.defaultBranches.includes(branch) && await canNameBranch(scope, branch, repository.remote, pullRequest(branch)));
102
+ return { ...(branch ? { branch } : {}), ...(defaultBranch ? { defaultBranch } : {}), canRename };
103
+ }
104
+ export async function changesText(scope, view, paths, pullRequestBase, github = gh) {
105
+ const listed = await changes(scope, view, pullRequestBase, github);
106
+ let text = listed.commits.length > 0 ? `Commits:\n${listed.commits.join("\n")}\n` : "";
107
+ for (const file of listed.files) {
108
+ if (text.length > 24_000)
109
+ break;
110
+ if (paths && !paths.includes(file.path))
111
+ continue;
112
+ const shown = await diff(scope, view, file.path, pullRequestBase, github);
113
+ text += "text" in shown ? shown.text : `${file.status} ${file.path}: no text diff\n`;
114
+ }
115
+ return text;
116
+ }
@@ -0,0 +1,84 @@
1
+ import { access } from "node:fs/promises";
2
+ import { resolve } from "node:path";
3
+ import { run, GIT_READ_TIMEOUT_MS } from "./git.js";
4
+ import { canNameBranch } from "./changes.js";
5
+ import { readStatus } from "./git-state.js";
6
+ import { gh } from "./github.js";
7
+ import { remoteHead } from "./push.js";
8
+ import { git, localRepository, resolvePullRequest, resolveRepository } from "./repository.js";
9
+ async function refuseOperation(scope) {
10
+ if ((await readStatus(scope)).files.some(file => file.status.includes("U") || ["AA", "DD"].includes(file.status)))
11
+ throw new Error("Resolve the merge conflicts before you commit.");
12
+ for (const operation of ["MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD"]) {
13
+ if ((await run(scope, ["rev-parse", "--verify", "-q", operation], GIT_READ_TIMEOUT_MS)).ok)
14
+ throw new Error("Finish the current Git operation before you commit.");
15
+ }
16
+ for (const operation of ["rebase-merge", "rebase-apply", "sequencer"]) {
17
+ const path = (await git(scope, ["rev-parse", "--git-path", operation])).trim();
18
+ if (await access(resolve(scope, path)).then(() => true, () => false))
19
+ throw new Error("Finish the current Git operation before you commit.");
20
+ }
21
+ }
22
+ async function refuseBranchName(scope, name, repository) {
23
+ if (name.startsWith("-") || name.includes("@{") || repository?.defaultBranches.includes(name))
24
+ throw new Error(`${name} is not a valid new branch name.`);
25
+ await git(scope, ["check-ref-format", "--branch", name]);
26
+ if ((await run(scope, ["show-ref", "--verify", "--quiet", `refs/heads/${name}`], GIT_READ_TIMEOUT_MS)).ok)
27
+ throw new Error(`The branch ${name} already exists. Enter a new name.`);
28
+ if (repository && await remoteHead(scope, repository.remote, name))
29
+ throw new Error(`The branch ${name} already exists on ${repository.remote}. Enter a new name.`);
30
+ }
31
+ async function renameAllowed(scope, branch, repository, github) {
32
+ if (!repository?.github)
33
+ return false;
34
+ const pullRequest = await resolvePullRequest(scope, await resolveRepository(scope, branch, github), branch, github);
35
+ return await canNameBranch(scope, branch, repository.remote, pullRequest !== undefined) && !await remoteHead(scope, repository.remote, branch);
36
+ }
37
+ export async function commit(scope, input, github = gh) {
38
+ if (typeof input.message !== "string" || !input.message.trim())
39
+ throw new Error("Enter a commit message.");
40
+ if (!Array.isArray(input.paths) || input.paths.length === 0 || input.paths.some(path => typeof path !== "string"))
41
+ throw new Error("Select at least one file to commit.");
42
+ await refuseOperation(scope);
43
+ const reviewed = await readStatus(scope);
44
+ const changed = "The changes changed after the list was read. Read the list again.";
45
+ if (reviewed.fingerprint !== input.fingerprint)
46
+ throw new Error(changed);
47
+ const paths = new Set(input.paths);
48
+ if ([...paths].some(path => !reviewed.files.some(file => file.path === path)))
49
+ throw new Error("A selected file is not in the list of changes. Read the list again.");
50
+ const branch = reviewed.local.branch;
51
+ const repository = await localRepository(scope, branch);
52
+ if (repository?.github && repository.defaultBranches.length === 0)
53
+ throw new Error(`The default branch of ${repository.remote} is not known. Refresh when GitHub answers, or run git remote set-head ${repository.remote} --auto.`);
54
+ const creating = branch === undefined || repository?.defaultBranches.includes(branch) === true;
55
+ const name = typeof input.branch === "string" ? input.branch.trim() : "";
56
+ if (creating && (!name || name === branch))
57
+ throw new Error(branch ? `${branch} is the default branch. Enter a new branch name.` : "HEAD is detached. Enter a new branch name.");
58
+ if (name && name !== branch) {
59
+ await refuseBranchName(scope, name, repository);
60
+ if (!creating && !await renameAllowed(scope, branch, repository, github))
61
+ throw new Error(`${branch} has a pull request, a remote branch or a stack registration, so it cannot be renamed.`);
62
+ await git(scope, creating ? ["switch", "--quiet", "-c", name] : ["branch", "-m", name], true);
63
+ }
64
+ if ((await readStatus(scope)).fingerprint !== input.fingerprint)
65
+ throw new Error(name && name !== branch ? `The branch ${name} is ready, but the changes changed. Read the list again.` : changed);
66
+ const untracked = reviewed.files.filter(file => file.status === "??" && paths.has(file.path)).map(file => file.path);
67
+ try {
68
+ if (untracked.length > 0)
69
+ await git(scope, ["--literal-pathspecs", "add", "--intent-to-add", "--", ...untracked], true);
70
+ await git(scope, ["--literal-pathspecs", "commit", "--quiet", "-m", input.message, "--", ...paths], true);
71
+ }
72
+ catch (error) {
73
+ if (untracked.length > 0)
74
+ await run(scope, ["--literal-pathspecs", "rm", "--cached", "--quiet", "--ignore-unmatch", "--", ...untracked], GIT_READ_TIMEOUT_MS);
75
+ throw error;
76
+ }
77
+ const [created, ...parents] = (await git(scope, ["rev-list", "--parents", "-n", "1", "HEAD"])).trim().split(" ");
78
+ if (parents.join(" ") !== (reviewed.local.head ?? ""))
79
+ throw new Error(`Commit ${created.slice(0, 7)} was created, but its parent is not the commit that was read. Review the commit before you push.`);
80
+ const committed = (await git(scope, ["diff-tree", "-r", "-z", "--name-only", "--no-renames", "--no-commit-id", "--root", "HEAD"])).split("\0").filter(Boolean);
81
+ if (committed.length !== paths.size || committed.some(path => !paths.has(path)))
82
+ throw new Error(`Commit ${created.slice(0, 7)} was created, but it does not contain exactly the selected files. Review the commit before you push.`);
83
+ return created;
84
+ }
@@ -1,9 +1,9 @@
1
1
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { applyPatch, formatDuration, loadConfig, } from "./config.js";
4
- import { DEFAULT_WORKFLOW_RUNTIME } from "../protocol/settings.js";
5
- import { detectFilesystemIsolationSupport, } from "../isolation/support.js";
6
- import { detectSandboxSupport } from "../isolation/sandbox.js";
4
+ import { DEFAULT_WORKFLOW_RUNTIME } from '../protocol/settings.js';
5
+ import { detectFilesystemIsolationSupport, } from '../isolation/support.js';
6
+ import { detectSandboxSupport } from '../isolation/sandbox.js';
7
7
  import { expandHome } from "./projects.js";
8
8
  import { defaultStateRoot } from "./store.js";
9
9
  /**
@@ -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;