@nathanstephenson/flow 0.1.10-beta.1 → 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 (170) hide show
  1. package/README.md +52 -22
  2. package/build/backend-worker-chunks/{chunk-CYE5L6Z5.mjs → chunk-3KDHJA5P.mjs} +41 -10
  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-UKRC4DDM.mjs → pi-KJSP23AO.mjs} +2091 -92
  8. package/build/backend-worker.mjs +69 -122
  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 +188 -25
  13. package/dist/backend/claude/subagents.js +41 -9
  14. package/dist/backend/claude/todo-list.js +114 -0
  15. package/dist/backend/claude/workflow-parent.js +1 -1
  16. package/dist/backend/diff-excerpt-instructions.js +8 -0
  17. package/dist/backend/fake/index.js +54 -6
  18. package/dist/backend/mcp.js +4 -1
  19. package/dist/backend/pi/agent-permissions.js +1 -1
  20. package/dist/backend/pi/cache-warming.js +8 -0
  21. package/dist/backend/pi/canonical-json.js +120 -0
  22. package/dist/backend/pi/compaction-model.js +3 -2
  23. package/dist/backend/pi/host-auth.js +258 -0
  24. package/dist/backend/pi/import.js +269 -0
  25. package/dist/backend/pi/index.js +118 -20
  26. package/dist/backend/pi/model-auth.js +159 -0
  27. package/dist/backend/pi/model-catalog.js +120 -0
  28. package/dist/backend/pi/model-config.js +5 -0
  29. package/dist/backend/pi/model-selection.js +32 -0
  30. package/dist/backend/pi/plan-limits.js +41 -0
  31. package/dist/backend/pi/state.js +19 -1
  32. package/dist/backend/pi/subagents.js +7 -3
  33. package/dist/backend/pi/todo-list.js +23 -0
  34. package/dist/backend/pi/work.js +9 -1
  35. package/dist/backend/pi/workflow-parent.js +1 -1
  36. package/dist/backend/pi/workflow-subagent.js +4 -3
  37. package/dist/backend/plan-limits.js +17 -0
  38. package/dist/backend/session-tools.js +1 -1
  39. package/dist/backend/worker/claude-state.js +48 -0
  40. package/dist/backend/worker/entry.js +42 -8
  41. package/dist/backend/worker/index.js +131 -15
  42. package/dist/backend/worker/launcher.js +11 -4
  43. package/dist/backend/worker/protocol.js +2 -1
  44. package/dist/backend/worker/rpc.js +13 -0
  45. package/dist/backend/worker/sandbox-mcp.js +18 -7
  46. package/dist/backend/workflow-tools.js +9 -7
  47. package/dist/build-id +1 -1
  48. package/dist/cli/application.js +48 -42
  49. package/dist/cli/bootstrap.js +2 -2
  50. package/dist/cli/host-control.js +1 -1
  51. package/dist/cli/install-guard.js +2 -2
  52. package/dist/cli/main.js +4 -4
  53. package/dist/cli/systemd-update.js +3 -3
  54. package/dist/cli/update.js +6 -6
  55. package/dist/cli/web-update.js +6 -6
  56. package/dist/client/connection.js +46 -0
  57. package/dist/client/context-usage.js +3 -4
  58. package/dist/client/diff.js +40 -0
  59. package/dist/client/enquiry.js +0 -6
  60. package/dist/client/markdown.js +3 -2
  61. package/dist/client/model-choices.js +1 -1
  62. package/dist/client/permission.js +1 -2
  63. package/dist/client/project-name.js +3 -1
  64. package/dist/client/reduce.js +77 -3
  65. package/dist/client/relative-time.js +1 -1
  66. package/dist/client/scope-kind.js +6 -3
  67. package/dist/client/search.js +1 -1
  68. package/dist/client/status.js +1 -1
  69. package/dist/client/subagent-tree.js +49 -0
  70. package/dist/client/tool-chains.js +1 -1
  71. package/dist/client/tool-summary.js +28 -18
  72. package/dist/daemon/changes.js +128 -0
  73. package/dist/daemon/commit.js +84 -0
  74. package/dist/daemon/config-store.js +8 -3
  75. package/dist/daemon/config.js +105 -4
  76. package/dist/daemon/diff-excerpts.js +52 -0
  77. package/dist/daemon/git-state.js +197 -0
  78. package/dist/daemon/git.js +53 -10
  79. package/dist/daemon/github-image.js +18 -0
  80. package/dist/daemon/github.js +54 -0
  81. package/dist/daemon/host-control-routes.js +1 -1
  82. package/dist/daemon/host.js +940 -119
  83. package/dist/daemon/http.js +4 -1
  84. package/dist/daemon/log.js +3 -0
  85. package/dist/daemon/mcp-auth.js +1 -1
  86. package/dist/daemon/models.js +2 -2
  87. package/dist/daemon/pi-model-cache.js +44 -0
  88. package/dist/daemon/pull-request.js +223 -138
  89. package/dist/daemon/push.js +43 -0
  90. package/dist/daemon/repository.js +123 -0
  91. package/dist/daemon/runtime.js +103 -22
  92. package/dist/daemon/secret-store.js +1 -1
  93. package/dist/daemon/server.js +111 -14
  94. package/dist/daemon/skills.js +24 -0
  95. package/dist/daemon/spend-ledger.js +118 -0
  96. package/dist/daemon/stack-metadata.js +12 -5
  97. package/dist/daemon/stack.js +162 -657
  98. package/dist/daemon/store.js +2 -0
  99. package/dist/daemon/summariser.js +30 -12
  100. package/dist/daemon/tour.js +56 -0
  101. package/dist/daemon/whisper.js +144 -0
  102. package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
  103. package/dist/daemon/workflow-authoring-scope.js +1 -1
  104. package/dist/daemon/workflow-builder-files.js +2 -2
  105. package/dist/daemon/workflow-builder-guidance.js +1 -1
  106. package/dist/daemon/workflow-builder-routes.js +2 -2
  107. package/dist/daemon/workflow-builder.js +44 -17
  108. package/dist/daemon/workflow-environment.js +193 -0
  109. package/dist/daemon/workflow-execution-launch.js +77 -0
  110. package/dist/daemon/workflow-execution-resources.js +76 -0
  111. package/dist/daemon/workflow-execution-routes.js +12 -9
  112. package/dist/daemon/workflow-execution-values.js +128 -0
  113. package/dist/daemon/workflow-executions.js +400 -311
  114. package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
  115. package/dist/daemon/workflow-mcp-authoring.js +4 -4
  116. package/dist/daemon/workflow-mcp.js +1 -1
  117. package/dist/daemon/workflow-routes.js +60 -2
  118. package/dist/daemon/workflow-schedule-driver.js +251 -0
  119. package/dist/daemon/workflow-schedule-routes.js +137 -0
  120. package/dist/daemon/workflow-schedules.js +342 -0
  121. package/dist/isolation/filesystem.js +6 -2
  122. package/dist/isolation/sandbox.js +61 -18
  123. package/dist/isolation/shared-sandbox.js +3 -3
  124. package/dist/isolation/toolchain-assets.js +1 -1
  125. package/dist/protocol/events.js +3 -0
  126. package/dist/protocol/plan-limits.js +1 -0
  127. package/dist/protocol/settings.js +1 -0
  128. package/dist/protocol/spend.js +2 -0
  129. package/dist/protocol/stack.js +12 -39
  130. package/dist/protocol/workflow-schedules.js +1 -0
  131. package/dist/workflows/calls.js +53 -0
  132. package/dist/workflows/errors.js +2 -0
  133. package/dist/workflows/executors.js +6 -5
  134. package/dist/workflows/graph.js +83 -9
  135. package/dist/workflows/invocations.js +23 -0
  136. package/dist/workflows/mcp.js +1 -1
  137. package/dist/workflows/owner.js +45 -0
  138. package/dist/workflows/records.js +127 -11
  139. package/dist/workflows/recovery.js +38 -2
  140. package/dist/workflows/runtime-settings.js +16 -16
  141. package/dist/workflows/runtime.js +2 -2
  142. package/dist/workflows/schedule-errors.js +2 -0
  143. package/dist/workflows/schedule-store.js +385 -0
  144. package/dist/workflows/scheduler.js +367 -96
  145. package/dist/workflows/schedules.js +130 -0
  146. package/dist/workflows/schema.js +3 -1
  147. package/dist/workflows/store.js +126 -13
  148. package/package.json +10 -6
  149. package/web/dist/assets/index-C76t-z4w.css +2 -0
  150. package/web/dist/assets/{index-DRfeO6GJ.js → index-WPfbYVQ4.js} +39 -23
  151. package/web/dist/assets/{switch-DIogWclb.js → select-C5Ly2OpB.js} +1 -1
  152. package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-BF-yqpeQ.js} +1 -1
  153. package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-WLarr2QP.js} +1 -1
  154. package/web/dist/assets/settings-workflows-DdcdRWFD.js +23 -0
  155. package/web/dist/assets/workflow-api-GjAmHc22.js +6 -0
  156. package/web/dist/assets/workflows-BhY3Uibo.js +149 -0
  157. package/web/dist/assets/workflows-pane-DElCcEpN.js +1 -0
  158. package/web/dist/index.html +6 -5
  159. package/build/backend-worker-chunks/claude-UXZDJKZQ.mjs +0 -30816
  160. package/dist/daemon/publish.js +0 -289
  161. package/dist/tui/app.js +0 -612
  162. package/dist/tui/keys.js +0 -90
  163. package/dist/tui/render.js +0 -411
  164. package/web/dist/assets/index-DgQFpKbn.css +0 -2
  165. package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
  166. package/web/dist/assets/workflow-api-BfExddae.js +0 -6
  167. package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
  168. package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
  169. package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
  170. /package/dist/protocol/{publish.js → imports.js} +0 -0
@@ -2,7 +2,8 @@ import { mcpConnectionsSchema } from "../protocol/mcp.js";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { DEFAULT_CHROME_FONT, DEFAULT_MONOSPACE_FONT, defaultFonts, } from "../protocol/fonts.js";
5
- import { DEFAULT_WORKFLOW_RUNTIME, formatDuration, parseDuration, } from "../protocol/settings.js";
5
+ import { DEFAULT_WORKFLOW_RUNTIME, WHISPER_MODELS, formatDuration, parseDuration, } from "../protocol/settings.js";
6
+ import { EFFORT_ORDER } from "../backend/effort.js";
6
7
  export { DEFAULT_CHROME_FONT, DEFAULT_MONOSPACE_FONT };
7
8
  export { formatDuration, parseDuration };
8
9
  export const DEFAULT_SETTLED_RETENTION = 24 * 60 * 60 * 1000;
@@ -34,6 +35,8 @@ export function loadConfig(stateRoot) {
34
35
  const filesystemIsolation = readFilesystemIsolation(parsed, warnings);
35
36
  const sandboxSharing = readSandboxSharing(parsed, warnings);
36
37
  const updateChannel = readUpdateChannel(parsed, warnings);
38
+ const worktrees = readWorktrees(parsed, warnings);
39
+ const dictation = readDictation(parsed, warnings);
37
40
  return {
38
41
  config: {
39
42
  retention,
@@ -43,6 +46,8 @@ export function loadConfig(stateRoot) {
43
46
  ...(updateChannel === undefined ? {} : { updateChannel }),
44
47
  mcp: readMcp(parsed, warnings),
45
48
  workflowRuntime: readWorkflowRuntime(parsed, warnings),
49
+ ...(worktrees === undefined ? {} : { worktrees }),
50
+ ...(dictation === undefined ? {} : { dictation }),
46
51
  ...(projects === undefined ? {} : { projects }),
47
52
  ...(permissions === undefined ? {} : { permissions }),
48
53
  ...(providers === undefined ? {} : { providers }),
@@ -144,6 +149,70 @@ function patchSandboxSharing(current, value) {
144
149
  throw new ConfigError('sandboxSharing must be "session" or "shared"');
145
150
  return value;
146
151
  }
152
+ const worktreeKeys = ["always", "updateSource"];
153
+ function readWorktrees(parsed, warnings) {
154
+ try {
155
+ return patchWorktrees(undefined, parsed?.worktrees);
156
+ }
157
+ catch (error) {
158
+ warnings.push(`${error.message}; using defaults`);
159
+ return undefined;
160
+ }
161
+ }
162
+ function patchWorktrees(current, value) {
163
+ if (value === undefined)
164
+ return current;
165
+ if (typeof value !== "object" || value === null || Array.isArray(value))
166
+ throw new ConfigError("worktrees must be an object");
167
+ refuseUnknownKeys(value, worktreeKeys, "worktrees");
168
+ const next = { ...current };
169
+ for (const key of worktreeKeys) {
170
+ const flag = value[key];
171
+ if (flag === undefined)
172
+ continue;
173
+ if (typeof flag !== "boolean")
174
+ throw new ConfigError(`worktrees.${key} must be true or false`);
175
+ next[key] = flag;
176
+ }
177
+ return next;
178
+ }
179
+ const dictationEngines = ["off", "browser", "whisper"];
180
+ function readDictation(parsed, warnings) {
181
+ try {
182
+ return patchDictation(undefined, parsed?.dictation);
183
+ }
184
+ catch (error) {
185
+ warnings.push(`${error.message}; using defaults`);
186
+ return undefined;
187
+ }
188
+ }
189
+ function patchDictation(current, value) {
190
+ if (value === undefined)
191
+ return current;
192
+ if (typeof value !== "object" || value === null || Array.isArray(value))
193
+ throw new ConfigError("dictation must be an object");
194
+ refuseUnknownKeys(value, ["engine", "model", "whisperServer"], "dictation");
195
+ const { engine, model, whisperServer } = value;
196
+ const next = { ...current };
197
+ if (engine !== undefined) {
198
+ if (!dictationEngines.includes(engine))
199
+ throw new ConfigError('dictation.engine must be "off", "browser" or "whisper"');
200
+ next.engine = engine;
201
+ }
202
+ if (model !== undefined) {
203
+ if (!WHISPER_MODELS.includes(model))
204
+ throw new ConfigError(`dictation.model must be one of ${WHISPER_MODELS.join(", ")}`);
205
+ next.model = model;
206
+ }
207
+ if (whisperServer === "")
208
+ delete next.whisperServer;
209
+ else if (whisperServer !== undefined) {
210
+ if (typeof whisperServer !== "string" || !whisperServer.startsWith("/") || /[\x00-\x1f]/.test(whisperServer))
211
+ throw new ConfigError("dictation.whisperServer must be an absolute path");
212
+ next.whisperServer = whisperServer;
213
+ }
214
+ return next;
215
+ }
147
216
  const updateChannels = ["stable", "beta"];
148
217
  function readUpdateChannel(parsed, warnings) {
149
218
  const value = parsed?.updateChannel;
@@ -214,7 +283,7 @@ function parseProviders(parsed, warnings) {
214
283
  };
215
284
  }
216
285
  }
217
- for (const field of ["efforts", "summaries", "autoCompaction", "compactionModels", "permissionModes"]) {
286
+ for (const field of ["efforts", "summaries", "tours", "autoCompaction", "compactionModels", "permissionModes"]) {
218
287
  const entries = section[field];
219
288
  if (entries === undefined)
220
289
  continue;
@@ -442,19 +511,23 @@ export function applyPatch(current, patch) {
442
511
  throw new ConfigError("expected an object");
443
512
  }
444
513
  const body = patch;
445
- refuseUnknownKeys(body, ["retention", "fonts", "projects", "permissions", "providers", "workflowRuntime", "mcp", "filesystemIsolation", "sandboxSharing", "updateChannel"], "config");
514
+ refuseUnknownKeys(body, ["retention", "fonts", "projects", "permissions", "providers", "workflowRuntime", "mcp", "filesystemIsolation", "sandboxSharing", "updateChannel", "worktrees", "dictation"], "config");
446
515
  const projects = patchProjects(current.projects, body.projects);
447
516
  const permissions = patchPermissions(current.permissions, body.permissions);
448
517
  const providers = patchProviders(current.providers, body.providers);
449
518
  const filesystemIsolation = patchFilesystemIsolation(current.filesystemIsolation, body.filesystemIsolation);
450
519
  const sandboxSharing = patchSandboxSharing(current.sandboxSharing, body.sandboxSharing);
451
520
  const updateChannel = patchUpdateChannel(current.updateChannel, body.updateChannel);
521
+ const worktrees = patchWorktrees(current.worktrees, body.worktrees);
522
+ const dictation = patchDictation(current.dictation, body.dictation);
452
523
  return {
453
524
  ...(filesystemIsolation === undefined ? {} : { filesystemIsolation }),
454
525
  ...(sandboxSharing === undefined ? {} : { sandboxSharing }),
455
526
  ...(updateChannel === undefined ? {} : { updateChannel }),
456
527
  mcp: body.mcp === undefined ? current.mcp ?? [] : parseMcp(body.mcp),
457
528
  workflowRuntime: patchWorkflowRuntime(current.workflowRuntime, body.workflowRuntime),
529
+ ...(worktrees === undefined ? {} : { worktrees }),
530
+ ...(dictation === undefined ? {} : { dictation }),
458
531
  retention: { settled: patchRetention(current.retention.settled, body.retention) },
459
532
  fonts: patchFonts(current.fonts, body.fonts),
460
533
  ...(projects === undefined ? {} : { projects }),
@@ -477,7 +550,7 @@ export function applyPatch(current, patch) {
477
550
  function patchProviders(current, patch) {
478
551
  if (patch === undefined)
479
552
  return current;
480
- refuseUnknownKeys(patch, ["defaultBackend", "defaults", "summary", "efforts", "summaries", "autoCompaction", "compactionModels", "permissionModes"], "providers");
553
+ refuseUnknownKeys(patch, ["defaultBackend", "defaults", "summary", "efforts", "summaries", "tours", "autoCompaction", "compactionModels", "permissionModes"], "providers");
481
554
  const next = {
482
555
  ...(current?.autoCompaction === undefined ? {} : { autoCompaction: { ...current.autoCompaction } }),
483
556
  ...(current?.compactionModels === undefined ? {} : { compactionModels: { ...current.compactionModels } }),
@@ -485,6 +558,7 @@ function patchProviders(current, patch) {
485
558
  ...(current?.efforts === undefined ? {} : { efforts: { ...current.efforts } }),
486
559
  ...(current?.permissionModes === undefined ? {} : { permissionModes: { ...current.permissionModes } }),
487
560
  ...(current?.summaries === undefined ? {} : { summaries: { ...current.summaries } }),
561
+ ...(current?.tours === undefined ? {} : { tours: { ...current.tours } }),
488
562
  ...(current?.defaults === undefined ? {} : { defaults: { ...current.defaults } }),
489
563
  ...(current?.summary === undefined ? {} : { summary: current.summary }),
490
564
  };
@@ -599,6 +673,33 @@ function patchProviders(current, patch) {
599
673
  };
600
674
  }
601
675
  }
676
+ if (patch.tours !== undefined) {
677
+ const entries = patch.tours;
678
+ if (typeof entries !== "object" || entries === null || Array.isArray(entries))
679
+ throw new ConfigError("providers.tours must be an object");
680
+ const tours = { ...next.tours };
681
+ for (const [backend, value] of Object.entries(entries)) {
682
+ const field = `providers.tours.${backend}`;
683
+ if (value === null) {
684
+ delete tours[backend];
685
+ continue;
686
+ }
687
+ if (typeof value !== "object" || Array.isArray(value))
688
+ throw new ConfigError(`${field} must name a model and an effort`);
689
+ refuseUnknownKeys(value, ["modelId", "effort"], field);
690
+ const named = value;
691
+ const problem = checkModelId(named.modelId, `${field}.modelId`);
692
+ if (problem)
693
+ throw new ConfigError(problem);
694
+ if (!EFFORT_ORDER.includes(named.effort))
695
+ throw new ConfigError(`${field}.effort must be a valid effort`);
696
+ tours[backend] = { modelId: named.modelId.trim(), effort: named.effort };
697
+ }
698
+ if (Object.keys(tours).length)
699
+ next.tours = tours;
700
+ else
701
+ delete next.tours;
702
+ }
602
703
  if (patch.permissionModes !== undefined) {
603
704
  if (typeof patch.permissionModes !== "object" || patch.permissionModes === null || Array.isArray(patch.permissionModes))
604
705
  throw new ConfigError("providers.permissionModes must be an object");
@@ -0,0 +1,52 @@
1
+ import { run, GIT_READ_TIMEOUT_MS } from "./git.js";
2
+ import { diff } from "./changes.js";
3
+ import { readStatus } from "./git-state.js";
4
+ import { excerptHunks, numberedDiff } from "../client/diff.js";
5
+ export const hasDiffReference = (markdown) => /^```flow-diff\s/m.test(markdown);
6
+ export async function diffExcerpts(markdown, head, read) {
7
+ const diffs = new Map();
8
+ const cached = (path, view) => {
9
+ const key = `${view}:${path}`;
10
+ if (!diffs.has(key))
11
+ diffs.set(key, read(path, view));
12
+ return diffs.get(key);
13
+ };
14
+ const excerpts = {};
15
+ for (const match of markdown.matchAll(/^```(flow-diff\s.*)$/gm)) {
16
+ const info = match[1].trim();
17
+ excerpts[info] ??= await excerpt(info, head, cached);
18
+ }
19
+ return excerpts;
20
+ }
21
+ export async function messageExcerpts(markdown, scope, pullRequestBase) {
22
+ const sha = await run(scope, ["rev-parse", "HEAD"], GIT_READ_TIMEOUT_MS);
23
+ let uncommitted;
24
+ return diffExcerpts(markdown, sha.ok ? sha.value.trim() : "", async (path, view) => {
25
+ uncommitted ??= readStatus(scope).then(status => status.files.map(file => file.path));
26
+ const chosen = view ?? ((await uncommitted).includes(path) ? "uncommitted" : "branch");
27
+ return { view: chosen, diff: await diff(scope, chosen, path, pullRequestBase) };
28
+ });
29
+ }
30
+ async function excerpt(info, head, read) {
31
+ const path = /\bpath=(\S+)/.exec(info)?.[1];
32
+ if (!path)
33
+ return { problem: "This reference names no path." };
34
+ const lines = /\blines=(\d+)(?:-(\d+))?/.exec(info);
35
+ const range = lines ? { from: Number(lines[1]), to: Number(lines[2] ?? lines[1]) } : undefined;
36
+ const asked = /\bview=(uncommitted|branch)\b/.exec(info)?.[1];
37
+ let shown;
38
+ try {
39
+ shown = await read(path, asked);
40
+ }
41
+ catch (error) {
42
+ return { problem: `Cannot show ${path}: ${error instanceof Error ? error.message : String(error)}` };
43
+ }
44
+ if (!("text" in shown.diff))
45
+ return { problem: `${path} has no text diff.` };
46
+ const { deleted, hunks } = numberedDiff(shown.diff.text);
47
+ const chosen = excerptHunks(hunks, deleted, range);
48
+ if (chosen.length === 0)
49
+ return { problem: `No change to ${path}${range ? ` at lines ${range.from}-${range.to}` : ""}.` };
50
+ const first = chosen[0];
51
+ return { path, view: shown.view, line: range?.from ?? (deleted ? first.oldStart : first.newStart), deleted, head, hunks: chosen };
52
+ }
@@ -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
+ }
@@ -219,7 +219,7 @@ function millisecondOfDay(now) {
219
219
  const midnight = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
220
220
  return now.getTime() - midnight;
221
221
  }
222
- async function refExists(repo, branch) {
222
+ export async function refExists(repo, branch) {
223
223
  const found = await run(repo, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], GIT_READ_TIMEOUT_MS);
224
224
  return found.ok;
225
225
  }
@@ -237,8 +237,7 @@ function candidate(base, attempt) {
237
237
  *
238
238
  * A name the reader supplied is never bumped. Someone who typed a name and got a different one has
239
239
  * been ignored, so an existing ref is a failure carrying git's own conclusion; bumping exists only
240
- * for the derived name, and only because the TUI never types and would otherwise be stuck on the
241
- * second worktree of the day.
240
+ * for the derived name, which would otherwise be stuck on the second worktree of the day.
242
241
  */
243
242
  export async function planWorktree(options) {
244
243
  const { repo, from, under } = options;
@@ -297,14 +296,49 @@ export async function createWorktree(options) {
297
296
  return added;
298
297
  return { ok: true, value: planned.value };
299
298
  }
300
- export async function removeMergedBranch(repo, branch) {
301
- const target = await head(repo);
302
- if (!target.ok)
303
- return target;
304
- if (target.value.detached)
305
- return refuse(`delete refs/heads/${branch}`, "The source repository has a detached HEAD");
299
+ /**
300
+ * Fast-forward the Source Branch `branch` in the Project `repo` to its upstream.
301
+ *
302
+ * Only a fast-forward: git refuses a diverged branch, and refuses to move a branch that is
303
+ * checked out in a linked worktree, so nothing local is ever lost.
304
+ */
305
+ export async function updateSourceBranch(repo, branch) {
306
+ const upstream = await run(repo, ["rev-parse", "--symbolic-full-name", `${branch}@{upstream}`], GIT_READ_TIMEOUT_MS);
307
+ if (!upstream.ok)
308
+ return upstream;
309
+ const remote = await run(repo, ["config", "--get", `branch.${branch}.remote`], GIT_READ_TIMEOUT_MS);
310
+ if (!remote.ok)
311
+ return remote;
312
+ const fetched = await run(repo, ["fetch", "--quiet", remote.value.trim()], GIT_WRITE_TIMEOUT_MS);
313
+ if (!fetched.ok)
314
+ return fetched;
315
+ const target = upstream.value.trim();
316
+ const contained = await run(repo, ["merge-base", "--is-ancestor", target, `refs/heads/${branch}`], GIT_READ_TIMEOUT_MS);
317
+ if (contained.ok)
318
+ return { ok: true, value: undefined };
319
+ if (contained.failure.code !== 1)
320
+ return contained;
321
+ const current = await head(repo);
322
+ if (!current.ok)
323
+ return current;
324
+ const updated = !current.value.detached && current.value.name === branch
325
+ ? await run(repo, ["merge", "--ff-only", "--quiet", target], GIT_WRITE_TIMEOUT_MS)
326
+ : await run(repo, ["fetch", ".", `${target}:refs/heads/${branch}`], GIT_WRITE_TIMEOUT_MS);
327
+ if (!updated.ok)
328
+ return updated;
329
+ return { ok: true, value: undefined };
330
+ }
331
+ export async function removeMergedBranch(repo, branch, from) {
332
+ if (from === undefined) {
333
+ const target = await head(repo);
334
+ if (!target.ok)
335
+ return target;
336
+ if (target.value.detached)
337
+ return refuse(`delete refs/heads/${branch}`, "The source repository has a detached HEAD");
338
+ from = target.value.name;
339
+ }
306
340
  const branchRef = `refs/heads/${branch}`;
307
- const targetRef = `refs/heads/${target.value.name}`;
341
+ const targetRef = `refs/heads/${from}`;
308
342
  const merged = await run(repo, ["merge-base", "--is-ancestor", branchRef, targetRef], GIT_READ_TIMEOUT_MS);
309
343
  if (!merged.ok)
310
344
  return merged;
@@ -338,6 +372,15 @@ export async function removeWorktree(options) {
338
372
  return removed;
339
373
  return { ok: true, value: undefined };
340
374
  }
375
+ /** Check out `oid` with a detached HEAD at `path`, for read-only host work such as a Tour. */
376
+ export async function addDetachedCheckout(repo, oid, path) {
377
+ const added = await run(repo, ["worktree", "add", "--detach", path, oid], GIT_WRITE_TIMEOUT_MS);
378
+ return added.ok ? { ok: true, value: undefined } : added;
379
+ }
380
+ export async function removeDetachedCheckout(repo, path) {
381
+ await run(repo, ["worktree", "remove", "--force", path], GIT_WRITE_TIMEOUT_MS);
382
+ await run(repo, ["worktree", "prune"], GIT_WRITE_TIMEOUT_MS);
383
+ }
341
384
  /**
342
385
  * Reconnect a worktree and its repository after one or both moved. Run from the repository.
343
386
  *
@@ -0,0 +1,18 @@
1
+ const TYPES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
2
+ function isGithubImage(url) {
3
+ if (url.protocol !== "https:")
4
+ return false;
5
+ if (url.hostname === "raw.githubusercontent.com")
6
+ return /^\/[^/]+\/[^/]+\/.+/.test(url.pathname);
7
+ return url.hostname === "github.com" && /^\/user-attachments\/assets\/[0-9a-f-]+$/i.test(url.pathname);
8
+ }
9
+ export async function githubImage(href, token, fetcher = fetch) {
10
+ if (!URL.canParse(href) || !isGithubImage(new URL(href)))
11
+ return null;
12
+ const response = await fetcher(href, { headers: { authorization: `token ${(await token()).trim()}` } });
13
+ const type = response.headers.get("content-type")?.split(";")[0]?.trim() ?? "";
14
+ if (response.ok && TYPES.has(type))
15
+ return response;
16
+ await response.body?.cancel();
17
+ return null;
18
+ }
@@ -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;