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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +2 -2
  2. package/build/backend-worker-chunks/{chunk-JOI2POLP.mjs → chunk-U73G6KK4.mjs} +18 -0
  3. package/build/backend-worker-chunks/{claude-GY27HBAY.mjs → claude-THGSOTC2.mjs} +7 -1
  4. package/build/backend-worker-chunks/{pi-JV6MWPW7.mjs → pi-5LAWIJNE.mjs} +82 -3
  5. package/build/backend-worker.mjs +7 -3
  6. package/build/workflow-runtime.cjs +12 -12
  7. package/dist/backend/claude/index.js +6 -0
  8. package/dist/backend/claude/workflow-parent.js +1 -1
  9. package/dist/backend/fake/index.js +6 -0
  10. package/dist/backend/pi/index.js +34 -2
  11. package/dist/backend/pi/model-auth.js +2 -2
  12. package/dist/backend/pi/plan-limits.js +41 -0
  13. package/dist/backend/pi/workflow-parent.js +1 -1
  14. package/dist/backend/plan-limits.js +17 -0
  15. package/dist/backend/worker/entry.js +4 -1
  16. package/dist/backend/worker/index.js +9 -3
  17. package/dist/backend/worker/launcher.js +11 -4
  18. package/dist/backend/worker/protocol.js +2 -1
  19. package/dist/build-id +1 -1
  20. package/dist/cli/application.js +5 -5
  21. package/dist/cli/bootstrap.js +1 -1
  22. package/dist/cli/host-control.js +1 -1
  23. package/dist/cli/install-guard.js +1 -1
  24. package/dist/cli/main.js +4 -4
  25. package/dist/cli/systemd-update.js +3 -3
  26. package/dist/cli/update.js +6 -6
  27. package/dist/cli/web-update.js +6 -6
  28. package/dist/client/context-usage.js +1 -1
  29. package/dist/client/markdown.js +3 -2
  30. package/dist/daemon/changes.js +116 -0
  31. package/dist/daemon/commit.js +84 -0
  32. package/dist/daemon/config-store.js +4 -3
  33. package/dist/daemon/config.js +31 -2
  34. package/dist/daemon/git-state.js +197 -0
  35. package/dist/daemon/github-image.js +18 -0
  36. package/dist/daemon/github.js +54 -0
  37. package/dist/daemon/host-control-routes.js +1 -1
  38. package/dist/daemon/host.js +280 -81
  39. package/dist/daemon/log.js +3 -0
  40. package/dist/daemon/mcp-auth.js +1 -1
  41. package/dist/daemon/pi-model-cache.js +1 -1
  42. package/dist/daemon/pull-request.js +156 -129
  43. package/dist/daemon/push.js +43 -0
  44. package/dist/daemon/repository.js +106 -0
  45. package/dist/daemon/runtime.js +28 -21
  46. package/dist/daemon/secret-store.js +1 -1
  47. package/dist/daemon/server.js +37 -10
  48. package/dist/daemon/skills.js +24 -0
  49. package/dist/daemon/spend-ledger.js +118 -0
  50. package/dist/daemon/stack-metadata.js +12 -5
  51. package/dist/daemon/stack.js +127 -656
  52. package/dist/daemon/summariser.js +30 -12
  53. package/dist/daemon/tour.js +42 -0
  54. package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
  55. package/dist/daemon/workflow-authoring-scope.js +1 -1
  56. package/dist/daemon/workflow-builder-files.js +2 -2
  57. package/dist/daemon/workflow-builder-routes.js +2 -2
  58. package/dist/daemon/workflow-builder.js +8 -6
  59. package/dist/daemon/workflow-environment.js +5 -5
  60. package/dist/daemon/workflow-execution-launch.js +5 -5
  61. package/dist/daemon/workflow-execution-resources.js +4 -4
  62. package/dist/daemon/workflow-execution-routes.js +3 -3
  63. package/dist/daemon/workflow-execution-values.js +5 -5
  64. package/dist/daemon/workflow-executions.js +19 -19
  65. package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
  66. package/dist/daemon/workflow-mcp-authoring.js +4 -4
  67. package/dist/daemon/workflow-mcp.js +1 -1
  68. package/dist/daemon/workflow-routes.js +22 -3
  69. package/dist/daemon/workflow-schedule-driver.js +8 -8
  70. package/dist/daemon/workflow-schedule-routes.js +5 -5
  71. package/dist/daemon/workflow-schedules.js +9 -8
  72. package/dist/isolation/toolchain-assets.js +1 -1
  73. package/dist/protocol/spend.js +2 -0
  74. package/dist/protocol/stack.js +1 -41
  75. package/dist/workflows/calls.js +2 -2
  76. package/dist/workflows/executors.js +3 -3
  77. package/dist/workflows/graph.js +6 -6
  78. package/dist/workflows/invocations.js +1 -1
  79. package/dist/workflows/mcp.js +1 -1
  80. package/dist/workflows/records.js +6 -6
  81. package/dist/workflows/recovery.js +2 -2
  82. package/dist/workflows/runtime-settings.js +1 -1
  83. package/dist/workflows/runtime.js +2 -2
  84. package/dist/workflows/schedule-store.js +2 -2
  85. package/dist/workflows/scheduler.js +35 -23
  86. package/dist/workflows/schema.js +1 -1
  87. package/dist/workflows/store.js +19 -5
  88. package/package.json +3 -2
  89. package/web/dist/assets/index-BhfJhrVJ.js +51 -0
  90. package/web/dist/assets/index-BvkM2cWL.css +2 -0
  91. package/web/dist/assets/{settings-mcp-bcNKV147.js → settings-mcp-3cgqQB28.js} +1 -1
  92. package/web/dist/assets/settings-workflows-Cutm8isB.js +23 -0
  93. package/web/dist/assets/{switch-DIogWclb.js → switch-B00FEUA7.js} +1 -1
  94. package/web/dist/assets/{workflows-DHG-CIo3.js → workflows-D6oEUUhj.js} +31 -31
  95. package/web/dist/assets/{workflows-pane-9u_hJvgQ.js → workflows-pane-KIdSDKJB.js} +1 -1
  96. package/web/dist/index.html +4 -4
  97. package/dist/daemon/publish.js +0 -289
  98. package/web/dist/assets/index-BWKZK5HD.css +0 -2
  99. package/web/dist/assets/index-nIc09tKZ.js +0 -40
  100. package/web/dist/assets/settings-workflows-C_TKOhVa.js +0 -23
  101. /package/dist/protocol/{publish.js → plan-limits.js} +0 -0
@@ -2,6 +2,7 @@ import { spawn } from "node:child_process";
2
2
  import { encodeFrame, frameDecoder } from "./frames.js";
3
3
  import { isSea } from "node:sea";
4
4
  import { fileURLToPath } from "node:url";
5
+ const sdkShadowWarning = /^\(node:\d+\) \[CLAUDE_SDK_CAN_USE_TOOL_SHADOWED\].*\n(?:\(Use `node --trace-warnings .*\n)?/gm;
5
6
  export function workerCommand(options = {}) {
6
7
  const source = import.meta.url.endsWith(".ts");
7
8
  const entry = options.entry ?? fileURLToPath(new URL(source ? "./entry.ts" : "./entry.js", import.meta.url));
@@ -19,9 +20,15 @@ export function launchWorker(options = {}) {
19
20
  stdio: ["pipe", "pipe", "pipe", ...(options.stdioFds ?? [])],
20
21
  });
21
22
  child.stdin?.on("error", () => { });
22
- // Drain diagnostics so a chatty SDK cannot block on stderr. Keep only a bounded failure tail.
23
- let diagnostics = "";
24
- child.stderr?.on("data", (chunk) => { diagnostics = (diagnostics + chunk.toString()).slice(-8192); });
23
+ // Drain diagnostics so a chatty SDK cannot block on stderr. Keep only a bounded, recent failure tail.
24
+ const windowMs = options.diagnosticsWindowMs ?? 10_000;
25
+ let diagnostics = [];
26
+ const recent = () => diagnostics.filter(({ at }) => at >= performance.now() - windowMs);
27
+ child.stderr?.on("data", (chunk) => {
28
+ diagnostics = [...recent(), { at: performance.now(), text: chunk.toString() }];
29
+ while (diagnostics.length > 1 && diagnostics.reduce((length, { text }) => length + text.length, 0) > 8192)
30
+ diagnostics.shift();
31
+ });
25
32
  const exited = new Promise((resolve) => {
26
33
  child.once("close", () => resolve());
27
34
  });
@@ -45,7 +52,7 @@ export function launchWorker(options = {}) {
45
52
  }
46
53
  });
47
54
  },
48
- diagnostics: () => diagnostics.trim(),
55
+ diagnostics: () => recent().map(({ text }) => text).join("").replace(sdkShadowWarning, "").slice(-8192).trim(),
49
56
  /** Await the process, then kill its entire process group if cooperative disposal stalled. */
50
57
  stop: (graceful) => stopping ??= (async () => {
51
58
  let timer;
@@ -2,7 +2,8 @@ export function snapshot(session) {
2
2
  return {
3
3
  capabilities: session.capabilities,
4
4
  resume: session.resumeToken(),
5
- methods: ["refreshMcp", "startWorkflowSubagent", "compact", "rewindFiles", "skills", "answerEnquiry", "answerPermission", "setPermissionMode"]
5
+ spend: session.spend,
6
+ methods: ["refreshMcp", "startWorkflowSubagent", "compact", "rewindFiles", "skills", "planLimits", "answerEnquiry", "answerPermission", "setPermissionMode"]
6
7
  .filter((method) => typeof session[method] === "function"),
7
8
  };
8
9
  }
package/dist/build-id CHANGED
@@ -1 +1 @@
1
- f94da56f-258e-42d7-900e-3933fca5ee5e
1
+ 607b7e81-c593-4a74-86cb-83029e6da64f
@@ -1,11 +1,11 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { readFileSync } from "node:fs";
3
- import { getHostStatus, launchBackground, requestHostStop, requireRestartable, waitUntil } from "./host-control.js";
4
- import { readHost, oidcFingerprint } from "../daemon/ownership.js";
5
- import { startRuntime } from "../daemon/runtime.js";
3
+ import { getHostStatus, launchBackground, requestHostStop, requireRestartable, waitUntil } from './host-control.js';
4
+ import { readHost, oidcFingerprint } from '../daemon/ownership.js';
5
+ import { startRuntime } from '../daemon/runtime.js';
6
6
  import { join, resolve } from "node:path";
7
7
  import { ConfigStore } from "../daemon/config-store.js";
8
- import { embeddedWorkflowRuntime } from "../workflows/runtime-asset.js";
8
+ import { embeddedWorkflowRuntime } from '../workflows/runtime-asset.js';
9
9
  import { fileURLToPath } from 'node:url';
10
10
  import { getAsset, isSea } from 'node:sea';
11
11
  import { EMBEDDED } from "../web/embedded.js";
@@ -16,7 +16,7 @@ import { answerLines } from "../client/enquiry.js";
16
16
  import { authorisationLabel } from "../client/permission.js";
17
17
  import { initialState, reduce } from "../client/reduce.js";
18
18
  import { runTui } from "../tui/app.js";
19
- import { updateUnsupportedReason } from "./install-guard.js";
19
+ import { updateUnsupportedReason } from './install-guard.js';
20
20
  let webUpdateSupport;
21
21
  const USAGE = `usage:
22
22
  flow --version print the installed version
@@ -889,7 +889,7 @@ async function bootstrap() {
889
889
  if (!managed) throw new Error("Missing systemd update configuration");
890
890
  await assertSystemdOwner(managed, managed.updater, process.pid);
891
891
  }
892
- const lease = await install.register("f94da56f-258e-42d7-900e-3933fca5ee5e", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
892
+ const lease = await install.register("607b7e81-c593-4a74-86cb-83029e6da64f", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
893
893
  delete process.env.FLOW_UPDATE_CAPABILITY;
894
894
  process.on("exit", lease.release);
895
895
  if (args[0] === "update") {
@@ -2,7 +2,7 @@ import { spawn } from 'node:child_process';
2
2
  import { closeSync, constants, fchmodSync, mkdirSync, openSync, realpathSync, statSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
  import { setTimeout as delay } from 'node:timers/promises';
5
- import { oidcFingerprint, readHost } from "../daemon/ownership.js";
5
+ import { oidcFingerprint, readHost } from '../daemon/ownership.js';
6
6
  export class HostRefusal extends Error {
7
7
  }
8
8
  export function processAlive(pid) {
@@ -2,7 +2,7 @@ import { mkdirSync, realpathSync, lstatSync, readFileSync, writeFileSync, readdi
2
2
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
3
3
  import { createHash, randomUUID } from 'node:crypto';
4
4
  import { setTimeout as delay } from 'node:timers/promises';
5
- import { processAlive } from "./host-control.js";
5
+ import { processAlive } from './host-control.js';
6
6
  export const packageName = '@nathanstephenson/flow';
7
7
  function record(path) {
8
8
  try {
package/dist/cli/main.js CHANGED
@@ -1,18 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import { isSea } from 'node:sea';
3
3
  if (process.argv[2] === '--flow-workflow-authoring-scope-reader' && process.env.FLOW_WORKFLOW_AUTHORING_SCOPE_READER === '1') {
4
- void import("../daemon/workflow-authoring-scope-reader.js").then(({ runWorkflowAuthoringScopeReader }) => runWorkflowAuthoringScopeReader()).catch(() => {
4
+ void import('../daemon/workflow-authoring-scope-reader.js').then(({ runWorkflowAuthoringScopeReader }) => runWorkflowAuthoringScopeReader()).catch(() => {
5
5
  process.exitCode = 1;
6
6
  });
7
7
  }
8
8
  else if (process.argv[2] === '--flow-workflow-builder-reader' && process.env.FLOW_WORKFLOW_BUILDER_READER === '1') {
9
- void import("../daemon/workflow-builder-reader.js").then(({ runWorkflowBuilderReader }) => runWorkflowBuilderReader()).catch(() => {
9
+ void import('../daemon/workflow-builder-reader.js').then(({ runWorkflowBuilderReader }) => runWorkflowBuilderReader()).catch(() => {
10
10
  process.exitCode = 1;
11
11
  });
12
12
  }
13
13
  else if (process.argv[2] === '--flow-isolation-launch' ||
14
14
  (process.argv[2] === '--flow-backend-worker' && process.env.FLOW_BACKEND_WORKER === '1')) {
15
- void import("../backend/worker/entry.js").catch(error => {
15
+ void import('../backend/worker/entry.js').catch(error => {
16
16
  console.error(error instanceof Error ? error.message : error);
17
17
  process.exitCode = 1;
18
18
  });
@@ -22,7 +22,7 @@ else if (!isSea() && import.meta.url.endsWith('.js')) {
22
22
  process.exitCode = 1;
23
23
  }
24
24
  else {
25
- void import("./application.js").then(({ runCli }) => runCli()).catch(error => {
25
+ void import('./application.js').then(({ runCli }) => runCli()).catch(error => {
26
26
  console.error(error instanceof Error ? error.message : error);
27
27
  process.exitCode = 1;
28
28
  });
@@ -2,9 +2,9 @@ import { execFile } from 'node:child_process';
2
2
  import { promisify } from 'node:util';
3
3
  import { readFileSync, writeFileSync, unlinkSync } from 'node:fs';
4
4
  import { join } from 'node:path';
5
- import { getHostStatus, waitUntil } from "./host-control.js";
6
- import { readHost } from "../daemon/ownership.js";
7
- import { isReleaseVersion } from "../daemon/release-checker.js";
5
+ import { getHostStatus, waitUntil } from './host-control.js';
6
+ import { readHost } from '../daemon/ownership.js';
7
+ import { isReleaseVersion } from '../daemon/release-checker.js';
8
8
  const exec = promisify(execFile);
9
9
  export function parseSystemdUpdate(value) {
10
10
  const c = value;
@@ -1,12 +1,12 @@
1
1
  import { execFileSync } from 'node:child_process';
2
2
  import { accessSync, constants, readFileSync, realpathSync } from 'node:fs';
3
3
  import { delimiter, join, resolve } from 'node:path';
4
- import { packageName, privatePath } from "./install-guard.js";
5
- import { readHost } from "../daemon/ownership.js";
6
- import { backgroundHostArgs, getHostStatus, HostRefusal, launchBackground, processAlive, requestHostStop, requireRestartable, waitUntil } from "./host-control.js";
7
- import { InstallationProcessUncertain, replacePackage } from "./install-process.js";
8
- import { assertSystemdOwner, restoreSystemd, resumeSystemdAdmission, systemctl, SystemdCommandFailed } from "./systemd-update.js";
9
- import { newerReleaseVersion } from "../daemon/release-checker.js";
4
+ import { packageName, privatePath } from './install-guard.js';
5
+ import { readHost } from '../daemon/ownership.js';
6
+ import { backgroundHostArgs, getHostStatus, HostRefusal, launchBackground, processAlive, requestHostStop, requireRestartable, waitUntil } from './host-control.js';
7
+ import { InstallationProcessUncertain, replacePackage } from './install-process.js';
8
+ import { assertSystemdOwner, restoreSystemd, resumeSystemdAdmission, systemctl, SystemdCommandFailed } from './systemd-update.js';
9
+ import { newerReleaseVersion } from '../daemon/release-checker.js';
10
10
  export function npmExecutable() {
11
11
  for (const directory of (process.env.PATH ?? '').split(delimiter)) {
12
12
  const path = resolve(directory, 'npm');
@@ -1,13 +1,13 @@
1
- import { systemdUpdate, launchSystemdUpdate, SystemdLaunchUncertain } from "./systemd-update.js";
1
+ import { systemdUpdate, launchSystemdUpdate, SystemdLaunchUncertain } from './systemd-update.js';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { closeSync, constants, fchmodSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmdirSync, unlinkSync, writeFileSync, } from 'node:fs';
4
4
  import { join } from 'node:path';
5
5
  import { spawn } from 'node:child_process';
6
- import { newerReleaseVersion, ReleaseChecker } from "../daemon/release-checker.js";
7
- import { UpdateRefusal } from "../daemon/update-api.js";
8
- export { UpdateRefusal } from "../daemon/update-api.js";
9
- import { processAlive } from "./host-control.js";
10
- import { inspectUpdateInstallation } from "./update.js";
6
+ import { newerReleaseVersion, ReleaseChecker } from '../daemon/release-checker.js';
7
+ import { UpdateRefusal } from '../daemon/update-api.js';
8
+ export { UpdateRefusal } from '../daemon/update-api.js';
9
+ import { processAlive } from './host-control.js';
10
+ import { inspectUpdateInstallation } from './update.js';
11
11
  const STATUS_FILE = 'web-update.json';
12
12
  const STATUS_LOCK = 'web-update-lock';
13
13
  const STATUS_LOCK_ATTEMPTS = 100;
@@ -43,7 +43,7 @@ export function contextUsageDetail(usage) {
43
43
  * cent, and rounding that to `$0.00` would report free work. Anything at or above a cent reads in
44
44
  * the two places money is normally written.
45
45
  */
46
- function money(usd) {
46
+ export function money(usd) {
47
47
  if (usd >= 0.01)
48
48
  return `$${usd.toFixed(2)}`;
49
49
  if (usd === 0)
@@ -156,12 +156,13 @@ function toImage(href, alt, raw, options) {
156
156
  if (!src || !/^https?:\/\//i.test(src))
157
157
  return { kind: "text", text: raw };
158
158
  const url = new URL(src);
159
- const blob = /^\/([^/]+)\/([^/]+)\/blob\/(.+)$/.exec(url.pathname);
159
+ const blob = /^\/([^/]+)\/([^/]+)\/(?:blob|raw)\/(.+)$/.exec(url.pathname);
160
160
  if (url.hostname === "github.com" && blob) {
161
161
  url.hostname = "raw.githubusercontent.com";
162
162
  url.pathname = `/${blob[1]}/${blob[2]}/${blob[3]}`;
163
163
  }
164
- return { kind: "image", src: url.href, alt };
164
+ const github = url.hostname === "raw.githubusercontent.com" || (url.hostname === "github.com" && url.pathname.startsWith("/user-attachments/assets/"));
165
+ return { kind: "image", src: options.imageProxy && github ? `${options.imageProxy}${encodeURIComponent(url.href)}` : url.href, alt };
165
166
  }
166
167
  function htmlImages(text, options) {
167
168
  const tags = text.match(/<img\b(?:[^"'<>]|"[^"]*"|'[^']*')*\/?>/gi);
@@ -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
  /**
@@ -131,6 +131,7 @@ export class ConfigStore {
131
131
  return { backend, ...summary };
132
132
  return providers?.summary?.backend === backend ? providers.summary : undefined;
133
133
  };
134
+ tourModel = (backend) => this.config.providers?.tours?.[backend];
134
135
  defaultPermissionMode = (backend) => this.config.providers?.permissionModes?.[backend];
135
136
  defaultEffort = (backend) => this.config.providers?.efforts?.[backend];
136
137
  /**
@@ -3,6 +3,7 @@ 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
5
  import { DEFAULT_WORKFLOW_RUNTIME, 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;
@@ -214,7 +215,7 @@ function parseProviders(parsed, warnings) {
214
215
  };
215
216
  }
216
217
  }
217
- for (const field of ["efforts", "summaries", "autoCompaction", "compactionModels", "permissionModes"]) {
218
+ for (const field of ["efforts", "summaries", "tours", "autoCompaction", "compactionModels", "permissionModes"]) {
218
219
  const entries = section[field];
219
220
  if (entries === undefined)
220
221
  continue;
@@ -477,7 +478,7 @@ export function applyPatch(current, patch) {
477
478
  function patchProviders(current, patch) {
478
479
  if (patch === undefined)
479
480
  return current;
480
- refuseUnknownKeys(patch, ["defaultBackend", "defaults", "summary", "efforts", "summaries", "autoCompaction", "compactionModels", "permissionModes"], "providers");
481
+ refuseUnknownKeys(patch, ["defaultBackend", "defaults", "summary", "efforts", "summaries", "tours", "autoCompaction", "compactionModels", "permissionModes"], "providers");
481
482
  const next = {
482
483
  ...(current?.autoCompaction === undefined ? {} : { autoCompaction: { ...current.autoCompaction } }),
483
484
  ...(current?.compactionModels === undefined ? {} : { compactionModels: { ...current.compactionModels } }),
@@ -485,6 +486,7 @@ function patchProviders(current, patch) {
485
486
  ...(current?.efforts === undefined ? {} : { efforts: { ...current.efforts } }),
486
487
  ...(current?.permissionModes === undefined ? {} : { permissionModes: { ...current.permissionModes } }),
487
488
  ...(current?.summaries === undefined ? {} : { summaries: { ...current.summaries } }),
489
+ ...(current?.tours === undefined ? {} : { tours: { ...current.tours } }),
488
490
  ...(current?.defaults === undefined ? {} : { defaults: { ...current.defaults } }),
489
491
  ...(current?.summary === undefined ? {} : { summary: current.summary }),
490
492
  };
@@ -599,6 +601,33 @@ function patchProviders(current, patch) {
599
601
  };
600
602
  }
601
603
  }
604
+ if (patch.tours !== undefined) {
605
+ const entries = patch.tours;
606
+ if (typeof entries !== "object" || entries === null || Array.isArray(entries))
607
+ throw new ConfigError("providers.tours must be an object");
608
+ const tours = { ...next.tours };
609
+ for (const [backend, value] of Object.entries(entries)) {
610
+ const field = `providers.tours.${backend}`;
611
+ if (value === null) {
612
+ delete tours[backend];
613
+ continue;
614
+ }
615
+ if (typeof value !== "object" || Array.isArray(value))
616
+ throw new ConfigError(`${field} must name a model and an effort`);
617
+ refuseUnknownKeys(value, ["modelId", "effort"], field);
618
+ const named = value;
619
+ const problem = checkModelId(named.modelId, `${field}.modelId`);
620
+ if (problem)
621
+ throw new ConfigError(problem);
622
+ if (!EFFORT_ORDER.includes(named.effort))
623
+ throw new ConfigError(`${field}.effort must be a valid effort`);
624
+ tours[backend] = { modelId: named.modelId.trim(), effort: named.effort };
625
+ }
626
+ if (Object.keys(tours).length)
627
+ next.tours = tours;
628
+ else
629
+ delete next.tours;
630
+ }
602
631
  if (patch.permissionModes !== undefined) {
603
632
  if (typeof patch.permissionModes !== "object" || patch.permissionModes === null || Array.isArray(patch.permissionModes))
604
633
  throw new ConfigError("providers.permissionModes must be an object");