@nathanstephenson/flow 0.1.10-beta.4 → 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 (82) hide show
  1. package/README.md +2 -2
  2. package/build/workflow-runtime.cjs +12 -12
  3. package/dist/backend/claude/workflow-parent.js +1 -1
  4. package/dist/backend/pi/model-auth.js +2 -2
  5. package/dist/backend/pi/workflow-parent.js +1 -1
  6. package/dist/backend/worker/index.js +4 -3
  7. package/dist/backend/worker/launcher.js +11 -4
  8. package/dist/build-id +1 -1
  9. package/dist/cli/application.js +5 -5
  10. package/dist/cli/bootstrap.js +1 -1
  11. package/dist/cli/host-control.js +1 -1
  12. package/dist/cli/install-guard.js +1 -1
  13. package/dist/cli/main.js +4 -4
  14. package/dist/cli/systemd-update.js +3 -3
  15. package/dist/cli/update.js +6 -6
  16. package/dist/cli/web-update.js +6 -6
  17. package/dist/daemon/changes.js +116 -0
  18. package/dist/daemon/commit.js +84 -0
  19. package/dist/daemon/config-store.js +3 -3
  20. package/dist/daemon/git-state.js +197 -0
  21. package/dist/daemon/github.js +54 -0
  22. package/dist/daemon/host-control-routes.js +1 -1
  23. package/dist/daemon/host.js +134 -76
  24. package/dist/daemon/log.js +3 -0
  25. package/dist/daemon/mcp-auth.js +1 -1
  26. package/dist/daemon/pi-model-cache.js +1 -1
  27. package/dist/daemon/pull-request.js +156 -129
  28. package/dist/daemon/push.js +43 -0
  29. package/dist/daemon/repository.js +106 -0
  30. package/dist/daemon/runtime.js +27 -20
  31. package/dist/daemon/secret-store.js +1 -1
  32. package/dist/daemon/server.js +11 -10
  33. package/dist/daemon/stack-metadata.js +12 -5
  34. package/dist/daemon/stack.js +127 -656
  35. package/dist/daemon/summariser.js +19 -8
  36. package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
  37. package/dist/daemon/workflow-authoring-scope.js +1 -1
  38. package/dist/daemon/workflow-builder-files.js +2 -2
  39. package/dist/daemon/workflow-builder-routes.js +2 -2
  40. package/dist/daemon/workflow-builder.js +5 -5
  41. package/dist/daemon/workflow-environment.js +5 -5
  42. package/dist/daemon/workflow-execution-launch.js +5 -5
  43. package/dist/daemon/workflow-execution-resources.js +3 -3
  44. package/dist/daemon/workflow-execution-routes.js +3 -3
  45. package/dist/daemon/workflow-execution-values.js +5 -5
  46. package/dist/daemon/workflow-executions.js +19 -19
  47. package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
  48. package/dist/daemon/workflow-mcp-authoring.js +4 -4
  49. package/dist/daemon/workflow-mcp.js +1 -1
  50. package/dist/daemon/workflow-routes.js +3 -3
  51. package/dist/daemon/workflow-schedule-driver.js +8 -8
  52. package/dist/daemon/workflow-schedule-routes.js +5 -5
  53. package/dist/daemon/workflow-schedules.js +3 -3
  54. package/dist/isolation/toolchain-assets.js +1 -1
  55. package/dist/protocol/stack.js +1 -41
  56. package/dist/workflows/calls.js +2 -2
  57. package/dist/workflows/executors.js +3 -3
  58. package/dist/workflows/graph.js +6 -6
  59. package/dist/workflows/invocations.js +1 -1
  60. package/dist/workflows/mcp.js +1 -1
  61. package/dist/workflows/records.js +6 -6
  62. package/dist/workflows/recovery.js +2 -2
  63. package/dist/workflows/runtime-settings.js +1 -1
  64. package/dist/workflows/runtime.js +2 -2
  65. package/dist/workflows/schedule-store.js +2 -2
  66. package/dist/workflows/scheduler.js +9 -9
  67. package/dist/workflows/schema.js +1 -1
  68. package/dist/workflows/store.js +3 -3
  69. package/package.json +3 -2
  70. package/web/dist/assets/index-BqZ_iUmY.css +2 -0
  71. package/web/dist/assets/index-CxdSb7k0.js +51 -0
  72. package/web/dist/assets/{settings-mcp-bcNKV147.js → settings-mcp-BwOPXAfH.js} +1 -1
  73. package/web/dist/assets/settings-workflows-DocTa31_.js +23 -0
  74. package/web/dist/assets/{switch-DIogWclb.js → switch-B00FEUA7.js} +1 -1
  75. package/web/dist/assets/{workflows-DHG-CIo3.js → workflows-DJqUuGyg.js} +31 -31
  76. package/web/dist/assets/{workflows-pane-9u_hJvgQ.js → workflows-pane-oM1fO_BC.js} +1 -1
  77. package/web/dist/index.html +4 -4
  78. package/dist/daemon/publish.js +0 -289
  79. package/dist/protocol/publish.js +0 -1
  80. package/web/dist/assets/index-BWKZK5HD.css +0 -2
  81. package/web/dist/assets/index-nIc09tKZ.js +0 -40
  82. package/web/dist/assets/settings-workflows-C_TKOhVa.js +0 -23
package/README.md CHANGED
@@ -146,7 +146,7 @@ Steering is a deliberate action.
146
146
  section.
147
147
 
148
148
  Settings, Projects, MCP connections and fonts are described in
149
- [docs/configuration.md](docs/configuration.md). Git publishing and stacked pull requests are
149
+ [docs/configuration.md](docs/configuration.md). Commit, push, pull requests and stacked pull requests are
150
150
  described in [docs/git.md](docs/git.md).
151
151
 
152
152
  ## Where state lives
@@ -186,7 +186,7 @@ requirements, the browser update, systemd setup and the repair procedure.
186
186
  | [docs/isolation.md](docs/isolation.md) | Filesystem isolation, Bubblewrap and sandboxes |
187
187
  | [docs/remote-access.md](docs/remote-access.md) | Container access and the OIDC gate |
188
188
  | [docs/configuration.md](docs/configuration.md) | Settings, MCP connections, Projects, fonts, environment variables |
189
- | [docs/git.md](docs/git.md) | Publish branch names and stacked pull requests |
189
+ | [docs/git.md](docs/git.md) | Commit, push, pull requests and stacked pull requests |
190
190
  | [docs/workflow-builder-scope.md](docs/workflow-builder-scope.md) | Workflows, including direct MCP steps |
191
191
  | [docs/development.md](docs/development.md) | Build, test, web development, releases |
192
192
  | [docs/milestones.md](docs/milestones.md) | Project status and design notes from each milestone |
@@ -42,9 +42,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
42
42
  mod
43
43
  ));
44
44
 
45
- // node_modules/typescript/lib/typescript.js
45
+ // node_modules/typescript-api/lib/typescript.js
46
46
  var require_typescript = __commonJS({
47
- "node_modules/typescript/lib/typescript.js"(exports2, module2) {
47
+ "node_modules/typescript-api/lib/typescript.js"(exports2, module2) {
48
48
  var ts2 = {};
49
49
  ((module3) => {
50
50
  "use strict";
@@ -212503,7 +212503,7 @@ var import_node_child_process = require("node:child_process");
212503
212503
  var import_node_fs = require("node:fs");
212504
212504
  var import_node_path = require("node:path");
212505
212505
  var import_node_readline = require("node:readline");
212506
- var import_typescript = __toESM(require_typescript(), 1);
212506
+ var import_typescript_api = __toESM(require_typescript(), 1);
212507
212507
 
212508
212508
  // node_modules/quickjs-emscripten-core/dist/index.mjs
212509
212509
  init_chunk_V2S4ZYJR();
@@ -213698,16 +213698,16 @@ async function main(): Promise<${outputType}> {
213698
213698
  ${code}
213699
213699
  }
213700
213700
  main();`;
213701
- const file = import_typescript.default.createSourceFile("/guest.ts", source, import_typescript.default.ScriptTarget.ES2020, true);
213701
+ const file = import_typescript_api.default.createSourceFile("/guest.ts", source, import_typescript_api.default.ScriptTarget.ES2020, true);
213702
213702
  const visit = (node) => {
213703
- if (import_typescript.default.isImportDeclaration(node) || import_typescript.default.isExportDeclaration(node) || import_typescript.default.isImportEqualsDeclaration(node) || import_typescript.default.isImportTypeNode(node) || node.kind === import_typescript.default.SyntaxKind.ImportKeyword) throw new Error("Imports are not supported");
213704
- import_typescript.default.forEachChild(node, visit);
213703
+ if (import_typescript_api.default.isImportDeclaration(node) || import_typescript_api.default.isExportDeclaration(node) || import_typescript_api.default.isImportEqualsDeclaration(node) || import_typescript_api.default.isImportTypeNode(node) || node.kind === import_typescript_api.default.SyntaxKind.ImportKeyword) throw new Error("Imports are not supported");
213704
+ import_typescript_api.default.forEachChild(node, visit);
213705
213705
  };
213706
213706
  visit(file);
213707
- const options = { strict: true, target: import_typescript.default.ScriptTarget.ES2020, module: import_typescript.default.ModuleKind.None, types: [], noEmitOnError: true, skipLibCheck: true };
213707
+ const options = { strict: true, target: import_typescript_api.default.ScriptTarget.ES2020, module: import_typescript_api.default.ModuleKind.None, types: [], noEmitOnError: true, skipLibCheck: true };
213708
213708
  let javascript = "";
213709
213709
  const host = {
213710
- getSourceFile: (path) => path === "/guest.ts" ? file : libraries[path.replace(/^\//, "")] === void 0 ? void 0 : import_typescript.default.createSourceFile(path, libraries[path.replace(/^\//, "")], import_typescript.default.ScriptTarget.ES2020, true),
213710
+ getSourceFile: (path) => path === "/guest.ts" ? file : libraries[path.replace(/^\//, "")] === void 0 ? void 0 : import_typescript_api.default.createSourceFile(path, libraries[path.replace(/^\//, "")], import_typescript_api.default.ScriptTarget.ES2020, true),
213711
213711
  getDefaultLibFileName: () => "/lib.es2020.d.ts",
213712
213712
  writeFile: (_path, text) => {
213713
213713
  javascript = text;
@@ -213720,9 +213720,9 @@ main();`;
213720
213720
  useCaseSensitiveFileNames: () => true,
213721
213721
  getNewLine: () => "\n"
213722
213722
  };
213723
- const program = import_typescript.default.createProgram(["/guest.ts"], options, host);
213724
- const errors = import_typescript.default.getPreEmitDiagnostics(program);
213725
- if (errors.length) throw new Error(import_typescript.default.flattenDiagnosticMessageText(errors[0].messageText, "\n"));
213723
+ const program = import_typescript_api.default.createProgram(["/guest.ts"], options, host);
213724
+ const errors = import_typescript_api.default.getPreEmitDiagnostics(program);
213725
+ if (errors.length) throw new Error(import_typescript_api.default.flattenDiagnosticMessageText(errors[0].messageText, "\n"));
213726
213726
  program.emit();
213727
213727
  return javascript;
213728
213728
  }
@@ -213901,7 +213901,7 @@ async function guest(request) {
213901
213901
  }
213902
213902
  /*! Bundled license information:
213903
213903
 
213904
- typescript/lib/typescript.js:
213904
+ typescript-api/lib/typescript.js:
213905
213905
  (*! *****************************************************************************
213906
213906
  Copyright (c) Microsoft Corporation. All rights reserved.
213907
213907
  Licensed under the Apache License, Version 2.0 (the "License"); you may not use
@@ -1,5 +1,5 @@
1
1
  import { createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';
2
- import { workflowInspectInput, workflowRecoverInput, workflowRelayInput, inspectDescription, recoverDescription, relayEnquiryDescription, relayPermissionDescription } from "../workflow-tools.js";
2
+ import { workflowInspectInput, workflowRecoverInput, workflowRelayInput, inspectDescription, recoverDescription, relayEnquiryDescription, relayPermissionDescription } from '../workflow-tools.js';
3
3
  export function workflowParentServer(parent) {
4
4
  if (!parent)
5
5
  return {};
@@ -1,5 +1,5 @@
1
- import { registerPiNativeProvider, unregisterPiNativeProvider, withPi099RadiusCatalog } from "./model-catalog.js";
2
- export { createPiModelAuth } from "./host-auth.js";
1
+ import { registerPiNativeProvider, unregisterPiNativeProvider, withPi099RadiusCatalog } from './model-catalog.js';
2
+ export { createPiModelAuth } from './host-auth.js';
3
3
  const emptyCredentials = {
4
4
  async read(_providerId, options) { options?.signal?.throwIfAborted(); return undefined; },
5
5
  async list(options) { options?.signal?.throwIfAborted(); return []; },
@@ -1,6 +1,6 @@
1
1
  import { Type } from 'typebox';
2
2
  import { z } from 'zod';
3
- import { workflowInspectInput, workflowRecoverInput, workflowRelayInput, inspectDescription, recoverDescription, relayEnquiryDescription, relayPermissionDescription } from "../workflow-tools.js";
3
+ import { workflowInspectInput, workflowRecoverInput, workflowRelayInput, inspectDescription, recoverDescription, relayEnquiryDescription, relayPermissionDescription } from '../workflow-tools.js';
4
4
  export function workflowParentTools(parent) {
5
5
  if (!parent)
6
6
  return [];
@@ -10,7 +10,7 @@ import { validateFilesystemScope } from "../../isolation/filesystem.js";
10
10
  import { workflowBuilderFolder } from "../../isolation/shared-sandbox.js";
11
11
  import { nodeExecutionAssets } from "../../isolation/node-assets.js";
12
12
  import { launchWorker, workerCommand } from "./launcher.js";
13
- import { seaSdkExecutionAssets } from "./assets.js";
13
+ import { seaSdkExecutionAssets } from './assets.js';
14
14
  import { WorkerRpc } from "./rpc.js";
15
15
  import { SandboxMcpSession } from "./sandbox-mcp.js";
16
16
  import { mcpMetadata } from "./protocol.js";
@@ -18,7 +18,7 @@ import { workflowInspectInput, workflowRecoverInput, workflowRelayInput } from "
18
18
  import { sessionListInput, sessionInspectInput, sessionCreateInput, sessionSendInput } from "../session-tools.js";
19
19
  import { migrateLegacyClaudeState, prepareClaudeState, relocateClaudeState, forkClaudeState } from "./claude-state.js";
20
20
  import { relocatePiState, forkPiState } from "../pi/state.js";
21
- import { createPiModelAuth } from "../pi/model-auth.js";
21
+ import { createPiModelAuth } from '../pi/model-auth.js';
22
22
  import { recordTiming } from "../../daemon/timings.js";
23
23
  /** One owned worker per Backend Session, optionally enforcing a filesystem boundary. */
24
24
  export class WorkerBackend {
@@ -347,7 +347,8 @@ class WorkerSession {
347
347
  }, (name, value) => this.notify(name, value));
348
348
  this.worker.onMessage((message) => this.rpc.receive(message), (error) => this.fail(error));
349
349
  child.once("error", (error) => this.fail(error));
350
- child.stdout?.once("close", () => this.fail(new Error("Backend worker disconnected")));
350
+ child.stdout?.once("close", () => void Promise.race([this.worker.exited, new Promise((resolve) => setTimeout(resolve, 1000).unref())])
351
+ .then(() => this.fail(new Error("Backend worker disconnected"))));
351
352
  child.once("exit", (code, signal) => this.fail(new Error(`Backend worker exited (${signal ?? code ?? "unknown"})${this.worker.diagnostics() ? `: ${this.worker.diagnostics()}` : ""}`)));
352
353
  }
353
354
  requirePiAuth() {
@@ -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;
package/dist/build-id CHANGED
@@ -1 +1 @@
1
- f94da56f-258e-42d7-900e-3933fca5ee5e
1
+ c0812b29-3bd1-4f02-be7b-5147006e3476
@@ -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("c0812b29-3bd1-4f02-be7b-5147006e3476", 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;
@@ -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
  /**