@pmelab/gtd 24.2.0 → 24.4.0

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 (81) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +41 -6
  3. package/dist/chunks/{Schema-Dh-mkwkq.mjs → Schema-B5yK7QrT.mjs} +47 -1
  4. package/dist/chunks/{reserved-ejn-LVYO.mjs → reserved-B9pG93Fc.mjs} +53 -13
  5. package/dist/chunks/{steering-D-PvRC5W.mjs → steering-DVILanVf.mjs} +16 -5
  6. package/dist/flows.mjs +9 -1
  7. package/dist/gtd.bundle.mjs +1114 -865
  8. package/dist/steering.mjs +2 -2
  9. package/dist/testkit.mjs +1135 -218
  10. package/dist/workflow-kit.mjs +9 -7
  11. package/dist/workflows/feature.mjs +152 -35
  12. package/dist/workflows/fix.mjs +2 -2
  13. package/dist/workflows/review.mjs +1 -1
  14. package/dist/workflows.mjs +223 -54
  15. package/package.json +1 -1
  16. package/src/cli/Cli.test.ts +57 -0
  17. package/src/cli/Cli.ts +89 -9
  18. package/src/cli/History.test.ts +225 -0
  19. package/src/cli/History.ts +143 -0
  20. package/src/cli/Output.ts +68 -0
  21. package/src/cli/Program.test.ts +10 -9
  22. package/src/cli/Program.ts +24 -72
  23. package/src/edge/Edge.test.ts +261 -3
  24. package/src/edge/Edge.ts +218 -41
  25. package/src/edge/index.ts +1 -0
  26. package/src/emit/GitScript.test.ts +27 -0
  27. package/src/emit/GitScript.ts +18 -2
  28. package/src/emit/index.ts +2 -0
  29. package/src/flows/scripts.ts +6 -0
  30. package/src/platform/Git.test.ts +6 -9
  31. package/src/platform/Git.ts +48 -10
  32. package/src/platform/RetainedHistory.test.ts +14 -0
  33. package/src/platform/RetainedHistory.ts +5 -0
  34. package/src/platform/index.ts +7 -1
  35. package/src/replay/Trailers.test.ts +32 -0
  36. package/src/replay/Trailers.ts +17 -0
  37. package/src/steering/FORMATS.md +1 -1
  38. package/src/steering/SteeringFormat.test.ts +9 -1
  39. package/src/steering/SteeringFormat.ts +7 -0
  40. package/src/steering/contract.test.ts +3 -0
  41. package/src/steering/index.ts +1 -0
  42. package/src/steering/review.test.ts +30 -0
  43. package/src/steering/review.ts +8 -2
  44. package/src/step/LandStep.ts +3 -1
  45. package/src/step/RepoSnapshot.ts +7 -1
  46. package/src/step/planStart.test.ts +6 -3
  47. package/src/step/planStep.test.ts +29 -1
  48. package/src/step/planStep.ts +8 -0
  49. package/src/testkit/EmittedScriptRecognizer.test.ts +29 -30
  50. package/src/testkit/EmittedScriptRecognizer.ts +149 -52
  51. package/src/testkit/EmittedScripts.test.ts +166 -0
  52. package/src/testkit/FakeGitOperations.ts +6 -2
  53. package/src/testkit/FlowScripts.test.ts +242 -0
  54. package/src/testkit/FlowScripts.ts +326 -0
  55. package/src/testkit/GitTiers.ts +269 -47
  56. package/src/testkit/InMemRepo.ts +61 -8
  57. package/src/testkit/Layers.ts +10 -2
  58. package/src/testkit/TestRepo.ts +4 -1
  59. package/src/testkit/index.ts +1 -1
  60. package/src/workflow/discovery.test.ts +147 -0
  61. package/src/workflow/discovery.ts +5 -0
  62. package/src/workflow/fingerprint.test.ts +20 -4
  63. package/src/workflow/fingerprint.ts +8 -9
  64. package/src/workflow/index.ts +1 -6
  65. package/src/workflow/load.test.ts +5 -19
  66. package/src/workflow/load.ts +94 -10
  67. package/src/workflow-kit/review.test.ts +84 -0
  68. package/src/workflow-kit/review.ts +9 -6
  69. package/src/workflows/feature/review.test.ts +238 -12
  70. package/src/workflows/feature/review.ts +172 -31
  71. package/src/workflows/feature/steps.test.ts +12 -0
  72. package/src/workflows/feature/steps.ts +8 -1
  73. package/src/workflows/shared/access.test.ts +4 -2
  74. package/src/workflows/shared/access.ts +1 -0
  75. package/src/workflows/shared/options.test.ts +8 -0
  76. package/src/workflows/shared/options.ts +1 -0
  77. package/src/workflows/shared/steps.ts +2 -0
  78. package/src/workflows/shared/tail.ts +3 -11
  79. package/src/workflows/shared/text.test.ts +106 -0
  80. package/src/workflows/shared/text.ts +57 -1
  81. package/src/workflows/shared/vars.ts +1 -0
@@ -3,17 +3,17 @@ import { createRequire as __createRequire } from 'module';
3
3
  const require = __createRequire(import.meta.url);
4
4
  import { createRequire } from "node:module";
5
5
  import * as http from "node:http";
6
- import { IncomingMessage } from "node:http";
7
6
  import { isIP } from "node:net";
8
7
  import * as Crypto from "node:crypto";
9
8
  import { createHash, randomUUID } from "node:crypto";
10
9
  import * as NFS from "node:fs";
11
10
  import { appendFileSync, closeSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
12
11
  import * as OS from "node:os";
13
- import { constants, homedir, tmpdir } from "node:os";
12
+ import { constants, homedir, networkInterfaces, tmpdir } from "node:os";
14
13
  import * as Path from "node:path";
15
14
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
16
15
  import * as https from "node:https";
16
+ import { Readable } from "node:stream";
17
17
  import { mkdir, readFile, writeFile } from "node:fs/promises";
18
18
  import * as ChildProcess from "node:child_process";
19
19
  import { execFile, execFileSync, spawn } from "node:child_process";
@@ -6826,7 +6826,7 @@ var init_label = __esmMin((() => {
6826
6826
  }));
6827
6827
  //#endregion
6828
6828
  //#region node_modules/effect/dist/esm/internal/core-effect.js
6829
- var annotateLogs$1, asSome, try_$1, catchTag$1, diffFiberRefs, bind, bindTo, match$4, fiberRefs, ignore$1, logWithLevel, logWarning$1, logError$1, mapErrorCause, negate$1, patchFiberRefs, promise$1, provideService$1, provideServiceEffect, sandbox$1, sleep$1, succeedNone, summarized, tapErrorCause$1, tryPromise$1, tryMap$1, updateFiberRefs, when$1, serviceOption$1;
6829
+ var annotateLogs$1, asSome, try_$1, catchTag$1, diffFiberRefs, bind, bindTo, match$4, fiberRefs, ignore$1, logWithLevel, logWarning$1, logError$1, mapErrorCause, negate$1, orElseSucceed$1, patchFiberRefs, promise$1, provideService$1, provideServiceEffect, sandbox$1, sleep$1, succeedNone, summarized, tapErrorCause$1, tryPromise$1, tryMap$1, updateFiberRefs, when$1, serviceOption$1;
6830
6830
  var init_core_effect = __esmMin((() => {
6831
6831
  init_Clock();
6832
6832
  init_Context();
@@ -6910,6 +6910,7 @@ var init_core_effect = __esmMin((() => {
6910
6910
  onSuccess: succeed$8
6911
6911
  }));
6912
6912
  negate$1 = (self) => map$8(self, (b) => !b);
6913
+ orElseSucceed$1 = /*#__PURE__*/ dual(2, (self, evaluate) => orElse$2(self, () => sync$2(evaluate)));
6913
6914
  patchFiberRefs = (patch) => updateFiberRefs((fiberId, fiberRefs) => pipe(patch, patch$2(fiberId, fiberRefs)));
6914
6915
  promise$1 = (evaluate) => evaluate.length >= 1 ? async_((resolve, signal) => {
6915
6916
  try {
@@ -10185,7 +10186,7 @@ var init_Fiber = __esmMin((() => {
10185
10186
  }));
10186
10187
  //#endregion
10187
10188
  //#region node_modules/effect/dist/esm/internal/runtime.js
10188
- var makeDual, unsafeFork, unsafeRunSync, AsyncFiberExceptionImpl, asyncFiberException, FiberFailureId, FiberFailureCauseId, FiberFailureImpl, fiberFailure, fastPath, unsafeRunSyncExit, unsafeRunPromiseExit, RuntimeImpl, make$16, runtime$1, defaultRuntimeFlags, defaultRuntime, updateContext$1, unsafeForkEffect, unsafeRunSyncEffect;
10189
+ var makeDual, unsafeFork, unsafeRunSync, AsyncFiberExceptionImpl, asyncFiberException, FiberFailureId, FiberFailureCauseId, FiberFailureImpl, fiberFailure, fastPath, unsafeRunSyncExit, unsafeRunPromise, unsafeRunPromiseExit, RuntimeImpl, make$16, runtime$1, defaultRuntimeFlags, defaultRuntime, updateContext$1, unsafeForkEffect, unsafeRunPromiseEffect, unsafeRunSyncEffect;
10189
10190
  var init_runtime = __esmMin((() => {
10190
10191
  init_Context();
10191
10192
  init_Equal();
@@ -10202,6 +10203,7 @@ var init_runtime = __esmMin((() => {
10202
10203
  init_executionStrategy();
10203
10204
  init_fiberRuntime();
10204
10205
  init_fiberScope();
10206
+ init_effect();
10205
10207
  init_runtimeFlags();
10206
10208
  init_supervisor();
10207
10209
  makeDual = (f) => function() {
@@ -10309,6 +10311,12 @@ var init_runtime = __esmMin((() => {
10309
10311
  if (result) return result;
10310
10312
  return exitDie$1(capture(asyncFiberException(fiberRuntime), currentSpanFromFiber(fiberRuntime)));
10311
10313
  });
10314
+ unsafeRunPromise = /*#__PURE__*/ makeDual((runtime, effect, options) => unsafeRunPromiseExit(runtime, effect, options).then((result) => {
10315
+ switch (result._tag) {
10316
+ case OP_SUCCESS: return result.effect_instruction_i0;
10317
+ case OP_FAILURE: throw fiberFailure(result.effect_instruction_i0);
10318
+ }
10319
+ }));
10312
10320
  unsafeRunPromiseExit = /*#__PURE__*/ makeDual((runtime, effect, options) => new Promise((resolve) => {
10313
10321
  const op = fastPath(effect);
10314
10322
  if (op) resolve(op);
@@ -10348,6 +10356,7 @@ var init_runtime = __esmMin((() => {
10348
10356
  fiberRefs: self.fiberRefs
10349
10357
  }));
10350
10358
  unsafeForkEffect = /*#__PURE__*/ unsafeFork(defaultRuntime);
10359
+ unsafeRunPromiseEffect = /*#__PURE__*/ unsafeRunPromise(defaultRuntime);
10351
10360
  unsafeRunSyncEffect = /*#__PURE__*/ unsafeRunSync(defaultRuntime);
10352
10361
  }));
10353
10362
  //#endregion
@@ -11426,7 +11435,7 @@ var init_MutableQueue = __esmMin((() => {
11426
11435
  }));
11427
11436
  //#endregion
11428
11437
  //#region node_modules/effect/dist/esm/Effect.js
11429
- var isEffect, all$1, forEach$2, async, withFiberRuntime, fail$7, failCause$2, die, dieMessage, gen, promise, succeed$3, suspend$5, sync$1, _void, catchAll, catchAllCause, catchTag, ignore, sandbox, retry, try_, tryMap, tryPromise, interrupt, interruptible, uninterruptible, uninterruptibleMask, as, asVoid, map$4, mapBoth$1, mapError$1, negate, acquireRelease, acquireUseRelease$2, addFinalizer, ensuring$2, onError, scope$1, scopeWith, scopedWith$1, scoped$3, fiberIdWith, forkDaemon, forkIn, forkScoped, timeout, provide$1, provideService, serviceOption, either, exit$1, intoDeferred, when, flatMap$4, andThen, flatten$5, race, raceWith, tap, tapErrorCause, repeat, match$2, matchCause, matchCauseEffect, matchEffect, logWarning, logError, annotateLogs, orDie, orElse$1, runtime, unsafeMakeSemaphore, makeSemaphore, unsafeMakeLatch, runFork$1, runSync, zip$1, zipLeft, zipRight$1, zipWith, fnUntraced;
11438
+ var isEffect, all$1, forEach$2, async, withFiberRuntime, fail$7, failCause$2, die, dieMessage, gen, promise, succeed$3, suspend$5, sync$1, _void, catchAll, catchAllCause, catchTag, ignore, sandbox, retry, try_, tryMap, tryPromise, interrupt, interruptible, uninterruptible, uninterruptibleMask, as, asVoid, map$4, mapBoth$1, mapError$1, negate, acquireRelease, acquireUseRelease$2, addFinalizer, ensuring$2, onError, scope$1, scopeWith, scopedWith$1, scoped$3, fiberIdWith, forkDaemon, forkIn, forkScoped, timeout, provide$1, provideService, serviceOption, either, exit$1, intoDeferred, when, flatMap$4, andThen, flatten$5, race, raceWith, tap, tapErrorCause, repeat, match$2, matchCause, matchCauseEffect, matchEffect, logWarning, logError, annotateLogs, orDie, orElse$1, orElseSucceed, runtime, unsafeMakeSemaphore, makeSemaphore, unsafeMakeLatch, runFork$1, runPromise, runSync, zip$1, zipLeft, zipRight$1, zipWith, fnUntraced;
11430
11439
  var init_Effect = __esmMin((() => {
11431
11440
  init_core_effect();
11432
11441
  init_core();
@@ -11507,11 +11516,13 @@ var init_Effect = __esmMin((() => {
11507
11516
  annotateLogs = annotateLogs$1;
11508
11517
  orDie = orDie$1;
11509
11518
  orElse$1 = orElse$2;
11519
+ orElseSucceed = orElseSucceed$1;
11510
11520
  runtime = runtime$1;
11511
11521
  unsafeMakeSemaphore = unsafeMakeSemaphore$1;
11512
11522
  makeSemaphore = makeSemaphore$1;
11513
11523
  unsafeMakeLatch = unsafeMakeLatch$1;
11514
11524
  runFork$1 = unsafeForkEffect;
11525
+ runPromise = unsafeRunPromiseEffect;
11515
11526
  runSync = unsafeRunSyncEffect;
11516
11527
  zip$1 = zipOptions;
11517
11528
  zipLeft = zipLeftOptions;
@@ -20243,8 +20254,17 @@ const resolvedRefOrCorrupted = (ref, hash) => /^[0-9a-f]{40}$/.test(hash) ? succ
20243
20254
  const makeGitImpl = (executor, root) => {
20244
20255
  const exec = (...args) => run$4(root, ...args).pipe(provide$1(succeed$2(CommandExecutor, executor)));
20245
20256
  return {
20246
- lastCommitSubject: (ref = "HEAD") => exec("git", "log", "-1", "--pretty=%s", ref).pipe(map$4((s) => s.trim())),
20247
- lastCommitMessage: () => exec("git", "log", "-1", "--pretty=%B").pipe(map$4((s) => s.trim())),
20257
+ lastCommitSubject: (ref = "HEAD") => exec("git", "log", "-1", "--pretty=%s", "--end-of-options", ref).pipe(map$4((s) => s.trim())),
20258
+ lastCommitMessage: (ref = "HEAD") => exec("git", "log", "-1", "--pretty=%B", "--end-of-options", ref).pipe(map$4((s) => s.trim())),
20259
+ currentBranch: () => exec("git", "symbolic-ref", "--quiet", "--short", "HEAD").pipe(map$4((s) => s.trim()), map$4((name) => some(name)), catchAll(() => succeed$3(none$4()))),
20260
+ listRefs: (prefix) => exec("git", "for-each-ref", "--sort=-committerdate", "--format=%(refname)%09%(objectname)%09%(committerdate:iso-strict)", prefix).pipe(map$4((out) => out.split("\n").filter((line) => line.length > 0).map((line) => {
20261
+ const [ref = "", hash = "", date = ""] = line.split(" ");
20262
+ return {
20263
+ ref,
20264
+ hash,
20265
+ date
20266
+ };
20267
+ }))),
20248
20268
  hasCommits: () => exec("git", "rev-parse", "--verify", "HEAD").pipe(map$4(() => true), catchAll(() => succeed$3(false))),
20249
20269
  readFileAtRef: (ref, path) => exec("git", "show", `${ref}:${path}`),
20250
20270
  changedPaths: (base) => gen(function* () {
@@ -20264,7 +20284,7 @@ const makeGitImpl = (executor, root) => {
20264
20284
  }
20265
20285
  return all;
20266
20286
  }),
20267
- resolveRef: (ref) => exec("git", "rev-parse", "--verify", ref).pipe(map$4((s) => s.trim()), flatMap$4((hash) => resolvedRefOrCorrupted(ref, hash))),
20287
+ resolveRef: (ref) => exec("git", "rev-parse", "--verify", "--end-of-options", ref).pipe(map$4((s) => s.trim()), flatMap$4((hash) => resolvedRefOrCorrupted(ref, hash))),
20268
20288
  readRefOption: (ref) => exec("git", "rev-parse", "--verify", "--quiet", ref).pipe(map$4((s) => some(s.trim())), catchAll(() => succeed$3(none$4()))),
20269
20289
  isAncestor: (a, b) => run$4(root, "git", "merge-base", "--is-ancestor", a, b).pipe(provide$1(succeed$2(CommandExecutor, executor)), map$4(() => true), catchAll(() => succeed$3(false))),
20270
20290
  mergeBase: (a, b) => exec("git", "merge-base", a, b).pipe(map$4((s) => some(s.trim())), catchAll(() => succeed$3(none$4()))),
@@ -20920,6 +20940,9 @@ const loopLogPath = gen(function* () {
20920
20940
  init_esm();
20921
20941
  /** Per-worktree (`refs/worktree/gtd/*`) so linked worktrees sharing one `.git` don't clobber each other's retained history. */
20922
20942
  const HISTORY_REF = "refs/worktree/gtd/history";
20943
+ /** One ref per finished process, kept past the branch's deletion; distinct from the per-worktree `HISTORY_REF`. */
20944
+ const PROCESS_HISTORY_PREFIX = "refs/gtd/history/";
20945
+ const processHistoryRef = (hash) => `${PROCESS_HISTORY_PREFIX}${hash}`;
20923
20946
  const readRetainedHistory = (git) => git.readRefOption(HISTORY_REF);
20924
20947
  /**
20925
20948
  * Whether resetting to `tipHash` is safe: HEAD must be an ancestor of
@@ -21800,6 +21823,13 @@ const moveScript = (from, to) => [
21800
21823
  `mv -- ${quote(from)} ${quote(to)}`,
21801
21824
  ""
21802
21825
  ].join("\n");
21826
+ /** Write `path` as committed at `ref` to `to`. */
21827
+ const showScript = (ref, path, to) => [
21828
+ "#!/usr/bin/env sh",
21829
+ "set -e",
21830
+ `git show ${quote(`${ref}:${path}`)} > ${quote(to)}`,
21831
+ ""
21832
+ ].join("\n");
21803
21833
  //#endregion
21804
21834
  //#region src/flows/helpers.ts
21805
21835
  /** Whether a judge answered `expected` at a probability of at least `minP`. */
@@ -22078,6 +22108,7 @@ var flows_exports = /* @__PURE__ */ __exportAll({
22078
22108
  scope: () => scope,
22079
22109
  sectionBodies: () => sectionBodies,
22080
22110
  sections: () => sections,
22111
+ showScript: () => showScript,
22081
22112
  skillsFor: () => skillsFor,
22082
22113
  start: () => start,
22083
22114
  threads: () => threads,
@@ -22085,6 +22116,16 @@ var flows_exports = /* @__PURE__ */ __exportAll({
22085
22116
  wrote: () => wrote
22086
22117
  });
22087
22118
  //#endregion
22119
+ //#region src/steering/SteeringFormat.ts
22120
+ var formatFinding;
22121
+ var init_SteeringFormat = __esmMin((() => {
22122
+ formatFinding = (file, finding) => {
22123
+ if (finding.line === void 0) return finding.message;
22124
+ const col = finding.range !== void 0 ? `:${finding.range.start.character + 1}` : "";
22125
+ return `${file}:${finding.line + 1}${col}: ${finding.message}`;
22126
+ };
22127
+ }));
22128
+ //#endregion
22088
22129
  //#region node_modules/mdast-util-to-string/lib/index.js
22089
22130
  /**
22090
22131
  * Get the text content of a node or list of nodes.
@@ -37025,6 +37066,7 @@ var init_CodeThreads = __esmMin((() => {
37025
37066
  //#region src/steering/index.ts
37026
37067
  var REGISTRY, BUILT_IN_MODE_NAMES, steeringFormatFor, steeringFormatOrFreeForm, unansweredQuestions, viewOf, openThreads;
37027
37068
  var init_steering = __esmMin((() => {
37069
+ init_SteeringFormat();
37028
37070
  init_qa();
37029
37071
  init_review();
37030
37072
  init_Edits();
@@ -37547,6 +37589,12 @@ const TRAILER_READERS = {
37547
37589
  "Gtd-Review-Base": (value, into) => {
37548
37590
  into.reviewBase ??= value.split(/\s/)[0];
37549
37591
  },
37592
+ "Gtd-Branch": (value, into) => {
37593
+ if (value !== "") into.branch ??= value;
37594
+ },
37595
+ "Gtd-Version": (value, into) => {
37596
+ if (value !== "") into.version ??= value;
37597
+ },
37550
37598
  "Gtd-Format": (value, into) => {
37551
37599
  if (FORMAT_RE.test(value)) into.format ??= Number(value);
37552
37600
  },
@@ -37565,6 +37613,8 @@ const parseCommitMessage = (message) => {
37565
37613
  step: void 0,
37566
37614
  workflow: void 0,
37567
37615
  reviewBase: void 0,
37616
+ branch: void 0,
37617
+ version: void 0,
37568
37618
  judge: [],
37569
37619
  vars: {},
37570
37620
  config: {},
@@ -37590,6 +37640,8 @@ const formatCommitMessage = (spec) => {
37590
37640
  for (const [path, hash] of sortedEntries(spec.config)) lines.push(`Gtd-Config: ${hash} ${encodePath(path)}`);
37591
37641
  if (spec.cost !== void 0) lines.push(`Gtd-Cost: ${spec.cost.cost}${spec.cost.model !== void 0 ? ` ${spec.cost.model}` : ""}`);
37592
37642
  for (const verdict of spec.judge ?? []) lines.push(`Gtd-Judge: ${JSON.stringify(verdict)}`);
37643
+ if (spec.branch !== void 0) lines.push(`Gtd-Branch: ${spec.branch}`);
37644
+ if (spec.version !== void 0) lines.push(`Gtd-Version: ${spec.version}`);
37593
37645
  lines.push(`Gtd-Format: 1`);
37594
37646
  return `${formatSubject(spec.actor, spec.to, spec.from)}\n\n${lines.join("\n")}`;
37595
37647
  };
@@ -38175,6 +38227,30 @@ var ConfigDiscovery = class ConfigDiscovery extends Tag("ConfigDiscovery")() {
38175
38227
  });
38176
38228
  };
38177
38229
  //#endregion
38230
+ //#region src/workflow/fingerprint.ts
38231
+ const HASH_LENGTH = 16;
38232
+ const CONTROL_CHARACTER = /[\x00-\x1f\x7f-\x9f]/;
38233
+ const contentHash = (content) => createHash("sha256").update(content).digest("hex").slice(0, HASH_LENGTH);
38234
+ const realOr = (path) => {
38235
+ try {
38236
+ return realpathSync(path);
38237
+ } catch {
38238
+ return path;
38239
+ }
38240
+ };
38241
+ const configFingerprint = (files, root, read) => {
38242
+ const fingerprint = {};
38243
+ const realRoot = realOr(root);
38244
+ for (const file of files) {
38245
+ const path = relative(realRoot, realOr(file)).split(sep).join("/");
38246
+ if (CONTROL_CHARACTER.test(path)) continue;
38247
+ const content = read(file);
38248
+ if (content !== void 0) fingerprint[path] = contentHash(content);
38249
+ }
38250
+ return fingerprint;
38251
+ };
38252
+ const changedConfigFiles = (recorded, current) => [.../* @__PURE__ */ new Set([...Object.keys(recorded), ...Object.keys(current)])].filter((path) => recorded[path] !== current[path]).sort();
38253
+ //#endregion
38178
38254
  //#region src/workflow/Diagnostic.ts
38179
38255
  const compareSegment = (a, b) => {
38180
38256
  if (typeof a === "number" && typeof b === "number") return a - b;
@@ -38310,9 +38386,16 @@ const load = gen(function* () {
38310
38386
  },
38311
38387
  ...compiled.ui !== void 0 ? { ui: compiled.ui } : {},
38312
38388
  warnings: diagnostics.filter((d) => d.severity === "warning"),
38313
- workflowFiles: loaded.file.dependencyFiles
38389
+ fingerprint: configFingerprint(loaded.file.dependencyFiles, host.root, module.read ?? readFromDisk)
38314
38390
  };
38315
38391
  });
38392
+ const readFromDisk = (path) => {
38393
+ try {
38394
+ return readFileSync(path, "utf8");
38395
+ } catch {
38396
+ return;
38397
+ }
38398
+ };
38316
38399
  const TRANSFORM_MEMO_SIZE = 512;
38317
38400
  const memoized = (transform) => {
38318
38401
  const memo = /* @__PURE__ */ new Map();
@@ -38329,12 +38412,18 @@ const memoized = (transform) => {
38329
38412
  };
38330
38413
  let jitiModule;
38331
38414
  let transform;
38332
- const jiti = (shipped) => {
38415
+ const jiti = (shipped, local) => {
38333
38416
  const require = createRequire(import.meta.url);
38334
38417
  jitiModule ??= require("jiti");
38335
38418
  transform ??= memoized(require(join(dirname(require.resolve("jiti/package.json")), "dist", "babel.cjs")));
38336
38419
  return jitiModule.createJiti(import.meta.url, {
38337
- virtualModules: shipped.modules,
38420
+ virtualModules: new Proxy(shipped.modules, {
38421
+ has: (modules, id) => id in modules || typeof id === "string" && local?.resolve(id) !== void 0,
38422
+ get: (modules, id) => {
38423
+ const path = typeof id === "string" ? local?.resolve(id) : void 0;
38424
+ return path === void 0 ? modules[id] : local.load(path);
38425
+ }
38426
+ }),
38338
38427
  alias: shipped.missing,
38339
38428
  fsCache: false,
38340
38429
  moduleCache: false,
@@ -38531,12 +38620,9 @@ const namespaceOf = (exported) => typeof exported === "object" && exported !== n
38531
38620
  * pulled in, transitively.
38532
38621
  */
38533
38622
  const loadWorkflows = (module, shipped) => {
38534
- const cache = {};
38535
- const exports = namespaceOf(jiti(shipped).evalModule(module.source, {
38536
- filename: module.filepath,
38537
- cache
38538
- }));
38539
- const file = fileFrom(exports, module.filepath, Object.keys(cache));
38623
+ const { exports: evaluated, files } = module.read === void 0 ? evaluateFromDisk(module, shipped) : evaluateRead(module, module.read, shipped);
38624
+ const exports = namespaceOf(evaluated);
38625
+ const file = fileFrom(exports, module.filepath, files);
38540
38626
  const exported = Object.entries(exports).filter(([name, value]) => !RESERVED_EXPORTS.has(name) && isWorkflow(value));
38541
38627
  const value = defaultExport(exports);
38542
38628
  const defaultName = exported.find(([, other]) => other === value)?.[0] ?? "default";
@@ -38560,6 +38646,49 @@ const loadWorkflows = (module, shipped) => {
38560
38646
  diagnostics: nameRejections(rejections)
38561
38647
  };
38562
38648
  };
38649
+ const evaluateFromDisk = (module, shipped) => {
38650
+ const cache = {};
38651
+ return {
38652
+ exports: jiti(shipped).evalModule(module.source, {
38653
+ filename: module.filepath,
38654
+ cache
38655
+ }),
38656
+ files: Object.keys(cache)
38657
+ };
38658
+ };
38659
+ const moduleCandidates = (path) => [
38660
+ path,
38661
+ path.replace(/\.js$/, ".ts"),
38662
+ path.replace(/\.mjs$/, ".mts"),
38663
+ `${path}.ts`,
38664
+ join(path, "index.ts")
38665
+ ];
38666
+ /**
38667
+ * Evaluates the config with every local module it imports taken from `read`
38668
+ * instead of the disk. jiti matches a virtual module on the specifier as
38669
+ * written, so each module gets its own instance resolving against its own
38670
+ * directory. A specifier `read` cannot serve falls through to the disk, and
38671
+ * fails the way a missing file does.
38672
+ */
38673
+ const evaluateRead = (module, read, shipped) => {
38674
+ const files = [module.filepath];
38675
+ const evaluated = /* @__PURE__ */ new Map();
38676
+ const evaluate = (filepath, source) => jiti(shipped, {
38677
+ resolve: (specifier) => /^\.\.?\//.test(specifier) ? moduleCandidates(join(dirname(filepath), specifier)).find((candidate) => read(candidate) !== void 0) : void 0,
38678
+ load: (path) => {
38679
+ if (!evaluated.has(path)) {
38680
+ evaluated.set(path, {});
38681
+ files.push(path);
38682
+ evaluated.set(path, evaluate(path, read(path)));
38683
+ }
38684
+ return evaluated.get(path);
38685
+ }
38686
+ }).evalModule(source, { filename: filepath });
38687
+ return {
38688
+ exports: evaluate(module.filepath, module.source),
38689
+ files
38690
+ };
38691
+ };
38563
38692
  const isWorkflow = (value) => typeof value === "function" || isFactoryWorkflow(value);
38564
38693
  const defaultExport = (exports) => {
38565
38694
  const value = exports.default;
@@ -38788,35 +38917,6 @@ const resolveScopeAccess = (def, skills, vars) => gen(function* () {
38788
38917
  //#region src/workflow/Workflow.ts
38789
38918
  const knownModes = (def) => Object.keys(def.modes);
38790
38919
  //#endregion
38791
- //#region src/workflow/fingerprint.ts
38792
- const HASH_LENGTH = 16;
38793
- const CONTROL_CHARACTER = /[\x00-\x1f\x7f-\x9f]/;
38794
- const contentHash = (content) => createHash("sha256").update(content).digest("hex").slice(0, HASH_LENGTH);
38795
- const realOr = (path) => {
38796
- try {
38797
- return realpathSync(path);
38798
- } catch {
38799
- return path;
38800
- }
38801
- };
38802
- const configFingerprint = (files, root) => {
38803
- const fingerprint = {};
38804
- const realRoot = realOr(root);
38805
- for (const file of files) {
38806
- const path = relative(realRoot, realOr(file)).split(sep).join("/");
38807
- if (CONTROL_CHARACTER.test(path)) continue;
38808
- let content;
38809
- try {
38810
- content = readFileSync(file);
38811
- } catch {
38812
- continue;
38813
- }
38814
- fingerprint[path] = contentHash(content);
38815
- }
38816
- return fingerprint;
38817
- };
38818
- const changedConfigFiles = (recorded, current) => [.../* @__PURE__ */ new Set([...Object.keys(recorded), ...Object.keys(current)])].filter((path) => recorded[path] !== current[path]).sort();
38819
- //#endregion
38820
38920
  //#region src/step/planStep.ts
38821
38921
  /**
38822
38922
  * At the human review gate an unconditional `gtd uncheck '<file>'` runs
@@ -38902,6 +39002,14 @@ const planStep = (snapshot, opts = {}) => {
38902
39002
  message
38903
39003
  }
38904
39004
  },
39005
+ ...landing.keepHistory !== void 0 ? [{
39006
+ kind: "gitWrite",
39007
+ write: {
39008
+ kind: "updateRef",
39009
+ ref: landing.keepHistory,
39010
+ target: "HEAD"
39011
+ }
39012
+ }] : [],
38905
39013
  outcome
38906
39014
  ]
38907
39015
  };
@@ -39214,25 +39322,38 @@ const currentRun = gen(function* () {
39214
39322
  const config = yield* (yield* ConfigService).load;
39215
39323
  return yield* computeProcessRun(git, config.workflow);
39216
39324
  });
39217
- /** The process HEAD closes or sits inside — `gtd summary`'s run. */
39218
- const summaryRun = gen(function* () {
39219
- const git = yield* GitService;
39220
- const def = (yield* (yield* ConfigService).load).workflow;
39221
- const headEntry = (yield* git.subjectHistory(1, 0))[0];
39222
- if (headEntry === void 0) {
39325
+ const runAtTip = (git, def, tip) => gen(function* () {
39326
+ if (tip === void 0) {
39223
39327
  const history = yield* historyUpTo(git, def, void 0);
39224
39328
  return yield* runOf(history, locateEpisode(def, history));
39225
39329
  }
39226
- if (!(parseCommitMessage(headEntry.subject).parsed?.to === def.initial)) {
39227
- const history = yield* historyUpTo(git, def, headEntry.hash);
39330
+ if (!(parseCommitMessage(tip.subject).parsed?.to === def.initial)) {
39331
+ const history = yield* historyUpTo(git, def, tip.hash);
39228
39332
  return yield* runOf(history, locateEpisode(def, history));
39229
39333
  }
39230
- const parentRef = `${headEntry.hash}~1`;
39334
+ const parentRef = `${tip.hash}~1`;
39231
39335
  const before = yield* historyUpTo(git, def, parentRef);
39232
39336
  const location = locateEpisode(def, before);
39233
- let closing = yield* git.commitHistory(parentRef, headEntry.hash);
39234
- if (closing.length === 0) closing = yield* git.commitHistory(void 0, headEntry.hash);
39235
- return yield* runOf([...before, ...closing], { ...location }, headEntry.hash);
39337
+ let closing = yield* git.commitHistory(parentRef, tip.hash);
39338
+ if (closing.length === 0) closing = yield* git.commitHistory(void 0, tip.hash);
39339
+ return yield* runOf([...before, ...closing], { ...location }, tip.hash);
39340
+ });
39341
+ /** The process HEAD closes or sits inside — `gtd summary`'s run. */
39342
+ const summaryRun = gen(function* () {
39343
+ const git = yield* GitService;
39344
+ const def = (yield* (yield* ConfigService).load).workflow;
39345
+ return yield* runAtTip(git, def, (yield* git.subjectHistory(1, 0))[0]);
39346
+ });
39347
+ /** The process whose finishing commit is `tip` — reads from `tip`'s own ancestry, so it works when no branch reaches it. */
39348
+ const closedRunAt = (tip) => gen(function* () {
39349
+ const git = yield* GitService;
39350
+ const def = (yield* (yield* ConfigService).load).workflow;
39351
+ const hash = yield* git.resolveRef(tip);
39352
+ const subject = yield* git.lastCommitSubject(hash);
39353
+ return yield* runAtTip(git, def, {
39354
+ hash,
39355
+ subject
39356
+ });
39236
39357
  });
39237
39358
  const commitTree = (workspace, hash) => {
39238
39359
  let entries;
@@ -39452,13 +39573,7 @@ const costByModel = (entries) => {
39452
39573
  cost
39453
39574
  })).sort((a, b) => b.cost - a.cost || a.model.localeCompare(b.model));
39454
39575
  };
39455
- /** Resolve the rest at `ref`, or at HEAD when `ref` is `undefined`. */
39456
- const restAt = (ref, startOverrides = {}) => gen(function* () {
39457
- const git = yield* GitService;
39458
- const config = yield* (yield* ConfigService).load;
39459
- const workspace = yield* Workspace;
39460
- const host = yield* Host;
39461
- const run = yield* computeProcessRun(git, config.workflow, ref);
39576
+ const setupFor = (config, run, workspace, host, startOverrides = {}) => gen(function* () {
39462
39577
  const resolved = yield* workflowOf(config, run);
39463
39578
  const def = resolved.def;
39464
39579
  const { vars, env } = settingsFor(resolved, run.pinnedVars, host.env, startOverrides);
@@ -39482,19 +39597,34 @@ const restAt = (ref, startOverrides = {}) => gen(function* () {
39482
39597
  tree: commitTree(workspace, c.hash)
39483
39598
  }));
39484
39599
  let pendingMemo;
39485
- const setup = {
39600
+ return {
39601
+ resolved,
39486
39602
  def,
39487
- run,
39488
39603
  vars,
39489
39604
  env,
39490
- budget,
39491
- skills,
39492
- access,
39493
- workspace,
39494
- base,
39495
- episode,
39496
- pendingWorktree: () => pendingMemo ??= workspace.worktreeSync()
39605
+ setup: {
39606
+ def,
39607
+ run,
39608
+ vars,
39609
+ env,
39610
+ budget,
39611
+ skills,
39612
+ access,
39613
+ workspace,
39614
+ base,
39615
+ episode,
39616
+ pendingWorktree: () => pendingMemo ??= workspace.worktreeSync()
39617
+ }
39497
39618
  };
39619
+ });
39620
+ /** Resolve the rest at `ref`, or at HEAD when `ref` is `undefined`. */
39621
+ const restAt = (ref, startOverrides = {}) => gen(function* () {
39622
+ const git = yield* GitService;
39623
+ const config = yield* (yield* ConfigService).load;
39624
+ const workspace = yield* Workspace;
39625
+ const host = yield* Host;
39626
+ const run = yield* computeProcessRun(git, config.workflow, ref);
39627
+ const { resolved, def, vars, env, setup } = yield* setupFor(config, run, workspace, host, startOverrides);
39498
39628
  const outcome = yield* promise(() => replayFor(setup));
39499
39629
  const error = replayError(outcome);
39500
39630
  if (error !== void 0 || outcome.kind !== "rest") return yield* fail$7(error ?? /* @__PURE__ */ new Error("gtd: replay found no rest"));
@@ -39507,7 +39637,7 @@ const restAt = (ref, startOverrides = {}) => gen(function* () {
39507
39637
  path: e.path
39508
39638
  })) : [];
39509
39639
  const memory = memoryOf(outcome.trace, run);
39510
- const configNow = configFingerprint(config.workflowFiles, host.root);
39640
+ const configNow = config.fingerprint;
39511
39641
  if (ref === void 0) yield* warnConfigChanges(run, configNow, workspace);
39512
39642
  return {
39513
39643
  def,
@@ -39636,14 +39766,21 @@ const initialStepRefusal = (workflow, step, initial) => workflow !== void 0 && s
39636
39766
  kind: "refusal",
39637
39767
  message: `gtd: workflow "${workflow}" reaches step "${step}", the default workflow's first step — that is where a finished process waits, so a started process must never land there; rename the step`
39638
39768
  } : void 0;
39639
- const landingTo = (rest, to) => {
39640
- if (rest.changes.length === 0 && rest.stepDef.kind === "script" && to === rest.state) return {
39769
+ const closingTrailers = (branch) => ({
39770
+ version: GTD_VERSION,
39771
+ ...isSome(branch) ? { branch: branch.value } : {}
39772
+ });
39773
+ const isSettledNoop = (rest, to) => rest.changes.length === 0 && rest.stepDef.kind === "script" && to === rest.state;
39774
+ const landingTo = (rest, to, branch) => {
39775
+ if (isSettledNoop(rest, to)) return {
39641
39776
  kind: "noop",
39642
39777
  settled: true
39643
39778
  };
39644
- const starts = noProcessUnderway(rest) && to !== rest.def.initial;
39779
+ const underway = !noProcessUnderway(rest);
39780
+ const starts = !underway && to !== rest.def.initial;
39645
39781
  const refused = starts ? multilineRefusal(rest.vars) : void 0;
39646
39782
  if (refused !== void 0) return refused;
39783
+ const finishes = underway && to === rest.def.initial;
39647
39784
  return {
39648
39785
  kind: "commit",
39649
39786
  to,
@@ -39655,8 +39792,10 @@ const landingTo = (rest, to) => {
39655
39792
  ...starts ? {
39656
39793
  vars: rest.vars,
39657
39794
  config: rest.config
39658
- } : {}
39659
- }
39795
+ } : {},
39796
+ ...finishes ? closingTrailers(branch) : {}
39797
+ },
39798
+ ...finishes ? { keepHistory: processHistoryRef(rest.run.startHash) } : {}
39660
39799
  };
39661
39800
  };
39662
39801
  /**
@@ -39664,7 +39803,7 @@ const landingTo = (rest, to) => {
39664
39803
  * replay with the working tree as the pending turn. The target step is
39665
39804
  * computed by replaying, never matched.
39666
39805
  */
39667
- const decideLanding = (rest, verdicts) => gen(function* () {
39806
+ const decideLanding = (rest, verdicts, branch) => gen(function* () {
39668
39807
  const early = cleanLanding(rest);
39669
39808
  if (early !== void 0) return early;
39670
39809
  if (rest.stepDef.kind === "prompt" && rest.stepDef.access?.write != null) {
@@ -39680,13 +39819,14 @@ const decideLanding = (rest, verdicts) => gen(function* () {
39680
39819
  }));
39681
39820
  const to = yield* landingTarget(outcome, rest);
39682
39821
  if (typeof to !== "string") return to;
39683
- return landingTo(rest, to);
39822
+ return landingTo(rest, to, branch);
39684
39823
  });
39685
39824
  /** Where landing the pending turn would leave the process, or `undefined` when it would land nothing. */
39686
- const previewLanding = (rest) => decideLanding(rest, void 0).pipe(map$4((landing) => landing.kind === "commit" ? landing.to : void 0), catchAll(() => succeed$3(void 0)));
39825
+ const previewLanding = (rest) => decideLanding(rest, void 0, none$4()).pipe(map$4((landing) => landing.kind === "commit" ? landing.to : void 0), catchAll(() => succeed$3(void 0)));
39687
39826
  /** Every fact the pure landing planner needs, read once: the rest, its steering file, and the landing decision. */
39688
39827
  const snapshotFromRest = (rest, verdicts) => gen(function* () {
39689
- const landing = yield* decideLanding(rest, verdicts);
39828
+ const branch = yield* (yield* GitService).currentBranch();
39829
+ const landing = yield* decideLanding(rest, verdicts, branch);
39690
39830
  return {
39691
39831
  stepDef: rest.stepDef,
39692
39832
  state: rest.state,
@@ -39717,6 +39857,66 @@ const summaryFor = (run) => gen(function* () {
39717
39857
  ...settingsFor(resolved, run.pinnedVars, host.env)
39718
39858
  });
39719
39859
  });
39860
+ /** Repository-relative paths of the config files today's config and the process's own record name; one outside the repository cannot be read at a ref, so it is left out. */
39861
+ const inRepoConfigPaths = (root, files, recorded) => {
39862
+ const paths = new Set(Object.keys(recorded));
39863
+ for (const file of files) paths.add(relative(root, resolve(root, file)).split(sep).join("/"));
39864
+ return [...paths].filter((p) => p !== "" && !p.startsWith("..") && !isAbsolute(p)).sort();
39865
+ };
39866
+ const configRefusal = (tip, paths) => /* @__PURE__ */ new Error(`gtd history: refused — config differs at ${tip.slice(0, 7)}: ${paths.join(", ")}. A history ref replays under today's config, so it is unreadable after the config changes`);
39867
+ const differingConfigPaths = (git, workspace, root, config, run, hash) => gen(function* () {
39868
+ const differing = [];
39869
+ for (const path of inRepoConfigPaths(root, Object.keys(config.fingerprint), run.pinnedConfig?.files ?? {})) if ((yield* orElseSucceed(git.readFileAtRef(hash, path), () => void 0)) !== workspace.readSync(path)) differing.push(path);
39870
+ return differing;
39871
+ });
39872
+ const notClosedError = (hash, outcome) => outcome.kind === "rest" ? /* @__PURE__ */ new Error(`gtd history: ${hash.slice(0, 7)} does not close a process under today's config`) : replayError(outcome) ?? /* @__PURE__ */ new Error("gtd history: replay failed");
39873
+ const historySteps = (run) => {
39874
+ const messages = new Map(run.episode.commits.map((c) => [c.hash, c.message]));
39875
+ return run.trace.map((entry) => {
39876
+ const message = parseCommitMessage(messages.get(entry.hash) ?? "");
39877
+ return {
39878
+ hash: entry.hash,
39879
+ subject: (messages.get(entry.hash) ?? "").split("\n")[0] ?? "",
39880
+ actor: entry.actor,
39881
+ from: message.parsed?.from,
39882
+ to: entry.state,
39883
+ verdicts: message.judge
39884
+ };
39885
+ });
39886
+ };
39887
+ const versionWarningFor = (recorded) => recorded === GTD_VERSION ? void 0 : `gtd: warning: this history was recorded by ${recorded === void 0 ? "an unknown gtd version" : `gtd ${recorded}`} and is replayed by gtd ${GTD_VERSION} — a workflow imported from @pmelab/gtd/workflows may have changed since`;
39888
+ /**
39889
+ * Replays the closed run at `tip` under today's config. The workflow is not
39890
+ * fingerprinted for a version change: one imported from `@pmelab/gtd/workflows`
39891
+ * moves with every upgrade, and the version warning is the only signal.
39892
+ */
39893
+ const historyTrail = (tip) => gen(function* () {
39894
+ const git = yield* GitService;
39895
+ const config = yield* (yield* ConfigService).load;
39896
+ const workspace = yield* Workspace;
39897
+ const host = yield* Host;
39898
+ const hash = yield* git.resolveRef(tip);
39899
+ const run = yield* closedRunAt(hash);
39900
+ const differing = yield* differingConfigPaths(git, workspace, host.root, config, run, hash);
39901
+ if (differing.length > 0) return yield* fail$7(configRefusal(hash, differing));
39902
+ const { setup } = yield* setupFor(config, run, workspace, host);
39903
+ yield* workspace.episodeTrees(run.episode.base, run.episode.commits.map((c) => c.hash));
39904
+ const outcome = yield* promise(() => replayFor(setup));
39905
+ if (outcome.kind !== "ended") return yield* fail$7(notClosedError(hash, outcome));
39906
+ const steps = historySteps(run);
39907
+ const recorded = parseCommitMessage(yield* git.lastCommitMessage(hash)).version;
39908
+ const versionWarning = versionWarningFor(recorded);
39909
+ return {
39910
+ tip: hash,
39911
+ steps,
39912
+ ended: outcome.via,
39913
+ version: {
39914
+ recorded,
39915
+ running: GTD_VERSION
39916
+ },
39917
+ ...versionWarning !== void 0 ? { versionWarning } : {}
39918
+ };
39919
+ });
39720
39920
  //#endregion
39721
39921
  //#region src/emit/GitScript.ts
39722
39922
  const shellQuote$1 = (value) => `'${value.replace(/'/g, "'\\''")}'`;
@@ -39738,13 +39938,24 @@ const commitAllowEmpty = (message) => {
39738
39938
  `fi`
39739
39939
  ].join("\n");
39740
39940
  };
39741
- /** `git add -A` then `commitAllowEmpty`, joined with `&&` so a failing `git add` never reaches the commit. */
39742
- const commitAll = (message) => `git add -A &&\n${commitAllowEmpty(message)}`;
39941
+ /** `git add -A || exit 1` (an `&&` left side would not abort under `set -e`) then `commitAllowEmpty`. */
39942
+ const commitAll = (message) => `git add -A || exit 1\n${commitAllowEmpty(message)}`;
39743
39943
  const mixedResetTo = (ref) => `git reset --mixed ${shellQuote$1(ref)}`;
39744
39944
  const hardResetTo = (ref) => `git reset --hard ${shellQuote$1(ref)}`;
39745
39945
  const updateRef = (ref, hash) => `git update-ref ${shellQuote$1(ref)} ${shellQuote$1(hash)}`;
39746
39946
  /** `git update-ref -d <ref>` — idempotent: deleting a missing ref is already a no-op in real git. */
39747
39947
  const deleteRef = (ref) => `git update-ref -d ${shellQuote$1(ref)}`;
39948
+ /**
39949
+ * No `+` on the refspec: a local ref the remote's tip does not descend from
39950
+ * fails the fetch instead of being overwritten (a fast-forward still applies).
39951
+ */
39952
+ const fetchHistoryRefs = (remote) => [
39953
+ `set -eu`,
39954
+ `before=$(git for-each-ref --format='x' 'refs/gtd/history/' | wc -l)`,
39955
+ `git fetch ${shellQuote$1(remote)} 'refs/gtd/history/*:refs/gtd/history/*'`,
39956
+ `after=$(git for-each-ref --format='x' 'refs/gtd/history/' | wc -l)`,
39957
+ `printf '%s history refs arrived\\n' "$((after - before))"`
39958
+ ].join("\n");
39748
39959
  /** Marks an emitted block as print-only — mirrors `OutcomeScript.ts`'s `OUTCOME_MARKER` verbatim, so `src/testkit/EmittedScriptRecognizer.ts` recognizes either path's output identically. */
39749
39960
  const OUTCOME_MARKER$1 = "# gtd: outcome (print-only)";
39750
39961
  const printfLine$1 = (fmt, args) => `${OUTCOME_MARKER$1}\nprintf ${shellQuote$1(fmt.replace(/\n/g, "\\n"))} ${args.join(" ")}`;
@@ -39762,6 +39973,7 @@ const renderOutcome = (outcome) => {
39762
39973
  const renderGitWrite = (write) => {
39763
39974
  switch (write.kind) {
39764
39975
  case "commitAll": return commitAll(write.message);
39976
+ case "updateRef": return updateRef(write.ref, write.target);
39765
39977
  }
39766
39978
  };
39767
39979
  /**
@@ -40133,10 +40345,9 @@ init_esm();
40133
40345
  */
40134
40346
  var ToolCommands = class extends Tag("ToolCommands")() {};
40135
40347
  //#endregion
40136
- //#region src/cli/Program.ts
40348
+ //#region src/cli/Output.ts
40137
40349
  init_esm();
40138
40350
  init_wire();
40139
- init_steering();
40140
40351
  /**
40141
40352
  * A command-level failure that should exit like a CLI usage error (2), not a
40142
40353
  * generic runtime failure (1): an unknown `--json=<path>` selector, or a
@@ -40146,12 +40357,97 @@ init_steering();
40146
40357
  * about the resolved rest's own state.
40147
40358
  */
40148
40359
  var SelectorUsageError = class extends Error {};
40149
- /** The `--json=<path>` select branch, shared by all three emitting commands so none drift on the unknown-selector message. `absent` writes nothing and lets the caller's success path continue. */
40360
+ /** The `--json=<path>` select branch, shared by the emitting commands so none drift on the unknown-selector message. `absent` writes nothing and lets the caller's success path continue. */
40150
40361
  const writeSelection = (out, fields, path) => gen(function* () {
40151
40362
  const selection = selectPath(fields, path);
40152
40363
  if (selection.kind === "value") out.write(`${selection.text}\n`);
40153
40364
  else if (selection.kind === "unknown") return yield* fail$7(new SelectorUsageError(`gtd: unknown --json selector "${selection.path}" — see \`gtd --help\``));
40154
40365
  });
40366
+ //#endregion
40367
+ //#region src/cli/History.ts
40368
+ init_esm();
40369
+ /** Newest tip first. */
40370
+ const historyEntries = gen(function* () {
40371
+ const git = yield* GitService;
40372
+ const refs = (yield* git.listRefs(PROCESS_HISTORY_PREFIX)).filter(({ ref }) => ENTRY_HASH.test(ref.slice(17)));
40373
+ return yield* forEach$2(refs, ({ ref, hash, date }) => gen(function* () {
40374
+ const entry = ref.slice(17);
40375
+ return {
40376
+ ref,
40377
+ entry,
40378
+ branch: parseCommitMessage(yield* git.lastCommitMessage(hash)).branch ?? null,
40379
+ tip: hash,
40380
+ date,
40381
+ subject: yield* git.lastCommitSubject(entry)
40382
+ };
40383
+ }));
40384
+ });
40385
+ const ENTRY_HASH = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
40386
+ const HEX = /^[0-9a-f]+$/i;
40387
+ /**
40388
+ * Lookup order: full ref; then entry hash or hex prefix (unique → it, several
40389
+ * → fail listing them); then branch name (newest tip first, as `entries` is
40390
+ * ordered). A hex-looking name that matches no entry still resolves as a
40391
+ * branch. No match → fail.
40392
+ */
40393
+ const resolveHistoryRef = (arg, entries) => {
40394
+ const byRef = entries.find((e) => e.ref === arg);
40395
+ if (byRef !== void 0) return succeed$3(byRef);
40396
+ if (HEX.test(arg)) {
40397
+ const lower = arg.toLowerCase();
40398
+ const matches = entries.filter((e) => e.entry.toLowerCase().startsWith(lower));
40399
+ if (matches.length === 1) return succeed$3(matches[0]);
40400
+ if (matches.length > 1) return fail$7(/* @__PURE__ */ new Error(`gtd history: "${arg}" is ambiguous — it matches:\n${matches.map((e) => ` ${e.entry} ${e.branch ?? "-"}`).join("\n")}`));
40401
+ }
40402
+ const byBranch = entries.find((e) => e.branch === arg);
40403
+ if (byBranch !== void 0) return succeed$3(byBranch);
40404
+ return fail$7(/* @__PURE__ */ new Error(`gtd history: no history ref matches "${arg}"`));
40405
+ };
40406
+ const seven = (hash) => hash.slice(0, 7);
40407
+ /** Writes `document` per `json` (bare → whole, `=path` → one value); returns false for `off`. */
40408
+ const writeJson = (json, out, document) => gen(function* () {
40409
+ if (json.kind === "off") return false;
40410
+ if (json.kind === "document") out.write(`${JSON.stringify(document)}\n`);
40411
+ else yield* writeSelection(out, document, json.path);
40412
+ return true;
40413
+ });
40414
+ const runHistoryListCommand = (json, out) => gen(function* () {
40415
+ const entries = yield* historyEntries;
40416
+ if (yield* writeJson(json, out, entries)) return;
40417
+ if (entries.length === 0) {
40418
+ out.write("no history refs; run gtd history fetch | sh to pull them\n");
40419
+ return;
40420
+ }
40421
+ out.write(entries.map((e) => `${seven(e.entry)} ${e.branch ?? "-"} ${seven(e.tip)} ${e.date} ${e.subject}\n`).join(""));
40422
+ });
40423
+ const runHistoryShowCommand = (ref, json, out) => gen(function* () {
40424
+ const entry = yield* resolveHistoryRef(ref, yield* historyEntries);
40425
+ const trail = yield* historyTrail(entry.tip);
40426
+ const document = {
40427
+ ref: entry.ref,
40428
+ entry: entry.entry,
40429
+ branch: entry.branch,
40430
+ ...trail
40431
+ };
40432
+ if (yield* writeJson(json, out, document)) return;
40433
+ if (trail.versionWarning !== void 0) yield* (yield* Narrator).warn(trail.versionWarning);
40434
+ const lines = [`${entry.ref} (branch ${entry.branch ?? "-"}, tip ${seven(entry.tip)})`];
40435
+ for (const step of trail.steps) {
40436
+ lines.push(`${seven(step.hash)} ${step.subject}`);
40437
+ for (const v of step.verdicts) lines.push(` judge ${v.id} = ${v.answer} (p=${v.p})`);
40438
+ }
40439
+ lines.push(`ended (${trail.ended})`);
40440
+ out.write(`${lines.join("\n")}\n`);
40441
+ });
40442
+ /** Prints the script and never runs git: gtd's promise that it only decides and prints. */
40443
+ const runHistoryFetchCommand = (remote, out) => sync$1(() => {
40444
+ out.write(`${combinedScript(fetchHistoryRefs(remote), "")}\n`);
40445
+ });
40446
+ //#endregion
40447
+ //#region src/cli/Program.ts
40448
+ init_esm();
40449
+ init_wire();
40450
+ init_steering();
40155
40451
  const selfGtd = () => {
40156
40452
  const script = process.argv[1];
40157
40453
  return script === void 0 ? ["gtd"] : [process.execPath, script];
@@ -40564,12 +40860,6 @@ const runValidateCommand = (out) => gen(function* () {
40564
40860
  const resolved = yield* resolveValidateScript(rest);
40565
40861
  out.write(resolved !== void 0 && resolved.script.length > 0 ? `${resolved.script}\n` : `nothing to validate at "${rest.state}"\n`);
40566
40862
  });
40567
- /** `file:line:col: message` — the shape editors and grep already jump on. Stored 0-based, printed 1-based. A finding with a `line` but no `range`, or none at all, degrades to the shorter forms. */
40568
- const formatFinding = (file, finding) => {
40569
- if (finding.line === void 0) return finding.message;
40570
- const col = finding.range !== void 0 ? `:${finding.range.start.character + 1}` : "";
40571
- return `${file}:${finding.line + 1}${col}: ${finding.message}`;
40572
- };
40573
40863
  /**
40574
40864
  * Runs `<mode>`'s parser over `<file>`, exiting non-zero on any finding.
40575
40865
  * Resolves no workflow state and reads no config — this is what a seeded
@@ -40773,6 +41063,9 @@ const dispatchVoidCommand = (command, json, out) => {
40773
41063
  case "judge": return runJudgeCommand(json, out);
40774
41064
  case "judgeAnswer": return runJudgeAnswerCommand(json, out);
40775
41065
  case "judgeRun": return runJudgeRunCommand(command, out);
41066
+ case "historyList": return runHistoryListCommand(json, out);
41067
+ case "historyShow": return runHistoryShowCommand(command.ref, json, out);
41068
+ case "historyFetch": return runHistoryFetchCommand(command.remote, out);
40776
41069
  }
40777
41070
  };
40778
41071
  /**
@@ -40813,13 +41106,13 @@ const FLAGS = [
40813
41106
  name: "--json",
40814
41107
  arity: "optional",
40815
41108
  repeatable: false,
40816
- scope: (kind) => kind === "next" || kind === "land" || kind === "judge" || kind === "judgeAnswer" || kind === "doors",
41109
+ scope: (kind) => kind === "next" || kind === "land" || kind === "judge" || kind === "judgeAnswer" || kind === "doors" || kind === "historyList" || kind === "historyShow",
40817
41110
  decode: ([raw]) => right(raw ?? ""),
40818
- scopeError: "gtd: --json is only valid for `gtd next`/`gtd land`/`gtd judge`/`gtd judge answer`/`gtd doors` — every other command prints plain text; see `gtd install` for the driver protocol briefing",
41111
+ scopeError: "gtd: --json is only valid for `gtd next`/`gtd land`/`gtd judge`/`gtd judge answer`/`gtd doors`/`gtd history list`/`gtd history show` — every other command prints plain text; see `gtd install` for the driver protocol briefing",
40819
41112
  valueHint: "<path>",
40820
41113
  help: [
40821
- "(gtd next/gtd land/gtd judge/gtd judge answer/gtd doors only) output",
40822
- "structured JSON. Bare --json prints the whole document;",
41114
+ "(gtd next/gtd land/gtd judge/gtd judge answer/gtd doors/gtd history",
41115
+ "list/gtd history show only) output structured JSON. Bare --json prints the whole document;",
40823
41116
  "--json=<path> (a dotted key path into that document, e.g.",
40824
41117
  "kind, content, session.id) prints just that value: a",
40825
41118
  "scalar raw and unquoted, a boolean as true/false, a list",
@@ -41327,6 +41620,44 @@ const COMMAND_ROWS = [
41327
41620
  "repository. jev and llm exit 1 when they cannot answer",
41328
41621
  "every question, with nothing on stdout"
41329
41622
  ]
41623
+ },
41624
+ {
41625
+ token: "history list",
41626
+ kind: "historyList",
41627
+ arity: "none",
41628
+ details: [
41629
+ "List the finished processes kept behind refs/gtd/history/*,",
41630
+ "newest first: entry, branch, tip, date and subject per line.",
41631
+ "--json prints one array of { ref, entry, branch, tip, date,",
41632
+ "subject }. Writes nothing and never replays; with no refs it",
41633
+ "hints at `gtd history fetch | sh` and still exits 0"
41634
+ ]
41635
+ },
41636
+ {
41637
+ token: "history show",
41638
+ kind: "historyShow",
41639
+ arity: { name: "ref" },
41640
+ details: [
41641
+ "Replay one kept process under today's config and print its",
41642
+ "steps and judge verdicts. <ref> is a full ref, an entry hash",
41643
+ "(or unique prefix) or a branch name. Refuses (exit 1) when a",
41644
+ "config file differs from its content at the ref's tip. A",
41645
+ "version mismatch only warns on stderr. --json prints the",
41646
+ "trail as one document; writes nothing"
41647
+ ]
41648
+ },
41649
+ {
41650
+ token: "history fetch",
41651
+ kind: "historyFetch",
41652
+ arity: {
41653
+ name: "remote",
41654
+ optional: true
41655
+ },
41656
+ details: [
41657
+ "Print a script that fetches every refs/gtd/history/* from",
41658
+ "<remote> (default origin) and reports how many arrived — run",
41659
+ "it with `gtd history fetch | sh`. Never runs git itself"
41660
+ ]
41330
41661
  }
41331
41662
  ];
41332
41663
  const commandByToken = (token) => COMMAND_ROWS.find((r) => r.token === token);
@@ -41346,7 +41677,7 @@ const flagHeader = (row) => {
41346
41677
  };
41347
41678
  const renderHelp = () => {
41348
41679
  const commandBlocks = COMMAND_ROWS.map((row) => {
41349
- const header = row.arity === "none" ? row.token : "names" in row.arity ? `${row.token} <${row.arity.names[0]}> <${row.arity.names[1]}>` : "variadic" in row.arity ? `${row.token} <${row.arity.name}> [${row.arity.variadic}...]` : `${row.token} <${row.arity.name}>`;
41680
+ const header = row.arity === "none" ? row.token : "names" in row.arity ? `${row.token} <${row.arity.names[0]}> <${row.arity.names[1]}>` : "variadic" in row.arity ? `${row.token} <${row.arity.name}> [${row.arity.variadic}...]` : "optional" in row.arity ? `${row.token} [${row.arity.name}]` : `${row.token} <${row.arity.name}>`;
41350
41681
  return renderBlock(header, row.details);
41351
41682
  });
41352
41683
  return `Usage: gtd [command] [options]\n\nCommands:\n${[
@@ -41457,6 +41788,7 @@ const conflictViolation = (present) => {
41457
41788
  const arityError = (cmd, rest, arity) => {
41458
41789
  if (arity === "none") return rest.length > 0 ? `gtd ${cmd}: too many arguments — expected none, got: ${rest.join(", ")}` : void 0;
41459
41790
  if ("names" in arity) return pairArityError(cmd, rest, arity.names);
41791
+ if ("optional" in arity) return rest.length > 1 ? `gtd ${cmd}: too many arguments — expected at most one ${arity.name}, got: ${rest.join(", ")}` : void 0;
41460
41792
  if (rest.length === 0) return `gtd ${cmd}: missing ${arity.name} argument`;
41461
41793
  if (!("variadic" in arity) && rest.length > 1) return `gtd ${cmd}: too many arguments — expected one ${arity.name}, got: ${rest.join(", ")}`;
41462
41794
  };
@@ -41507,7 +41839,9 @@ const parseArgv = (argv) => {
41507
41839
  kind: "output",
41508
41840
  stdout: renderHelp()
41509
41841
  };
41510
- const row = first === void 0 ? void 0 : commandByToken(first);
41842
+ const isHistory = first === "history";
41843
+ const row = first === void 0 ? void 0 : commandByToken(isHistory ? `history ${positionals[1] ?? ""}` : first);
41844
+ if (isHistory && row === void 0) return usagePlan("gtd history: expected a subcommand — list, show <ref> or fetch [remote]", jsonSeen);
41511
41845
  const judgeAnswer = row?.kind === "judge" && positionals[1] === "answer";
41512
41846
  const selectsStart = workflowPresent && first === void 0;
41513
41847
  const judgeRun = row?.kind === "judge" && positionals[1] === "run";
@@ -41518,11 +41852,11 @@ const parseArgv = (argv) => {
41518
41852
  if (first === void 0) return usagePlan("gtd: missing command — gtd decides and prints, a driver executes; run `gtd install`, or copy one from https://github.com/pmelab/gtd/blob/main/docs/driver.md's \"A complete minimal driver\" section and run that, or see usage above (`gtd --help`)", jsonSeen, renderHelp());
41519
41853
  return usagePlan(`unknown command '${first}'`, jsonSeen);
41520
41854
  }
41521
- const restPositionals = first === void 0 ? positionals : positionals.slice(judgeAnswer || judgeRun ? 2 : 1);
41855
+ const restPositionals = first === void 0 ? positionals : positionals.slice(judgeAnswer || judgeRun || isHistory ? 2 : 1);
41522
41856
  if (kind === "start" && first === void 0) {
41523
41857
  if (restPositionals.length > 0) return usagePlan(`gtd: too many arguments — expected none, got: ${restPositionals.join(", ")}`, jsonSeen);
41524
41858
  } else {
41525
- const arityMsg = kind === "check" && restPositionals.length === 0 && present.has("--open-threads") ? void 0 : arityError(first, restPositionals, row.arity);
41859
+ const arityMsg = kind === "check" && restPositionals.length === 0 && present.has("--open-threads") ? void 0 : arityError(isHistory ? row.token : first, restPositionals, row.arity);
41526
41860
  if (arityMsg !== void 0) return usagePlan(arityMsg, jsonSeen);
41527
41861
  }
41528
41862
  const violation = scopeViolation(kind, present);
@@ -41611,6 +41945,24 @@ const parseArgv = (argv) => {
41611
41945
  verbose
41612
41946
  };
41613
41947
  }
41948
+ if (kind === "historyShow") return {
41949
+ kind: "command",
41950
+ command: {
41951
+ kind: "historyShow",
41952
+ ref: restPositionals[0]
41953
+ },
41954
+ json,
41955
+ verbose
41956
+ };
41957
+ if (kind === "historyFetch") return {
41958
+ kind: "command",
41959
+ command: {
41960
+ kind: "historyFetch",
41961
+ remote: restPositionals[0] ?? "origin"
41962
+ },
41963
+ json,
41964
+ verbose
41965
+ };
41614
41966
  if (kind === "uncheck") return {
41615
41967
  kind: "command",
41616
41968
  command: {
@@ -41877,9 +42229,9 @@ function getErrorShape(opts) {
41877
42229
  };
41878
42230
  if (config.isDev && typeof opts.error.stack === "string") shape.data.stack = opts.error.stack;
41879
42231
  if (typeof path === "string") shape.data.path = path;
41880
- return config.errorFormatter((0, import_objectSpread2$5.default)((0, import_objectSpread2$5.default)({}, opts), {}, { shape }));
42232
+ return config.errorFormatter((0, import_objectSpread2$7.default)((0, import_objectSpread2$7.default)({}, opts), {}, { shape }));
41881
42233
  }
41882
- var __create, __defProp, __getOwnPropDesc, __getOwnPropNames, __getProtoOf, __hasOwnProp, __commonJS, __copyProps, __toESM, noop, freezeIfAvailable, createRecursiveProxy, JSONRPC2_TO_HTTP_CODE, require_typeof, require_toPrimitive, require_toPropertyKey, require_defineProperty, require_objectSpread2, import_objectSpread2$5;
42234
+ var __create, __defProp, __getOwnPropDesc, __getOwnPropNames, __getProtoOf, __hasOwnProp, __commonJS, __copyProps, __toESM, noop, freezeIfAvailable, createRecursiveProxy, JSONRPC2_TO_HTTP_CODE, require_typeof, require_toPrimitive, require_toPropertyKey, require_defineProperty, require_objectSpread2, import_objectSpread2$7;
41883
42235
  var init_getErrorShape_BPSzUA7W = __esmMin((() => {
41884
42236
  init_codes_DagpWZLc();
41885
42237
  __create = Object.create;
@@ -42004,7 +42356,7 @@ var init_getErrorShape_BPSzUA7W = __esmMin((() => {
42004
42356
  }
42005
42357
  module.exports = _objectSpread2, module.exports.__esModule = true, module.exports["default"] = module.exports;
42006
42358
  } });
42007
- import_objectSpread2$5 = __toESM(require_objectSpread2(), 1);
42359
+ import_objectSpread2$7 = __toESM(require_objectSpread2(), 1);
42008
42360
  }));
42009
42361
  //#endregion
42010
42362
  //#region node_modules/@trpc/server/dist/tracked-DWInO6EQ.mjs
@@ -42039,8 +42391,8 @@ function getDataTransformer(transformer) {
42039
42391
  };
42040
42392
  }
42041
42393
  function transformTRPCResponseItem(config, item) {
42042
- if ("error" in item) return (0, import_objectSpread2$1$5.default)((0, import_objectSpread2$1$5.default)({}, item), {}, { error: config.transformer.output.serialize(item.error) });
42043
- if ("data" in item.result) return (0, import_objectSpread2$1$5.default)((0, import_objectSpread2$1$5.default)({}, item), {}, { result: (0, import_objectSpread2$1$5.default)((0, import_objectSpread2$1$5.default)({}, item.result), {}, { data: config.transformer.output.serialize(item.result.data) }) });
42394
+ if ("error" in item) return (0, import_objectSpread2$1$6.default)((0, import_objectSpread2$1$6.default)({}, item), {}, { error: config.transformer.output.serialize(item.error) });
42395
+ if ("data" in item.result) return (0, import_objectSpread2$1$6.default)((0, import_objectSpread2$1$6.default)({}, item), {}, { result: (0, import_objectSpread2$1$6.default)((0, import_objectSpread2$1$6.default)({}, item.result), {}, { data: config.transformer.output.serialize(item.result.data) }) });
42044
42396
  return item;
42045
42397
  }
42046
42398
  /**
@@ -42121,13 +42473,13 @@ function createRouterFactory(config) {
42121
42473
  return aggregate;
42122
42474
  }
42123
42475
  const record = step(input);
42124
- const _def = (0, import_objectSpread2$6.default)((0, import_objectSpread2$6.default)({
42476
+ const _def = (0, import_objectSpread2$4.default)((0, import_objectSpread2$4.default)({
42125
42477
  _config: config,
42126
42478
  router: true,
42127
42479
  procedures,
42128
42480
  lazy: lazy$1
42129
42481
  }, emptyRouter), {}, { record });
42130
- return (0, import_objectSpread2$6.default)((0, import_objectSpread2$6.default)({}, record), {}, {
42482
+ return (0, import_objectSpread2$4.default)((0, import_objectSpread2$4.default)({}, record), {}, {
42131
42483
  _def,
42132
42484
  createCaller: createCallerFactory()({ _def })
42133
42485
  });
@@ -42218,7 +42570,7 @@ function mergeRouters(...routerList) {
42218
42570
  function isTrackedEnvelope(value) {
42219
42571
  return Array.isArray(value) && value[2] === trackedSymbol;
42220
42572
  }
42221
- var defaultFormatter, import_defineProperty$2, UnknownCauseError, TRPCError, import_objectSpread2$1$5, defaultTransformer, import_objectSpread2$6, lazyMarker, emptyRouter, reservedWords, trackedSymbol;
42573
+ var defaultFormatter, import_defineProperty$2, UnknownCauseError, TRPCError, import_objectSpread2$1$6, defaultTransformer, import_objectSpread2$4, lazyMarker, emptyRouter, reservedWords, trackedSymbol;
42222
42574
  var init_tracked_DWInO6EQ = __esmMin((() => {
42223
42575
  init_getErrorShape_BPSzUA7W();
42224
42576
  init_codes_DagpWZLc();
@@ -42245,7 +42597,7 @@ var init_tracked_DWInO6EQ = __esmMin((() => {
42245
42597
  (_this$cause = this.cause) !== null && _this$cause !== void 0 || (this.cause = cause);
42246
42598
  }
42247
42599
  };
42248
- import_objectSpread2$1$5 = __toESM(require_objectSpread2(), 1);
42600
+ import_objectSpread2$1$6 = __toESM(require_objectSpread2(), 1);
42249
42601
  defaultTransformer = {
42250
42602
  input: {
42251
42603
  serialize: (obj) => obj,
@@ -42256,7 +42608,7 @@ var init_tracked_DWInO6EQ = __esmMin((() => {
42256
42608
  deserialize: (obj) => obj
42257
42609
  }
42258
42610
  };
42259
- import_objectSpread2$6 = __toESM(require_objectSpread2(), 1);
42611
+ import_objectSpread2$4 = __toESM(require_objectSpread2(), 1);
42260
42612
  lazyMarker = "lazyMarker";
42261
42613
  emptyRouter = {
42262
42614
  _ctx: null,
@@ -43307,7 +43659,7 @@ async function resolveResponse(opts) {
43307
43659
  }));
43308
43660
  return isObservable(result.data) ? observableToAsyncIterable(result.data, opts.req.signal) : result.data;
43309
43661
  });
43310
- const stream = sseStreamProducer((0, import_objectSpread2$4.default)((0, import_objectSpread2$4.default)({}, config.sse), {}, {
43662
+ const stream = sseStreamProducer((0, import_objectSpread2$5.default)((0, import_objectSpread2$5.default)({}, config.sse), {}, {
43311
43663
  data: iterable,
43312
43664
  serialize: (v) => config.transformer.output.serialize(v),
43313
43665
  formatError(errorOpts) {
@@ -43382,7 +43734,7 @@ async function resolveResponse(opts) {
43382
43734
  headers,
43383
43735
  untransformedJSON: null
43384
43736
  });
43385
- const stream = jsonlStreamProducer((0, import_objectSpread2$4.default)((0, import_objectSpread2$4.default)({}, config.jsonl), {}, {
43737
+ const stream = jsonlStreamProducer((0, import_objectSpread2$5.default)((0, import_objectSpread2$5.default)({}, config.jsonl), {}, {
43386
43738
  maxDepth: Infinity,
43387
43739
  data: rpcCalls.map(async (res, index) => {
43388
43740
  const [error, result] = await res;
@@ -43506,13 +43858,13 @@ async function resolveResponse(opts) {
43506
43858
  });
43507
43859
  }
43508
43860
  }
43509
- var import_objectSpread2$1$3, jsonContentTypeHandler, handlers, import_defineProperty$1, _Symbol$toStringTag, subscribableCache, NOOP, Unpromise, _Symbol, _Symbol$dispose, _Symbol2, _Symbol2$asyncDispose, disposablePromiseTimerResult, require_usingCtx, require_OverloadYield, require_awaitAsyncGenerator, require_wrapAsyncGenerator, import_usingCtx$4, import_awaitAsyncGenerator$4, import_wrapAsyncGenerator$5, import_usingCtx$3, import_awaitAsyncGenerator$3, import_wrapAsyncGenerator$4, import_usingCtx$2, import_awaitAsyncGenerator$2, import_wrapAsyncGenerator$3, PING_SYM, require_asyncIterator, import_awaitAsyncGenerator$1, import_wrapAsyncGenerator$2, import_usingCtx$1, import_asyncIterator$1, CHUNK_VALUE_TYPE_PROMISE, CHUNK_VALUE_TYPE_ASYNC_ITERABLE, PROMISE_STATUS_FULFILLED, PROMISE_STATUS_REJECTED, ASYNC_ITERABLE_STATUS_RETURN, ASYNC_ITERABLE_STATUS_YIELD, ASYNC_ITERABLE_STATUS_ERROR, MaxDepthError, require_asyncGeneratorDelegate, import_asyncIterator, import_awaitAsyncGenerator, import_wrapAsyncGenerator$1, import_asyncGeneratorDelegate, PING_EVENT, SERIALIZED_ERROR_EVENT, CONNECTED_EVENT, RETURN_EVENT, sseHeaders, import_wrapAsyncGenerator, import_objectSpread2$4, TYPE_ACCEPTED_METHOD_MAP, TYPE_ACCEPTED_METHOD_MAP_WITH_METHOD_OVERRIDE;
43861
+ var import_objectSpread2$1$4, jsonContentTypeHandler, handlers, import_defineProperty$1, _Symbol$toStringTag, subscribableCache, NOOP, Unpromise, _Symbol, _Symbol$dispose, _Symbol2, _Symbol2$asyncDispose, disposablePromiseTimerResult, require_usingCtx, require_OverloadYield, require_awaitAsyncGenerator, require_wrapAsyncGenerator, import_usingCtx$4, import_awaitAsyncGenerator$4, import_wrapAsyncGenerator$5, import_usingCtx$3, import_awaitAsyncGenerator$3, import_wrapAsyncGenerator$4, import_usingCtx$2, import_awaitAsyncGenerator$2, import_wrapAsyncGenerator$3, PING_SYM, require_asyncIterator, import_awaitAsyncGenerator$1, import_wrapAsyncGenerator$2, import_usingCtx$1, import_asyncIterator$1, CHUNK_VALUE_TYPE_PROMISE, CHUNK_VALUE_TYPE_ASYNC_ITERABLE, PROMISE_STATUS_FULFILLED, PROMISE_STATUS_REJECTED, ASYNC_ITERABLE_STATUS_RETURN, ASYNC_ITERABLE_STATUS_YIELD, ASYNC_ITERABLE_STATUS_ERROR, MaxDepthError, require_asyncGeneratorDelegate, import_asyncIterator, import_awaitAsyncGenerator, import_wrapAsyncGenerator$1, import_asyncGeneratorDelegate, PING_EVENT, SERIALIZED_ERROR_EVENT, CONNECTED_EVENT, RETURN_EVENT, sseHeaders, import_wrapAsyncGenerator, import_objectSpread2$5, TYPE_ACCEPTED_METHOD_MAP, TYPE_ACCEPTED_METHOD_MAP_WITH_METHOD_OVERRIDE;
43510
43862
  var init_resolveResponse_CdASWfAV = __esmMin((() => {
43511
43863
  init_getErrorShape_BPSzUA7W();
43512
43864
  init_codes_DagpWZLc();
43513
43865
  init_tracked_DWInO6EQ();
43514
43866
  init_observable_UMO3vUa_();
43515
- import_objectSpread2$1$3 = __toESM(require_objectSpread2(), 1);
43867
+ import_objectSpread2$1$4 = __toESM(require_objectSpread2(), 1);
43516
43868
  jsonContentTypeHandler = {
43517
43869
  isMatch(req) {
43518
43870
  var _req$headers$get;
@@ -43562,7 +43914,7 @@ var init_resolveResponse_CdASWfAV = __esmMin((() => {
43562
43914
  if ((procedure === null || procedure === void 0 ? void 0 : procedure._def.type) === "subscription") {
43563
43915
  var _ref2, _opts$headers$get;
43564
43916
  const lastEventId = (_ref2 = (_opts$headers$get = opts.headers.get("last-event-id")) !== null && _opts$headers$get !== void 0 ? _opts$headers$get : opts.searchParams.get("lastEventId")) !== null && _ref2 !== void 0 ? _ref2 : opts.searchParams.get("Last-Event-Id");
43565
- if (lastEventId) if (isObject$2(input)) input = (0, import_objectSpread2$1$3.default)((0, import_objectSpread2$1$3.default)({}, input), {}, { lastEventId });
43917
+ if (lastEventId) if (isObject$2(input)) input = (0, import_objectSpread2$1$4.default)((0, import_objectSpread2$1$4.default)({}, input), {}, { lastEventId });
43566
43918
  else {
43567
43919
  var _input;
43568
43920
  (_input = input) !== null && _input !== void 0 || (input = { lastEventId });
@@ -44072,7 +44424,7 @@ var init_resolveResponse_CdASWfAV = __esmMin((() => {
44072
44424
  Connection: "keep-alive"
44073
44425
  };
44074
44426
  import_wrapAsyncGenerator = __toESM(require_wrapAsyncGenerator(), 1);
44075
- import_objectSpread2$4 = __toESM(require_objectSpread2(), 1);
44427
+ import_objectSpread2$5 = __toESM(require_objectSpread2(), 1);
44076
44428
  TYPE_ACCEPTED_METHOD_MAP = {
44077
44429
  mutation: ["POST"],
44078
44430
  query: ["GET"],
@@ -44085,570 +44437,58 @@ var init_resolveResponse_CdASWfAV = __esmMin((() => {
44085
44437
  };
44086
44438
  }));
44087
44439
  //#endregion
44088
- //#region node_modules/@trpc/server/dist/initTRPC-BRf4imah.mjs
44089
- /**
44090
- * @internal
44091
- */
44092
- function createMiddlewareFactory() {
44093
- function createMiddlewareInner(middlewares) {
44094
- return {
44095
- _middlewares: middlewares,
44096
- unstable_pipe(middlewareBuilderOrFn) {
44097
- const pipedMiddleware = "_middlewares" in middlewareBuilderOrFn ? middlewareBuilderOrFn._middlewares : [middlewareBuilderOrFn];
44098
- return createMiddlewareInner([...middlewares, ...pipedMiddleware]);
44099
- }
44100
- };
44101
- }
44102
- function createMiddleware(fn) {
44103
- return createMiddlewareInner([fn]);
44104
- }
44105
- return createMiddleware;
44106
- }
44107
- /**
44108
- * @internal
44109
- * Please note, `trpc-openapi` uses this function.
44110
- */
44111
- function createInputMiddleware(parse) {
44112
- const inputMiddleware = async function inputValidatorMiddleware(opts) {
44113
- let parsedInput;
44114
- const rawInput = await opts.getRawInput();
44115
- try {
44116
- parsedInput = await parse(rawInput);
44117
- } catch (cause) {
44118
- throw new TRPCError({
44119
- code: "BAD_REQUEST",
44120
- cause
44121
- });
44122
- }
44123
- const combinedInput = isObject$2(opts.input) && isObject$2(parsedInput) ? (0, import_objectSpread2$2.default)((0, import_objectSpread2$2.default)({}, opts.input), parsedInput) : parsedInput;
44124
- return opts.next({ input: combinedInput });
44125
- };
44126
- inputMiddleware._type = "input";
44127
- return inputMiddleware;
44128
- }
44129
- /**
44130
- * @internal
44131
- */
44132
- function createOutputMiddleware(parse) {
44133
- const outputMiddleware = async function outputValidatorMiddleware({ next }) {
44134
- const result = await next();
44135
- if (!result.ok) return result;
44136
- try {
44137
- const data = await parse(result.data);
44138
- return (0, import_objectSpread2$2.default)((0, import_objectSpread2$2.default)({}, result), {}, { data });
44139
- } catch (cause) {
44140
- throw new TRPCError({
44141
- message: "Output validation failed",
44142
- code: "INTERNAL_SERVER_ERROR",
44143
- cause
44144
- });
44145
- }
44146
- };
44147
- outputMiddleware._type = "output";
44148
- return outputMiddleware;
44149
- }
44150
- function getParseFn(procedureParser) {
44151
- const parser = procedureParser;
44152
- const isStandardSchema = "~standard" in parser;
44153
- if (typeof parser === "function" && typeof parser.assert === "function") return parser.assert.bind(parser);
44154
- if (typeof parser === "function" && !isStandardSchema) return parser;
44155
- if (typeof parser.parseAsync === "function") return parser.parseAsync.bind(parser);
44156
- if (typeof parser.parse === "function") return parser.parse.bind(parser);
44157
- if (typeof parser.validateSync === "function") return parser.validateSync.bind(parser);
44158
- if (typeof parser.create === "function") return parser.create.bind(parser);
44159
- if (typeof parser.assert === "function") return (value) => {
44160
- parser.assert(value);
44161
- return value;
44162
- };
44163
- if (isStandardSchema) return async (value) => {
44164
- const result = await parser["~standard"].validate(value);
44165
- if (result.issues) throw new StandardSchemaV1Error(result.issues);
44166
- return result.value;
44167
- };
44168
- throw new Error("Could not find a validator fn");
44169
- }
44170
- function createNewBuilder(def1, def2) {
44171
- const { middlewares = [], inputs, meta } = def2, rest = (0, import_objectWithoutProperties.default)(def2, _excluded);
44172
- return createBuilder((0, import_objectSpread2$1$1.default)((0, import_objectSpread2$1$1.default)({}, mergeWithoutOverrides(def1, rest)), {}, {
44173
- inputs: [...def1.inputs, ...inputs !== null && inputs !== void 0 ? inputs : []],
44174
- middlewares: [...def1.middlewares, ...middlewares],
44175
- meta: def1.meta && meta ? (0, import_objectSpread2$1$1.default)((0, import_objectSpread2$1$1.default)({}, def1.meta), meta) : meta !== null && meta !== void 0 ? meta : def1.meta
44176
- }));
44177
- }
44178
- function createBuilder(initDef = {}) {
44179
- const _def = (0, import_objectSpread2$1$1.default)({
44180
- procedure: true,
44181
- inputs: [],
44182
- middlewares: []
44183
- }, initDef);
44184
- return {
44185
- _def,
44186
- input(input) {
44187
- const parser = getParseFn(input);
44188
- return createNewBuilder(_def, {
44189
- inputs: [input],
44190
- middlewares: [createInputMiddleware(parser)]
44191
- });
44192
- },
44193
- output(output) {
44194
- const parser = getParseFn(output);
44195
- return createNewBuilder(_def, {
44196
- output,
44197
- middlewares: [createOutputMiddleware(parser)]
44198
- });
44199
- },
44200
- meta(meta) {
44201
- return createNewBuilder(_def, { meta });
44202
- },
44203
- use(middlewareBuilderOrFn) {
44204
- const middlewares = "_middlewares" in middlewareBuilderOrFn ? middlewareBuilderOrFn._middlewares : [middlewareBuilderOrFn];
44205
- return createNewBuilder(_def, { middlewares });
44206
- },
44207
- unstable_concat(builder$1) {
44208
- return createNewBuilder(_def, builder$1._def);
44209
- },
44210
- concat(builder$1) {
44211
- return createNewBuilder(_def, builder$1._def);
44212
- },
44213
- query(resolver) {
44214
- return createResolver((0, import_objectSpread2$1$1.default)((0, import_objectSpread2$1$1.default)({}, _def), {}, { type: "query" }), resolver);
44215
- },
44216
- mutation(resolver) {
44217
- return createResolver((0, import_objectSpread2$1$1.default)((0, import_objectSpread2$1$1.default)({}, _def), {}, { type: "mutation" }), resolver);
44218
- },
44219
- subscription(resolver) {
44220
- return createResolver((0, import_objectSpread2$1$1.default)((0, import_objectSpread2$1$1.default)({}, _def), {}, { type: "subscription" }), resolver);
44440
+ //#region node_modules/@trpc/server/dist/adapters/fetch/index.mjs
44441
+ async function fetchRequestHandler(opts) {
44442
+ const resHeaders = new Headers();
44443
+ const createContext = async (innerOpts) => {
44444
+ var _opts$createContext;
44445
+ return (_opts$createContext = opts.createContext) === null || _opts$createContext === void 0 ? void 0 : _opts$createContext.call(opts, (0, import_objectSpread2$3.default)({
44446
+ req: opts.req,
44447
+ resHeaders
44448
+ }, innerOpts));
44449
+ };
44450
+ const url = new URL(opts.req.url);
44451
+ const pathname = trimSlashes(url.pathname);
44452
+ const endpoint = trimSlashes(opts.endpoint);
44453
+ const path = trimSlashes(pathname.slice(endpoint.length));
44454
+ return await resolveResponse((0, import_objectSpread2$3.default)((0, import_objectSpread2$3.default)({}, opts), {}, {
44455
+ req: opts.req,
44456
+ createContext,
44457
+ path,
44458
+ error: null,
44459
+ onError(o) {
44460
+ var _opts$onError;
44461
+ opts === null || opts === void 0 || (_opts$onError = opts.onError) === null || _opts$onError === void 0 || _opts$onError.call(opts, (0, import_objectSpread2$3.default)((0, import_objectSpread2$3.default)({}, o), {}, { req: opts.req }));
44221
44462
  },
44222
- experimental_caller(caller) {
44223
- return createNewBuilder(_def, { caller });
44224
- }
44225
- };
44226
- }
44227
- function createResolver(_defIn, resolver) {
44228
- const finalBuilder = createNewBuilder(_defIn, {
44229
- resolver,
44230
- middlewares: [async function resolveMiddleware(opts) {
44231
- const data = await resolver(opts);
44232
- return {
44233
- marker: middlewareMarker,
44234
- ok: true,
44235
- data,
44236
- ctx: opts.ctx
44237
- };
44238
- }]
44239
- });
44240
- const _def = (0, import_objectSpread2$1$1.default)((0, import_objectSpread2$1$1.default)({}, finalBuilder._def), {}, {
44241
- type: _defIn.type,
44242
- experimental_caller: Boolean(finalBuilder._def.caller),
44243
- meta: finalBuilder._def.meta,
44244
- $types: null
44245
- });
44246
- const invoke = createProcedureCaller(finalBuilder._def);
44247
- const callerOverride = finalBuilder._def.caller;
44248
- if (!callerOverride) return invoke;
44249
- const callerWrapper = async (...args) => {
44250
- return await callerOverride({
44251
- args,
44252
- invoke,
44253
- _def
44254
- });
44255
- };
44256
- callerWrapper._def = _def;
44257
- return callerWrapper;
44258
- }
44259
- async function callRecursive(index, _def, opts) {
44260
- try {
44261
- const middleware = _def.middlewares[index];
44262
- return await middleware((0, import_objectSpread2$1$1.default)((0, import_objectSpread2$1$1.default)({}, opts), {}, {
44263
- meta: _def.meta,
44264
- input: opts.input,
44265
- next(_nextOpts) {
44266
- var _nextOpts$getRawInput;
44267
- const nextOpts = _nextOpts;
44268
- return callRecursive(index + 1, _def, (0, import_objectSpread2$1$1.default)((0, import_objectSpread2$1$1.default)({}, opts), {}, {
44269
- ctx: (nextOpts === null || nextOpts === void 0 ? void 0 : nextOpts.ctx) ? (0, import_objectSpread2$1$1.default)((0, import_objectSpread2$1$1.default)({}, opts.ctx), nextOpts.ctx) : opts.ctx,
44270
- input: nextOpts && "input" in nextOpts ? nextOpts.input : opts.input,
44271
- getRawInput: (_nextOpts$getRawInput = nextOpts === null || nextOpts === void 0 ? void 0 : nextOpts.getRawInput) !== null && _nextOpts$getRawInput !== void 0 ? _nextOpts$getRawInput : opts.getRawInput
44272
- }));
44273
- }
44274
- }));
44275
- } catch (cause) {
44276
- return {
44277
- ok: false,
44278
- error: getTRPCErrorFromUnknown(cause),
44279
- marker: middlewareMarker
44280
- };
44281
- }
44282
- }
44283
- function createProcedureCaller(_def) {
44284
- async function procedure(opts) {
44285
- if (!opts || !("getRawInput" in opts)) throw new Error(codeblock);
44286
- const result = await callRecursive(0, _def, opts);
44287
- if (!result) throw new TRPCError({
44288
- code: "INTERNAL_SERVER_ERROR",
44289
- message: "No result from middlewares - did you forget to `return next()`?"
44290
- });
44291
- if (!result.ok) throw result.error;
44292
- return result.data;
44293
- }
44294
- procedure._def = _def;
44295
- procedure.procedure = true;
44296
- procedure.meta = _def.meta;
44297
- return procedure;
44298
- }
44299
- var import_objectSpread2$2, middlewareMarker, import_defineProperty, StandardSchemaV1Error, require_objectWithoutPropertiesLoose, import_objectWithoutProperties, import_objectSpread2$1$1, _excluded, codeblock, _globalThis$process, _globalThis$process2, _globalThis$process3, isServerDefault, import_objectSpread2$3, initTRPC;
44300
- var init_initTRPC_BRf4imah = __esmMin((() => {
44301
- init_getErrorShape_BPSzUA7W();
44302
- init_codes_DagpWZLc();
44303
- init_tracked_DWInO6EQ();
44304
- import_objectSpread2$2 = __toESM(require_objectSpread2(), 1);
44305
- middlewareMarker = "middlewareMarker";
44306
- import_defineProperty = __toESM(require_defineProperty(), 1);
44307
- StandardSchemaV1Error = class extends Error {
44308
- /**
44309
- * Creates a schema error with useful information.
44310
- *
44311
- * @param issues The schema issues.
44312
- */
44313
- constructor(issues) {
44314
- var _issues$;
44315
- super((_issues$ = issues[0]) === null || _issues$ === void 0 ? void 0 : _issues$.message);
44316
- (0, import_defineProperty.default)(this, "issues", void 0);
44317
- this.name = "SchemaError";
44318
- this.issues = issues;
44319
- }
44320
- };
44321
- require_objectWithoutPropertiesLoose = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/objectWithoutPropertiesLoose.js"(exports, module) {
44322
- function _objectWithoutPropertiesLoose(r, e) {
44323
- if (null == r) return {};
44324
- var t = {};
44325
- for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
44326
- if (e.includes(n)) continue;
44327
- t[n] = r[n];
44328
- }
44329
- return t;
44330
- }
44331
- module.exports = _objectWithoutPropertiesLoose, module.exports.__esModule = true, module.exports["default"] = module.exports;
44332
- } });
44333
- import_objectWithoutProperties = __toESM(__commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/objectWithoutProperties.js"(exports, module) {
44334
- var objectWithoutPropertiesLoose = require_objectWithoutPropertiesLoose();
44335
- function _objectWithoutProperties$1(e, t) {
44336
- if (null == e) return {};
44337
- var o, r, i = objectWithoutPropertiesLoose(e, t);
44338
- if (Object.getOwnPropertySymbols) {
44339
- var s = Object.getOwnPropertySymbols(e);
44340
- for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
44463
+ responseMeta(data) {
44464
+ var _opts$responseMeta;
44465
+ const meta = (_opts$responseMeta = opts.responseMeta) === null || _opts$responseMeta === void 0 ? void 0 : _opts$responseMeta.call(opts, data);
44466
+ if (meta === null || meta === void 0 ? void 0 : meta.headers) {
44467
+ if (meta.headers instanceof Headers) for (const [key, value] of meta.headers.entries()) resHeaders.append(key, value);
44468
+ else
44469
+ /**
44470
+ * @deprecated, delete in v12
44471
+ */
44472
+ for (const [key, value] of Object.entries(meta.headers)) if (Array.isArray(value)) for (const v of value) resHeaders.append(key, v);
44473
+ else if (typeof value === "string") resHeaders.set(key, value);
44341
44474
  }
44342
- return i;
44343
- }
44344
- module.exports = _objectWithoutProperties$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
44345
- } })(), 1);
44346
- import_objectSpread2$1$1 = __toESM(require_objectSpread2(), 1);
44347
- _excluded = [
44348
- "middlewares",
44349
- "inputs",
44350
- "meta"
44351
- ];
44352
- codeblock = `
44353
- This is a client-only function.
44354
- If you want to call this function on the server, see https://trpc.io/docs/v11/server/server-side-calls
44355
- `.trim();
44356
- isServerDefault = typeof window === "undefined" || "Deno" in window || ((_globalThis$process = globalThis.process) === null || _globalThis$process === void 0 || (_globalThis$process = _globalThis$process.env) === null || _globalThis$process === void 0 ? void 0 : _globalThis$process["NODE_ENV"]) === "test" || !!((_globalThis$process2 = globalThis.process) === null || _globalThis$process2 === void 0 || (_globalThis$process2 = _globalThis$process2.env) === null || _globalThis$process2 === void 0 ? void 0 : _globalThis$process2["JEST_WORKER_ID"]) || !!((_globalThis$process3 = globalThis.process) === null || _globalThis$process3 === void 0 || (_globalThis$process3 = _globalThis$process3.env) === null || _globalThis$process3 === void 0 ? void 0 : _globalThis$process3["VITEST_WORKER_ID"]);
44357
- import_objectSpread2$3 = __toESM(require_objectSpread2(), 1);
44358
- initTRPC = new class TRPCBuilder {
44359
- /**
44360
- * Add a context shape as a generic to the root object
44361
- * @see https://trpc.io/docs/v11/server/context
44362
- */
44363
- context() {
44364
- return new TRPCBuilder();
44365
- }
44366
- /**
44367
- * Add a meta shape as a generic to the root object
44368
- * @see https://trpc.io/docs/v11/quickstart
44369
- */
44370
- meta() {
44371
- return new TRPCBuilder();
44372
- }
44373
- /**
44374
- * Create the root object
44375
- * @see https://trpc.io/docs/v11/server/routers#initialize-trpc
44376
- */
44377
- create(opts) {
44378
- var _opts$transformer, _opts$isDev, _globalThis$process$1, _opts$allowOutsideOfS, _opts$errorFormatter, _opts$isServer;
44379
- const config = (0, import_objectSpread2$3.default)((0, import_objectSpread2$3.default)({}, opts), {}, {
44380
- transformer: getDataTransformer((_opts$transformer = opts === null || opts === void 0 ? void 0 : opts.transformer) !== null && _opts$transformer !== void 0 ? _opts$transformer : defaultTransformer),
44381
- isDev: (_opts$isDev = opts === null || opts === void 0 ? void 0 : opts.isDev) !== null && _opts$isDev !== void 0 ? _opts$isDev : ((_globalThis$process$1 = globalThis.process) === null || _globalThis$process$1 === void 0 ? void 0 : _globalThis$process$1.env["NODE_ENV"]) !== "production",
44382
- allowOutsideOfServer: (_opts$allowOutsideOfS = opts === null || opts === void 0 ? void 0 : opts.allowOutsideOfServer) !== null && _opts$allowOutsideOfS !== void 0 ? _opts$allowOutsideOfS : false,
44383
- errorFormatter: (_opts$errorFormatter = opts === null || opts === void 0 ? void 0 : opts.errorFormatter) !== null && _opts$errorFormatter !== void 0 ? _opts$errorFormatter : defaultFormatter,
44384
- isServer: (_opts$isServer = opts === null || opts === void 0 ? void 0 : opts.isServer) !== null && _opts$isServer !== void 0 ? _opts$isServer : isServerDefault,
44385
- $types: null
44386
- });
44387
- var _opts$isServer2;
44388
- if (!((_opts$isServer2 = opts === null || opts === void 0 ? void 0 : opts.isServer) !== null && _opts$isServer2 !== void 0 ? _opts$isServer2 : isServerDefault) && (opts === null || opts === void 0 ? void 0 : opts.allowOutsideOfServer) !== true) throw new Error(`You're trying to use @trpc/server in a non-server environment. This is not supported by default.`);
44389
44475
  return {
44390
- _config: config,
44391
- procedure: createBuilder({ meta: opts === null || opts === void 0 ? void 0 : opts.defaultMeta }),
44392
- middleware: createMiddlewareFactory(),
44393
- router: createRouterFactory(config),
44394
- mergeRouters,
44395
- createCallerFactory: createCallerFactory()
44476
+ headers: resHeaders,
44477
+ status: meta === null || meta === void 0 ? void 0 : meta.status
44396
44478
  };
44397
44479
  }
44398
- }();
44399
- }));
44400
- //#endregion
44401
- //#region node_modules/@trpc/server/dist/node-http-gyWQuCv2.mjs
44402
- function createBody(req, opts) {
44403
- if ("body" in req) {
44404
- if (req.body === void 0) return void 0;
44405
- if (typeof req.body === "string") return req.body;
44406
- if (req.body instanceof IncomingMessage) return req.body;
44407
- return JSON.stringify(req.body);
44408
- }
44409
- let size = 0;
44410
- let hasClosed = false;
44411
- return new ReadableStream({
44412
- start(controller) {
44413
- const onData = (chunk) => {
44414
- size += chunk.length;
44415
- if (!opts.maxBodySize || size <= opts.maxBodySize) {
44416
- controller.enqueue(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength));
44417
- return;
44418
- }
44419
- controller.error(new TRPCError({ code: "PAYLOAD_TOO_LARGE" }));
44420
- hasClosed = true;
44421
- req.off("data", onData);
44422
- req.off("end", onEnd);
44423
- };
44424
- const onEnd = () => {
44425
- if (hasClosed) return;
44426
- hasClosed = true;
44427
- req.off("data", onData);
44428
- req.off("end", onEnd);
44429
- controller.close();
44430
- };
44431
- req.on("data", onData);
44432
- req.on("end", onEnd);
44433
- },
44434
- cancel() {
44435
- req.destroy();
44436
- }
44437
- });
44438
- }
44439
- function createURL(req) {
44440
- try {
44441
- var _ref, _req$headers$host;
44442
- const protocol = req.headers[":scheme"] && req.headers[":scheme"] === "https" || req.socket && "encrypted" in req.socket && req.socket.encrypted ? "https:" : "http:";
44443
- const host = (_ref = (_req$headers$host = req.headers.host) !== null && _req$headers$host !== void 0 ? _req$headers$host : req.headers[":authority"]) !== null && _ref !== void 0 ? _ref : "localhost";
44444
- return new URL(req.url, `${protocol}//${host}`);
44445
- } catch (cause) {
44446
- throw new TRPCError({
44447
- code: "BAD_REQUEST",
44448
- message: "Invalid URL",
44449
- cause
44450
- });
44451
- }
44452
- }
44453
- function createHeaders(incoming) {
44454
- const headers = new Headers();
44455
- for (const key in incoming) {
44456
- const value = incoming[key];
44457
- if (typeof key === "string" && key.startsWith(":")) continue;
44458
- if (Array.isArray(value)) for (const item of value) headers.append(key, item);
44459
- else if (value != null) headers.append(key, value);
44460
- }
44461
- return headers;
44462
- }
44463
- /**
44464
- * Convert an [`IncomingMessage`](https://nodejs.org/api/http.html#class-httpincomingmessage) to a [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request)
44465
- */
44466
- function incomingMessageToRequest(req, res, opts) {
44467
- const ac = new AbortController();
44468
- const onAbort = () => {
44469
- res.off("close", onAbort);
44470
- req.off("aborted", onAbort);
44471
- ac.abort();
44472
- };
44473
- res.once("close", onAbort);
44474
- req.once("aborted", onAbort);
44475
- const url = createURL(req);
44476
- const init = {
44477
- headers: createHeaders(req.headers),
44478
- method: req.method,
44479
- signal: ac.signal
44480
- };
44481
- if (req.method !== "GET" && req.method !== "HEAD") {
44482
- init.body = createBody(req, opts);
44483
- init.duplex = "half";
44484
- }
44485
- return new Request(url, init);
44486
- }
44487
- async function writeResponseBodyChunk(res, chunk) {
44488
- if (res.write(chunk) === false) await new Promise((resolve, reject) => {
44489
- const onError = (err) => {
44490
- reject(err);
44491
- cleanup();
44492
- };
44493
- const onDrain = () => {
44494
- resolve();
44495
- cleanup();
44496
- };
44497
- const cleanup = () => {
44498
- res.off("error", onError);
44499
- res.off("drain", onDrain);
44500
- };
44501
- res.once("error", onError);
44502
- res.once("drain", onDrain);
44503
- });
44504
- }
44505
- /**
44506
- * @internal
44507
- */
44508
- async function writeResponseBody(opts) {
44509
- const { res } = opts;
44510
- try {
44511
- const writableStream = new WritableStream({ async write(chunk) {
44512
- var _res$flush;
44513
- await writeResponseBodyChunk(res, chunk);
44514
- (_res$flush = res.flush) === null || _res$flush === void 0 || _res$flush.call(res);
44515
- } });
44516
- await opts.body.pipeTo(writableStream, { signal: opts.signal });
44517
- } catch (err) {
44518
- if (isAbortError(err)) return;
44519
- throw err;
44520
- }
44521
- }
44522
- /**
44523
- * @internal
44524
- */
44525
- async function writeResponse(opts) {
44526
- const { response, rawResponse } = opts;
44527
- if (rawResponse.statusCode === 200) rawResponse.statusCode = response.status;
44528
- for (const [key, value] of response.headers) {
44529
- if (key.toLowerCase() === "set-cookie") continue;
44530
- rawResponse.setHeader(key, value);
44531
- }
44532
- const cookies = response.headers.getSetCookie();
44533
- if (cookies.length > 0) rawResponse.setHeader("set-cookie", cookies);
44534
- try {
44535
- if (response.body) await writeResponseBody({
44536
- res: rawResponse,
44537
- signal: opts.request.signal,
44538
- body: response.body
44539
- });
44540
- } catch (err) {
44541
- if (!rawResponse.headersSent) rawResponse.statusCode = 500;
44542
- throw err;
44543
- } finally {
44544
- rawResponse.end();
44545
- }
44546
- }
44547
- /**
44548
- * @internal
44549
- */
44550
- function internal_exceptionHandler(opts) {
44551
- return (cause) => {
44552
- var _opts$onError;
44553
- const { res, req } = opts;
44554
- const error = getTRPCErrorFromUnknown(cause);
44555
- const shape = getErrorShape({
44556
- config: opts.router._def._config,
44557
- error,
44558
- type: "unknown",
44559
- path: void 0,
44560
- input: void 0,
44561
- ctx: void 0
44562
- });
44563
- (_opts$onError = opts.onError) === null || _opts$onError === void 0 || _opts$onError.call(opts, {
44564
- req,
44565
- error,
44566
- type: "unknown",
44567
- path: void 0,
44568
- input: void 0,
44569
- ctx: void 0
44570
- });
44571
- const transformed = transformTRPCResponse(opts.router._def._config, { error: shape });
44572
- res.statusCode = shape.data.httpStatus;
44573
- res.end(JSON.stringify(transformed));
44574
- };
44575
- }
44576
- /**
44577
- * @remark the promise never rejects
44578
- */
44579
- async function nodeHTTPRequestHandler(opts) {
44580
- return new Promise((resolve) => {
44581
- var _opts$middleware;
44582
- const handleViaMiddleware = (_opts$middleware = opts.middleware) !== null && _opts$middleware !== void 0 ? _opts$middleware : (_req, _res, next) => next();
44583
- opts.res.once("finish", () => {
44584
- resolve();
44585
- });
44586
- return handleViaMiddleware(opts.req, opts.res, (err) => {
44587
- run$2(async () => {
44588
- var _opts$maxBodySize;
44589
- const request = incomingMessageToRequest(opts.req, opts.res, { maxBodySize: (_opts$maxBodySize = opts.maxBodySize) !== null && _opts$maxBodySize !== void 0 ? _opts$maxBodySize : null });
44590
- const createContext = async (innerOpts) => {
44591
- var _opts$createContext;
44592
- return await ((_opts$createContext = opts.createContext) === null || _opts$createContext === void 0 ? void 0 : _opts$createContext.call(opts, (0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, opts), innerOpts)));
44593
- };
44594
- await writeResponse({
44595
- request,
44596
- response: await resolveResponse((0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, opts), {}, {
44597
- req: request,
44598
- error: err ? getTRPCErrorFromUnknown(err) : null,
44599
- createContext,
44600
- onError(o) {
44601
- var _opts$onError2;
44602
- opts === null || opts === void 0 || (_opts$onError2 = opts.onError) === null || _opts$onError2 === void 0 || _opts$onError2.call(opts, (0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, o), {}, { req: opts.req }));
44603
- }
44604
- })),
44605
- rawResponse: opts.res
44606
- });
44607
- }).catch(internal_exceptionHandler(opts));
44608
- });
44609
- });
44480
+ }));
44610
44481
  }
44611
- var import_objectSpread2$1;
44612
- var init_node_http_gyWQuCv2 = __esmMin((() => {
44482
+ var import_objectSpread2$3, trimSlashes;
44483
+ var init_fetch = __esmMin((() => {
44613
44484
  init_getErrorShape_BPSzUA7W();
44614
- init_codes_DagpWZLc();
44615
- init_tracked_DWInO6EQ();
44616
44485
  init_resolveResponse_CdASWfAV();
44617
- import_objectSpread2$1 = __toESM(require_objectSpread2(), 1);
44618
- }));
44619
- //#endregion
44620
- //#region node_modules/@trpc/server/dist/adapters/standalone.mjs
44621
- function createHandler(opts) {
44622
- var _opts$basePath;
44623
- const sliceLength = ((_opts$basePath = opts.basePath) !== null && _opts$basePath !== void 0 ? _opts$basePath : "/").length;
44624
- return (req, res) => {
44625
- let path = "";
44626
- run$2(async () => {
44627
- path = createURL(req).pathname.slice(sliceLength);
44628
- await nodeHTTPRequestHandler((0, import_objectSpread2.default)((0, import_objectSpread2.default)({}, opts), {}, {
44629
- req,
44630
- res,
44631
- path
44632
- }));
44633
- }).catch(internal_exceptionHandler((0, import_objectSpread2.default)({
44634
- req,
44635
- res,
44636
- path
44637
- }, opts)));
44486
+ import_objectSpread2$3 = __toESM(require_objectSpread2(), 1);
44487
+ trimSlashes = (path) => {
44488
+ path = path.startsWith("/") ? path.slice(1) : path;
44489
+ path = path.endsWith("/") ? path.slice(0, -1) : path;
44490
+ return path;
44638
44491
  };
44639
- }
44640
- /**
44641
- * @internal
44642
- */
44643
- function createHTTPHandler(opts) {
44644
- return createHandler(opts);
44645
- }
44646
- var import_objectSpread2;
44647
- var init_standalone = __esmMin((() => {
44648
- init_getErrorShape_BPSzUA7W();
44649
- init_codes_DagpWZLc();
44650
- init_node_http_gyWQuCv2();
44651
- import_objectSpread2 = __toESM(require_objectSpread2(), 1);
44652
44492
  }));
44653
44493
  //#endregion
44654
44494
  //#region src/ui/client.generated.html
@@ -44848,7 +44688,7 @@ var init_Bind = __esmMin((() => {
44848
44688
  }));
44849
44689
  //#endregion
44850
44690
  //#region src/ui/Ports.ts
44851
- var UiError, UiUsageError, UiShell;
44691
+ var UiError, UiUsageError, UiShell, UiHost;
44852
44692
  var init_Ports = __esmMin((() => {
44853
44693
  init_esm();
44854
44694
  UiError = class extends Error {
@@ -44868,6 +44708,7 @@ var init_Ports = __esmMin((() => {
44868
44708
  UiShell = class UiShell extends Tag("UiShell")() {
44869
44709
  static layer = (bash) => succeed$2(UiShell, { bash });
44870
44710
  };
44711
+ UiHost = class extends Tag("UiHost")() {};
44871
44712
  }));
44872
44713
  //#endregion
44873
44714
  //#region src/ui/Quote.ts
@@ -45026,10 +44867,9 @@ var init_View = __esmMin((() => {
45026
44867
  }));
45027
44868
  //#endregion
45028
44869
  //#region src/ui/Write.ts
45029
- var contentHashOf, writeQueues, enqueue, verifyForWrite, finishWrite, annotateRefusal, writeNote, writeValue, liveActorAt, liveReadFile, liveWriteFile;
44870
+ var contentHashOf, writeQueues, enqueue, verifyForWrite, finishWrite, annotateRefusal, writeNote, writeValue, actorVia, liveReadFile, liveWriteFile;
45030
44871
  var init_Write = __esmMin((() => {
45031
44872
  init_steering();
45032
- init_Beat();
45033
44873
  init_SafePath();
45034
44874
  contentHashOf = (content) => createHash("sha256").update(content, "utf8").digest("hex");
45035
44875
  writeQueues = /* @__PURE__ */ new Map();
@@ -45126,8 +44966,8 @@ var init_Write = __esmMin((() => {
45126
44966
  return finishWrite(absPath, nextContent, deps);
45127
44967
  });
45128
44968
  };
45129
- liveActorAt = async (worktreePath) => {
45130
- const outcome = await liveRunInWorktree(worktreePath, "gtd next --json");
44969
+ actorVia = (run) => async (worktreePath) => {
44970
+ const outcome = await run(worktreePath, "gtd next --json");
45131
44971
  if (outcome.status !== 0) return void 0;
45132
44972
  try {
45133
44973
  const parsed = JSON.parse(outcome.stdout);
@@ -45188,6 +45028,319 @@ var init_ReadSteeringFile = __esmMin((() => {
45188
45028
  };
45189
45029
  }));
45190
45030
  //#endregion
45031
+ //#region node_modules/@trpc/server/dist/initTRPC-BRf4imah.mjs
45032
+ /**
45033
+ * @internal
45034
+ */
45035
+ function createMiddlewareFactory() {
45036
+ function createMiddlewareInner(middlewares) {
45037
+ return {
45038
+ _middlewares: middlewares,
45039
+ unstable_pipe(middlewareBuilderOrFn) {
45040
+ const pipedMiddleware = "_middlewares" in middlewareBuilderOrFn ? middlewareBuilderOrFn._middlewares : [middlewareBuilderOrFn];
45041
+ return createMiddlewareInner([...middlewares, ...pipedMiddleware]);
45042
+ }
45043
+ };
45044
+ }
45045
+ function createMiddleware(fn) {
45046
+ return createMiddlewareInner([fn]);
45047
+ }
45048
+ return createMiddleware;
45049
+ }
45050
+ /**
45051
+ * @internal
45052
+ * Please note, `trpc-openapi` uses this function.
45053
+ */
45054
+ function createInputMiddleware(parse) {
45055
+ const inputMiddleware = async function inputValidatorMiddleware(opts) {
45056
+ let parsedInput;
45057
+ const rawInput = await opts.getRawInput();
45058
+ try {
45059
+ parsedInput = await parse(rawInput);
45060
+ } catch (cause) {
45061
+ throw new TRPCError({
45062
+ code: "BAD_REQUEST",
45063
+ cause
45064
+ });
45065
+ }
45066
+ const combinedInput = isObject$2(opts.input) && isObject$2(parsedInput) ? (0, import_objectSpread2$2.default)((0, import_objectSpread2$2.default)({}, opts.input), parsedInput) : parsedInput;
45067
+ return opts.next({ input: combinedInput });
45068
+ };
45069
+ inputMiddleware._type = "input";
45070
+ return inputMiddleware;
45071
+ }
45072
+ /**
45073
+ * @internal
45074
+ */
45075
+ function createOutputMiddleware(parse) {
45076
+ const outputMiddleware = async function outputValidatorMiddleware({ next }) {
45077
+ const result = await next();
45078
+ if (!result.ok) return result;
45079
+ try {
45080
+ const data = await parse(result.data);
45081
+ return (0, import_objectSpread2$2.default)((0, import_objectSpread2$2.default)({}, result), {}, { data });
45082
+ } catch (cause) {
45083
+ throw new TRPCError({
45084
+ message: "Output validation failed",
45085
+ code: "INTERNAL_SERVER_ERROR",
45086
+ cause
45087
+ });
45088
+ }
45089
+ };
45090
+ outputMiddleware._type = "output";
45091
+ return outputMiddleware;
45092
+ }
45093
+ function getParseFn(procedureParser) {
45094
+ const parser = procedureParser;
45095
+ const isStandardSchema = "~standard" in parser;
45096
+ if (typeof parser === "function" && typeof parser.assert === "function") return parser.assert.bind(parser);
45097
+ if (typeof parser === "function" && !isStandardSchema) return parser;
45098
+ if (typeof parser.parseAsync === "function") return parser.parseAsync.bind(parser);
45099
+ if (typeof parser.parse === "function") return parser.parse.bind(parser);
45100
+ if (typeof parser.validateSync === "function") return parser.validateSync.bind(parser);
45101
+ if (typeof parser.create === "function") return parser.create.bind(parser);
45102
+ if (typeof parser.assert === "function") return (value) => {
45103
+ parser.assert(value);
45104
+ return value;
45105
+ };
45106
+ if (isStandardSchema) return async (value) => {
45107
+ const result = await parser["~standard"].validate(value);
45108
+ if (result.issues) throw new StandardSchemaV1Error(result.issues);
45109
+ return result.value;
45110
+ };
45111
+ throw new Error("Could not find a validator fn");
45112
+ }
45113
+ function createNewBuilder(def1, def2) {
45114
+ const { middlewares = [], inputs, meta } = def2, rest = (0, import_objectWithoutProperties.default)(def2, _excluded);
45115
+ return createBuilder((0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, mergeWithoutOverrides(def1, rest)), {}, {
45116
+ inputs: [...def1.inputs, ...inputs !== null && inputs !== void 0 ? inputs : []],
45117
+ middlewares: [...def1.middlewares, ...middlewares],
45118
+ meta: def1.meta && meta ? (0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, def1.meta), meta) : meta !== null && meta !== void 0 ? meta : def1.meta
45119
+ }));
45120
+ }
45121
+ function createBuilder(initDef = {}) {
45122
+ const _def = (0, import_objectSpread2$1.default)({
45123
+ procedure: true,
45124
+ inputs: [],
45125
+ middlewares: []
45126
+ }, initDef);
45127
+ return {
45128
+ _def,
45129
+ input(input) {
45130
+ const parser = getParseFn(input);
45131
+ return createNewBuilder(_def, {
45132
+ inputs: [input],
45133
+ middlewares: [createInputMiddleware(parser)]
45134
+ });
45135
+ },
45136
+ output(output) {
45137
+ const parser = getParseFn(output);
45138
+ return createNewBuilder(_def, {
45139
+ output,
45140
+ middlewares: [createOutputMiddleware(parser)]
45141
+ });
45142
+ },
45143
+ meta(meta) {
45144
+ return createNewBuilder(_def, { meta });
45145
+ },
45146
+ use(middlewareBuilderOrFn) {
45147
+ const middlewares = "_middlewares" in middlewareBuilderOrFn ? middlewareBuilderOrFn._middlewares : [middlewareBuilderOrFn];
45148
+ return createNewBuilder(_def, { middlewares });
45149
+ },
45150
+ unstable_concat(builder$1) {
45151
+ return createNewBuilder(_def, builder$1._def);
45152
+ },
45153
+ concat(builder$1) {
45154
+ return createNewBuilder(_def, builder$1._def);
45155
+ },
45156
+ query(resolver) {
45157
+ return createResolver((0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, _def), {}, { type: "query" }), resolver);
45158
+ },
45159
+ mutation(resolver) {
45160
+ return createResolver((0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, _def), {}, { type: "mutation" }), resolver);
45161
+ },
45162
+ subscription(resolver) {
45163
+ return createResolver((0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, _def), {}, { type: "subscription" }), resolver);
45164
+ },
45165
+ experimental_caller(caller) {
45166
+ return createNewBuilder(_def, { caller });
45167
+ }
45168
+ };
45169
+ }
45170
+ function createResolver(_defIn, resolver) {
45171
+ const finalBuilder = createNewBuilder(_defIn, {
45172
+ resolver,
45173
+ middlewares: [async function resolveMiddleware(opts) {
45174
+ const data = await resolver(opts);
45175
+ return {
45176
+ marker: middlewareMarker,
45177
+ ok: true,
45178
+ data,
45179
+ ctx: opts.ctx
45180
+ };
45181
+ }]
45182
+ });
45183
+ const _def = (0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, finalBuilder._def), {}, {
45184
+ type: _defIn.type,
45185
+ experimental_caller: Boolean(finalBuilder._def.caller),
45186
+ meta: finalBuilder._def.meta,
45187
+ $types: null
45188
+ });
45189
+ const invoke = createProcedureCaller(finalBuilder._def);
45190
+ const callerOverride = finalBuilder._def.caller;
45191
+ if (!callerOverride) return invoke;
45192
+ const callerWrapper = async (...args) => {
45193
+ return await callerOverride({
45194
+ args,
45195
+ invoke,
45196
+ _def
45197
+ });
45198
+ };
45199
+ callerWrapper._def = _def;
45200
+ return callerWrapper;
45201
+ }
45202
+ async function callRecursive(index, _def, opts) {
45203
+ try {
45204
+ const middleware = _def.middlewares[index];
45205
+ return await middleware((0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, opts), {}, {
45206
+ meta: _def.meta,
45207
+ input: opts.input,
45208
+ next(_nextOpts) {
45209
+ var _nextOpts$getRawInput;
45210
+ const nextOpts = _nextOpts;
45211
+ return callRecursive(index + 1, _def, (0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, opts), {}, {
45212
+ ctx: (nextOpts === null || nextOpts === void 0 ? void 0 : nextOpts.ctx) ? (0, import_objectSpread2$1.default)((0, import_objectSpread2$1.default)({}, opts.ctx), nextOpts.ctx) : opts.ctx,
45213
+ input: nextOpts && "input" in nextOpts ? nextOpts.input : opts.input,
45214
+ getRawInput: (_nextOpts$getRawInput = nextOpts === null || nextOpts === void 0 ? void 0 : nextOpts.getRawInput) !== null && _nextOpts$getRawInput !== void 0 ? _nextOpts$getRawInput : opts.getRawInput
45215
+ }));
45216
+ }
45217
+ }));
45218
+ } catch (cause) {
45219
+ return {
45220
+ ok: false,
45221
+ error: getTRPCErrorFromUnknown(cause),
45222
+ marker: middlewareMarker
45223
+ };
45224
+ }
45225
+ }
45226
+ function createProcedureCaller(_def) {
45227
+ async function procedure(opts) {
45228
+ if (!opts || !("getRawInput" in opts)) throw new Error(codeblock);
45229
+ const result = await callRecursive(0, _def, opts);
45230
+ if (!result) throw new TRPCError({
45231
+ code: "INTERNAL_SERVER_ERROR",
45232
+ message: "No result from middlewares - did you forget to `return next()`?"
45233
+ });
45234
+ if (!result.ok) throw result.error;
45235
+ return result.data;
45236
+ }
45237
+ procedure._def = _def;
45238
+ procedure.procedure = true;
45239
+ procedure.meta = _def.meta;
45240
+ return procedure;
45241
+ }
45242
+ var import_objectSpread2$2, middlewareMarker, import_defineProperty, StandardSchemaV1Error, require_objectWithoutPropertiesLoose, import_objectWithoutProperties, import_objectSpread2$1, _excluded, codeblock, _globalThis$process, _globalThis$process2, _globalThis$process3, isServerDefault, import_objectSpread2, initTRPC;
45243
+ var init_initTRPC_BRf4imah = __esmMin((() => {
45244
+ init_getErrorShape_BPSzUA7W();
45245
+ init_codes_DagpWZLc();
45246
+ init_tracked_DWInO6EQ();
45247
+ import_objectSpread2$2 = __toESM(require_objectSpread2(), 1);
45248
+ middlewareMarker = "middlewareMarker";
45249
+ import_defineProperty = __toESM(require_defineProperty(), 1);
45250
+ StandardSchemaV1Error = class extends Error {
45251
+ /**
45252
+ * Creates a schema error with useful information.
45253
+ *
45254
+ * @param issues The schema issues.
45255
+ */
45256
+ constructor(issues) {
45257
+ var _issues$;
45258
+ super((_issues$ = issues[0]) === null || _issues$ === void 0 ? void 0 : _issues$.message);
45259
+ (0, import_defineProperty.default)(this, "issues", void 0);
45260
+ this.name = "SchemaError";
45261
+ this.issues = issues;
45262
+ }
45263
+ };
45264
+ require_objectWithoutPropertiesLoose = __commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/objectWithoutPropertiesLoose.js"(exports, module) {
45265
+ function _objectWithoutPropertiesLoose(r, e) {
45266
+ if (null == r) return {};
45267
+ var t = {};
45268
+ for (var n in r) if ({}.hasOwnProperty.call(r, n)) {
45269
+ if (e.includes(n)) continue;
45270
+ t[n] = r[n];
45271
+ }
45272
+ return t;
45273
+ }
45274
+ module.exports = _objectWithoutPropertiesLoose, module.exports.__esModule = true, module.exports["default"] = module.exports;
45275
+ } });
45276
+ import_objectWithoutProperties = __toESM(__commonJS({ "../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/objectWithoutProperties.js"(exports, module) {
45277
+ var objectWithoutPropertiesLoose = require_objectWithoutPropertiesLoose();
45278
+ function _objectWithoutProperties$1(e, t) {
45279
+ if (null == e) return {};
45280
+ var o, r, i = objectWithoutPropertiesLoose(e, t);
45281
+ if (Object.getOwnPropertySymbols) {
45282
+ var s = Object.getOwnPropertySymbols(e);
45283
+ for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]);
45284
+ }
45285
+ return i;
45286
+ }
45287
+ module.exports = _objectWithoutProperties$1, module.exports.__esModule = true, module.exports["default"] = module.exports;
45288
+ } })(), 1);
45289
+ import_objectSpread2$1 = __toESM(require_objectSpread2(), 1);
45290
+ _excluded = [
45291
+ "middlewares",
45292
+ "inputs",
45293
+ "meta"
45294
+ ];
45295
+ codeblock = `
45296
+ This is a client-only function.
45297
+ If you want to call this function on the server, see https://trpc.io/docs/v11/server/server-side-calls
45298
+ `.trim();
45299
+ isServerDefault = typeof window === "undefined" || "Deno" in window || ((_globalThis$process = globalThis.process) === null || _globalThis$process === void 0 || (_globalThis$process = _globalThis$process.env) === null || _globalThis$process === void 0 ? void 0 : _globalThis$process["NODE_ENV"]) === "test" || !!((_globalThis$process2 = globalThis.process) === null || _globalThis$process2 === void 0 || (_globalThis$process2 = _globalThis$process2.env) === null || _globalThis$process2 === void 0 ? void 0 : _globalThis$process2["JEST_WORKER_ID"]) || !!((_globalThis$process3 = globalThis.process) === null || _globalThis$process3 === void 0 || (_globalThis$process3 = _globalThis$process3.env) === null || _globalThis$process3 === void 0 ? void 0 : _globalThis$process3["VITEST_WORKER_ID"]);
45300
+ import_objectSpread2 = __toESM(require_objectSpread2(), 1);
45301
+ initTRPC = new class TRPCBuilder {
45302
+ /**
45303
+ * Add a context shape as a generic to the root object
45304
+ * @see https://trpc.io/docs/v11/server/context
45305
+ */
45306
+ context() {
45307
+ return new TRPCBuilder();
45308
+ }
45309
+ /**
45310
+ * Add a meta shape as a generic to the root object
45311
+ * @see https://trpc.io/docs/v11/quickstart
45312
+ */
45313
+ meta() {
45314
+ return new TRPCBuilder();
45315
+ }
45316
+ /**
45317
+ * Create the root object
45318
+ * @see https://trpc.io/docs/v11/server/routers#initialize-trpc
45319
+ */
45320
+ create(opts) {
45321
+ var _opts$transformer, _opts$isDev, _globalThis$process$1, _opts$allowOutsideOfS, _opts$errorFormatter, _opts$isServer;
45322
+ const config = (0, import_objectSpread2.default)((0, import_objectSpread2.default)({}, opts), {}, {
45323
+ transformer: getDataTransformer((_opts$transformer = opts === null || opts === void 0 ? void 0 : opts.transformer) !== null && _opts$transformer !== void 0 ? _opts$transformer : defaultTransformer),
45324
+ isDev: (_opts$isDev = opts === null || opts === void 0 ? void 0 : opts.isDev) !== null && _opts$isDev !== void 0 ? _opts$isDev : ((_globalThis$process$1 = globalThis.process) === null || _globalThis$process$1 === void 0 ? void 0 : _globalThis$process$1.env["NODE_ENV"]) !== "production",
45325
+ allowOutsideOfServer: (_opts$allowOutsideOfS = opts === null || opts === void 0 ? void 0 : opts.allowOutsideOfServer) !== null && _opts$allowOutsideOfS !== void 0 ? _opts$allowOutsideOfS : false,
45326
+ errorFormatter: (_opts$errorFormatter = opts === null || opts === void 0 ? void 0 : opts.errorFormatter) !== null && _opts$errorFormatter !== void 0 ? _opts$errorFormatter : defaultFormatter,
45327
+ isServer: (_opts$isServer = opts === null || opts === void 0 ? void 0 : opts.isServer) !== null && _opts$isServer !== void 0 ? _opts$isServer : isServerDefault,
45328
+ $types: null
45329
+ });
45330
+ var _opts$isServer2;
45331
+ if (!((_opts$isServer2 = opts === null || opts === void 0 ? void 0 : opts.isServer) !== null && _opts$isServer2 !== void 0 ? _opts$isServer2 : isServerDefault) && (opts === null || opts === void 0 ? void 0 : opts.allowOutsideOfServer) !== true) throw new Error(`You're trying to use @trpc/server in a non-server environment. This is not supported by default.`);
45332
+ return {
45333
+ _config: config,
45334
+ procedure: createBuilder({ meta: opts === null || opts === void 0 ? void 0 : opts.defaultMeta }),
45335
+ middleware: createMiddlewareFactory(),
45336
+ router: createRouterFactory(config),
45337
+ mergeRouters,
45338
+ createCallerFactory: createCallerFactory()
45339
+ };
45340
+ }
45341
+ }();
45342
+ }));
45343
+ //#endregion
45191
45344
  //#region node_modules/@trpc/server/dist/index.mjs
45192
45345
  var init_dist = __esmMin((() => {
45193
45346
  init_tracked_DWInO6EQ();
@@ -45569,19 +45722,25 @@ var init_Tailscale = __esmMin((() => {
45569
45722
  }));
45570
45723
  //#endregion
45571
45724
  //#region src/ui/Tls.ts
45572
- var generateSelfSignedCert, obtainTailscaleCert, loadCertPair;
45725
+ var issueInScratch, generateSelfSignedCert, obtainTailscaleCert, loadCertPair;
45573
45726
  var init_Tls = __esmMin((() => {
45574
45727
  init_esm$1();
45575
45728
  init_esm();
45576
45729
  init_Ports();
45577
45730
  init_Quote();
45578
- generateSelfSignedCert = (request) => gen(function* () {
45731
+ issueInScratch = (tool, command) => gen(function* () {
45579
45732
  const runner = yield* UiShell;
45580
- const dir = mkdtempSync(join(tmpdir(), "gtd-tls-"));
45581
- const keyPath = join(dir, "key.pem");
45582
- const certPath = join(dir, "cert.pem");
45733
+ return yield* (yield* UiHost).scratch((dir, read) => runner.bash(command(join(dir, "cert.pem"), join(dir, "key.pem"))).pipe(mapError$1((e) => new UiError(`gtd ui: could not run ${tool} to issue a certificate: ${e.message}`)), flatMap$4((outcome) => outcome.status !== 0 ? fail$7(new UiError(`gtd ui: ${tool} exited without issuing a certificate`, [`exit status: ${outcome.status ?? "signal"}`, ...outcome.output.trim().split("\n").filter(Boolean)])) : try_({
45734
+ try: () => ({
45735
+ cert: read("cert.pem"),
45736
+ key: read("key.pem")
45737
+ }),
45738
+ catch: (e) => new UiError(`gtd ui: ${tool} reported success but its output could not be read: ${e instanceof Error ? e.message : String(e)}`)
45739
+ }))));
45740
+ });
45741
+ generateSelfSignedCert = (request) => {
45583
45742
  const subjectAltName = request.ip !== void 0 ? `IP:${request.ip},DNS:${request.host}` : `DNS:${request.host}`;
45584
- const command = [
45743
+ return issueInScratch("openssl", (certPath, keyPath) => [
45585
45744
  "openssl req -x509 -newkey rsa:2048 -nodes -days 825",
45586
45745
  `-keyout ${shellQuote(keyPath)}`,
45587
45746
  `-out ${shellQuote(certPath)}`,
@@ -45589,40 +45748,14 @@ var init_Tls = __esmMin((() => {
45589
45748
  `-addext ${shellQuote(`subjectAltName=${subjectAltName}`)}`,
45590
45749
  `-addext "extendedKeyUsage=serverAuth"`,
45591
45750
  `-addext "basicConstraints=critical,CA:FALSE"`
45592
- ].join(" ");
45593
- return yield* runner.bash(command).pipe(mapError$1((e) => new UiError(`gtd ui: could not run openssl to issue a certificate: ${e.message}`)), flatMap$4((outcome) => outcome.status !== 0 ? fail$7(new UiError("gtd ui: openssl exited without issuing a certificate", [`exit status: ${outcome.status ?? "signal"}`, ...outcome.output.trim().split("\n").filter(Boolean)])) : try_({
45594
- try: () => ({
45595
- cert: readFileSync(certPath, "utf8"),
45596
- key: readFileSync(keyPath, "utf8")
45597
- }),
45598
- catch: (e) => new UiError(`gtd ui: openssl reported success but its output could not be read: ${e instanceof Error ? e.message : String(e)}`)
45599
- })), ensuring$2(sync$1(() => rmSync(dir, {
45600
- recursive: true,
45601
- force: true
45602
- }))));
45603
- });
45604
- obtainTailscaleCert = (domain) => gen(function* () {
45605
- const runner = yield* UiShell;
45606
- const dir = mkdtempSync(join(tmpdir(), "gtd-tls-"));
45607
- const keyPath = join(dir, "key.pem");
45608
- const certPath = join(dir, "cert.pem");
45609
- const command = [
45610
- "tailscale cert",
45611
- `--cert-file ${shellQuote(certPath)}`,
45612
- `--key-file ${shellQuote(keyPath)}`,
45613
- shellQuote(domain)
45614
- ].join(" ");
45615
- return yield* runner.bash(command).pipe(mapError$1((e) => new UiError(`gtd ui: could not run tailscale cert to issue a certificate: ${e.message}`)), flatMap$4((outcome) => outcome.status !== 0 ? fail$7(new UiError("gtd ui: tailscale cert exited without issuing a certificate", [`exit status: ${outcome.status ?? "signal"}`, ...outcome.output.trim().split("\n").filter(Boolean)])) : try_({
45616
- try: () => ({
45617
- cert: readFileSync(certPath, "utf8"),
45618
- key: readFileSync(keyPath, "utf8")
45619
- }),
45620
- catch: (e) => new UiError(`gtd ui: tailscale cert reported success but its output could not be read: ${e instanceof Error ? e.message : String(e)}`)
45621
- })), ensuring$2(sync$1(() => rmSync(dir, {
45622
- recursive: true,
45623
- force: true
45624
- }))));
45625
- });
45751
+ ].join(" "));
45752
+ };
45753
+ obtainTailscaleCert = (domain) => issueInScratch("tailscale cert", (certPath, keyPath) => [
45754
+ "tailscale cert",
45755
+ `--cert-file ${shellQuote(certPath)}`,
45756
+ `--key-file ${shellQuote(keyPath)}`,
45757
+ shellQuote(domain)
45758
+ ].join(" "));
45626
45759
  loadCertPair = (certPath, keyPath) => gen(function* () {
45627
45760
  const fs = yield* FileSystem;
45628
45761
  const read = (path) => fs.readFileString(path).pipe(mapError$1((e) => new UiError(`gtd ui: could not read ${path}: ${e.message}`)));
@@ -45634,9 +45767,9 @@ var init_Tls = __esmMin((() => {
45634
45767
  }));
45635
45768
  //#endregion
45636
45769
  //#region src/ui/Server.ts
45637
- var TRPC_PATH_PREFIX, resolveBindHost, resolveCertPair, UiListener, SERVE_PORT_CANDIDATES, normalizePort, findPackageRoot, readDevTemplate, rebuildDevClientScript, rebuildDevClientCss, resolveClientHtml, liveBeatDeps, buildFormatCommand, isRenderable, refusalFor, resolveHostsAndCert, isPidAlive, probeLiveServeMapping, clearOrphanForPublish, attemptServe, teardownServe, resolveListener, runUiCommand;
45770
+ var TRPC_PATH_PREFIX, resolveBindHost, resolveCertPair, UiListener, viaNode, SERVE_PORT_CANDIDATES, normalizePort, findPackageRoot, readDevTemplate, rebuildDevClientScript, rebuildDevClientCss, resolveClientHtml, buildFormatCommand, isRenderable, refusalFor, resolveHostsAndCert, probeLiveServeMapping, clearOrphanForPublish, attemptServe, teardownServe, resolveListener, runUiCommand;
45638
45771
  var init_Server = __esmMin((() => {
45639
- init_standalone();
45772
+ init_fetch();
45640
45773
  init_esm$1();
45641
45774
  init_esm();
45642
45775
  init_client_generated();
@@ -45653,7 +45786,7 @@ var init_Server = __esmMin((() => {
45653
45786
  init_Tls();
45654
45787
  init_Write();
45655
45788
  TRPC_PATH_PREFIX = "/trpc";
45656
- resolveBindHost = (host, config, pickHost = () => pickBindHost(OS.networkInterfaces())) => {
45789
+ resolveBindHost = (host, config, pickHost) => {
45657
45790
  const resolved = host ?? config?.host ?? pickHost();
45658
45791
  return resolved === void 0 ? fail$7(new UiError("gtd ui: no Tailscale interface found to bind to, and no --host given", ["join a tailnet, so a CGNAT (100.64.0.0/10) address is available", "or pass --host <address> to bind explicitly"])) : succeed$3(resolved);
45659
45792
  };
@@ -45677,10 +45810,11 @@ var init_Server = __esmMin((() => {
45677
45810
  };
45678
45811
  UiListener = class UiListener extends Tag("UiListener")() {
45679
45812
  static Live = succeed$2(UiListener, { listen: ({ tls, host, port, handler }) => async((resume) => {
45813
+ const serve = viaNode(handler);
45680
45814
  const server = tls !== void 0 ? https.createServer({
45681
45815
  cert: tls.cert,
45682
45816
  key: tls.key
45683
- }, handler) : http.createServer(handler);
45817
+ }, serve) : http.createServer(serve);
45684
45818
  server.once("error", (err) => {
45685
45819
  resume(fail$7(err.code === "EADDRINUSE" ? new UiError(`gtd ui: port ${port} is already in use`) : new UiError(`gtd ui: could not start the server: ${err.message}`)));
45686
45820
  });
@@ -45694,6 +45828,33 @@ var init_Server = __esmMin((() => {
45694
45828
  });
45695
45829
  }) });
45696
45830
  };
45831
+ viaNode = (handler) => (req, res) => {
45832
+ const headers = new Headers();
45833
+ for (const [name, value] of Object.entries(req.headers)) for (const one of [value ?? []].flat()) headers.append(name, one);
45834
+ const hasBody = req.method !== "GET" && req.method !== "HEAD";
45835
+ let request;
45836
+ try {
45837
+ request = new Request(new URL(req.url ?? "/", "http://localhost"), {
45838
+ method: req.method ?? "GET",
45839
+ headers,
45840
+ ...hasBody ? {
45841
+ body: Readable.toWeb(req),
45842
+ duplex: "half"
45843
+ } : {}
45844
+ });
45845
+ } catch {
45846
+ res.writeHead(400);
45847
+ res.end();
45848
+ return;
45849
+ }
45850
+ handler(request, (callback) => res.once("finish", callback)).then(async (response) => {
45851
+ res.writeHead(response.status, Object.fromEntries(response.headers));
45852
+ res.end(Buffer.from(await response.arrayBuffer()));
45853
+ }, () => {
45854
+ res.writeHead(500);
45855
+ res.end();
45856
+ });
45857
+ };
45697
45858
  SERVE_PORT_CANDIDATES = [
45698
45859
  8443,
45699
45860
  1e4,
@@ -45732,12 +45893,7 @@ var init_Server = __esmMin((() => {
45732
45893
  rebuildDevClientScript(runner, fs, root),
45733
45894
  rebuildDevClientCss(runner, fs, root)
45734
45895
  ])), map$4(([template, script, css]) => inlineStyles(inlineScript(template, script), css))) : succeed$3(client_generated_default);
45735
- liveBeatDeps = {
45736
- run: liveRunInWorktree,
45737
- readLocalGtdVersion: readLocalGtdVersionAt,
45738
- headSha: liveHeadSha
45739
- };
45740
- buildFormatCommand = (format, worktreeRoot, run = liveRunInWorktree) => {
45896
+ buildFormatCommand = (format, worktreeRoot, run) => {
45741
45897
  if (format === void 0) return void 0;
45742
45898
  return async (absPath) => {
45743
45899
  const outcome = await run(worktreeRoot, withFileVar(format, absPath));
@@ -45755,7 +45911,8 @@ var init_Server = __esmMin((() => {
45755
45911
  return new UiUsageError(`gtd ui: refuses to start — "${step.label}" rests with you, but names no steering file to show on the phone`, ["gtd next --json reported no steering file for this rest"]);
45756
45912
  };
45757
45913
  resolveHostsAndCert = (options, config) => gen(function* () {
45758
- const bindHost = yield* resolveBindHost(options.host, config);
45914
+ const host = yield* UiHost;
45915
+ const bindHost = yield* resolveBindHost(options.host, config, () => pickBindHost(host.networkInterfaces()));
45759
45916
  const tailscaleStatus = (options.host ?? config?.host) !== void 0 ? void 0 : yield* probeTailscaleStatus();
45760
45917
  const displayHost = tailscaleStatus?.hostname ?? bindHost;
45761
45918
  return {
@@ -45764,14 +45921,6 @@ var init_Server = __esmMin((() => {
45764
45921
  certPair: yield* resolveCertPair(options, config, bindHost, displayHost, tailscaleStatus)
45765
45922
  };
45766
45923
  });
45767
- isPidAlive = (pid) => {
45768
- try {
45769
- process.kill(pid, 0);
45770
- return true;
45771
- } catch {
45772
- return false;
45773
- }
45774
- };
45775
45924
  probeLiveServeMapping = (servePort) => gen(function* () {
45776
45925
  const outcome = yield* (yield* UiShell).bash("tailscale serve status --json").pipe(catchAll(() => succeed$3(void 0)));
45777
45926
  if (outcome === void 0 || outcome.status !== 0) return { ok: false };
@@ -45781,15 +45930,16 @@ var init_Server = __esmMin((() => {
45781
45930
  };
45782
45931
  });
45783
45932
  clearOrphanForPublish = (servePort) => gen(function* () {
45784
- const record = readServeRecord(servePort);
45933
+ const host = yield* UiHost;
45934
+ const record = host.serveRecords.read(servePort);
45785
45935
  if (record === void 0) {
45786
45936
  const probe = yield* probeLiveServeMapping(servePort);
45787
45937
  if (!probe.ok) return "unknowable";
45788
45938
  return probe.mapping === void 0 ? "clear" : "occupied";
45789
45939
  }
45790
- if (isPidAlive(record.pid) && record.pid !== process.pid) return "occupied";
45940
+ if (host.isPidAlive(record.pid) && record.pid !== process.pid) return "occupied";
45791
45941
  yield* unpublishServe(servePort).pipe(catchAll(() => succeed$3(void 0)));
45792
- deleteServeRecord(servePort);
45942
+ host.serveRecords.delete(servePort);
45793
45943
  return "clear";
45794
45944
  });
45795
45945
  attemptServe = (servePort, worktree, uiListener, handler) => gen(function* () {
@@ -45843,7 +45993,7 @@ var init_Server = __esmMin((() => {
45843
45993
  reason: `tailscale serve failed: ${publishResult.reason}`
45844
45994
  };
45845
45995
  }
45846
- writeServeRecord(servePort, {
45996
+ (yield* UiHost).serveRecords.write(servePort, {
45847
45997
  pid: process.pid,
45848
45998
  servePort,
45849
45999
  targetPort: bound.port,
@@ -45858,12 +46008,13 @@ var init_Server = __esmMin((() => {
45858
46008
  };
45859
46009
  });
45860
46010
  teardownServe = (servePort) => gen(function* () {
45861
- const record = readServeRecord(servePort);
46011
+ const host = yield* UiHost;
46012
+ const record = host.serveRecords.read(servePort);
45862
46013
  if (record === void 0) return;
45863
46014
  const probe = yield* probeLiveServeMapping(servePort);
45864
46015
  if (!probe.ok) return;
45865
46016
  if (probe.mapping !== void 0 && probe.mapping.targetUrl === record.target) yield* unpublishServe(servePort).pipe(catchAll(() => succeed$3(void 0)));
45866
- deleteServeRecord(servePort);
46017
+ host.serveRecords.delete(servePort);
45867
46018
  });
45868
46019
  resolveListener = (args) => gen(function* () {
45869
46020
  const { options, config, explicitPort, explicitHost, worktree, uiListener, handler, out } = args;
@@ -45914,7 +46065,13 @@ var init_Server = __esmMin((() => {
45914
46065
  };
45915
46066
  });
45916
46067
  runUiCommand = (options, config, out, root) => gen(function* () {
45917
- const step = yield* promise(() => readStep({ path: root }, liveBeatDeps));
46068
+ const host = yield* UiHost;
46069
+ const beatDeps = {
46070
+ run: host.run,
46071
+ readLocalGtdVersion: host.readLocalGtdVersion,
46072
+ headSha: host.headSha
46073
+ };
46074
+ const step = yield* promise(() => readStep({ path: root }, beatDeps));
45918
46075
  if (step.status === "broken" || !isRenderable(step)) return yield* fail$7(refusalFor(step));
45919
46076
  const servedState = step.state;
45920
46077
  const servedLabel = step.label;
@@ -45925,25 +46082,25 @@ var init_Server = __esmMin((() => {
45925
46082
  const explicitPort = normalizePort(options.port ?? config?.port);
45926
46083
  const explicitHost = options.host ?? config?.host;
45927
46084
  const clientHtml = yield* resolveClientHtml(options.dev, runner, fs);
45928
- const formatCommand = buildFormatCommand(config?.format, root);
46085
+ const formatCommand = buildFormatCommand(config?.format, root, host.run);
45929
46086
  const writeDeps = {
45930
- headSha: liveHeadSha,
45931
- actorAt: liveActorAt,
45932
- readFile: liveReadFile,
45933
- writeFile: liveWriteFile,
46087
+ headSha: host.headSha,
46088
+ actorAt: actorVia(host.run),
46089
+ readFile: host.readFile,
46090
+ writeFile: host.writeFile,
45934
46091
  ...formatCommand !== void 0 ? { formatCommand } : {}
45935
46092
  };
45936
- const diffDeps = { run: liveRunInWorktree };
46093
+ const diffDeps = { run: host.run };
45937
46094
  const readDeps = {
45938
- headSha: liveHeadSha,
45939
- readFile: liveReadFile
46095
+ headSha: host.headSha,
46096
+ readFile: host.readFile
45940
46097
  };
45941
46098
  const handoffDeferred = yield* make$33();
45942
46099
  const endServer = () => {
45943
46100
  runFork(runtime$4)(succeed$7(handoffDeferred, void 0));
45944
46101
  };
45945
46102
  const readServedStep = async () => {
45946
- const read = await readStep({ path: root }, liveBeatDeps);
46103
+ const read = await readStep({ path: root }, beatDeps);
45947
46104
  if (!(read.status === "broken" || read.state !== servedState || !isRenderable(read))) return read;
45948
46105
  endServer();
45949
46106
  return {
@@ -45952,53 +46109,50 @@ var init_Server = __esmMin((() => {
45952
46109
  };
45953
46110
  };
45954
46111
  const isServedFile = (filePath) => filePath === step.file;
45955
- const trpcHandler = createHTTPHandler({
45956
- router: appRouter,
45957
- basePath: `${TRPC_PATH_PREFIX}/`,
45958
- createContext: ({ res }) => ({
45959
- readStep: readServedStep,
45960
- writeNote: (request) => isServedFile(request.filePath) ? writeNote({
45961
- ...request,
45962
- worktreePath: root
45963
- }, writeDeps) : Promise.resolve({
45964
- ok: false,
45965
- reason: "file-vanished"
45966
- }),
45967
- writeValue: (request) => isServedFile(request.filePath) ? writeValue({
45968
- ...request,
45969
- worktreePath: root
45970
- }, writeDeps) : Promise.resolve({
45971
- ok: false,
45972
- reason: "file-vanished"
45973
- }),
45974
- resolveDiff: (path, line, endLine) => resolveDiff(root, path, line, endLine, diffDeps),
45975
- readSteeringFile: (request) => isServedFile(request.filePath) ? readSteeringFile({
45976
- ...request,
45977
- worktreePath: root
45978
- }, readDeps) : Promise.resolve({
45979
- ok: false,
45980
- reason: "file-vanished"
45981
- }),
45982
- handOff: () => {
45983
- let settled = false;
45984
- const settle = () => {
45985
- if (settled) return;
45986
- settled = true;
45987
- clearTimeout(fallback);
45988
- endServer();
45989
- };
45990
- res.once("finish", settle);
45991
- const fallback = setTimeout(settle, 2e3);
45992
- }
45993
- })
45994
- });
45995
- const handler = (req, res) => {
45996
- if (req.url === TRPC_PATH_PREFIX || req.url?.startsWith(`${TRPC_PATH_PREFIX}/`)) {
45997
- trpcHandler(req, res);
45998
- return;
45999
- }
46000
- res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
46001
- res.end(clientHtml);
46112
+ const handler = (request, afterResponse) => {
46113
+ const path = new URL(request.url).pathname;
46114
+ if (path !== TRPC_PATH_PREFIX && !path.startsWith(`${TRPC_PATH_PREFIX}/`)) return Promise.resolve(new Response(clientHtml, { headers: { "content-type": "text/html; charset=utf-8" } }));
46115
+ return fetchRequestHandler({
46116
+ endpoint: TRPC_PATH_PREFIX,
46117
+ req: request,
46118
+ router: appRouter,
46119
+ createContext: () => ({
46120
+ readStep: readServedStep,
46121
+ writeNote: (request) => isServedFile(request.filePath) ? writeNote({
46122
+ ...request,
46123
+ worktreePath: root
46124
+ }, writeDeps) : Promise.resolve({
46125
+ ok: false,
46126
+ reason: "file-vanished"
46127
+ }),
46128
+ writeValue: (request) => isServedFile(request.filePath) ? writeValue({
46129
+ ...request,
46130
+ worktreePath: root
46131
+ }, writeDeps) : Promise.resolve({
46132
+ ok: false,
46133
+ reason: "file-vanished"
46134
+ }),
46135
+ resolveDiff: (path, line, endLine) => resolveDiff(root, path, line, endLine, diffDeps),
46136
+ readSteeringFile: (request) => isServedFile(request.filePath) ? readSteeringFile({
46137
+ ...request,
46138
+ worktreePath: root
46139
+ }, readDeps) : Promise.resolve({
46140
+ ok: false,
46141
+ reason: "file-vanished"
46142
+ }),
46143
+ handOff: () => {
46144
+ let settled = false;
46145
+ const settle = () => {
46146
+ if (settled) return;
46147
+ settled = true;
46148
+ clearTimeout(fallback);
46149
+ endServer();
46150
+ };
46151
+ afterResponse(settle);
46152
+ const fallback = setTimeout(settle, 2e3);
46153
+ }
46154
+ })
46155
+ });
46002
46156
  };
46003
46157
  const { bound, url, teardown } = yield* resolveListener({
46004
46158
  options,
@@ -46016,9 +46170,45 @@ var init_Server = __esmMin((() => {
46016
46170
  });
46017
46171
  }));
46018
46172
  //#endregion
46173
+ //#region src/ui/Host.ts
46174
+ var liveUiHost;
46175
+ var init_Host$1 = __esmMin((() => {
46176
+ init_esm();
46177
+ init_Beat();
46178
+ init_Ports();
46179
+ init_Serve();
46180
+ init_Write();
46181
+ liveUiHost = succeed$2(UiHost, {
46182
+ run: liveRunInWorktree,
46183
+ headSha: liveHeadSha,
46184
+ readLocalGtdVersion: readLocalGtdVersionAt,
46185
+ readFile: liveReadFile,
46186
+ writeFile: liveWriteFile,
46187
+ networkInterfaces: () => networkInterfaces(),
46188
+ serveRecords: {
46189
+ read: (servePort) => readServeRecord(servePort),
46190
+ write: (servePort, record) => writeServeRecord(servePort, record),
46191
+ delete: (servePort) => deleteServeRecord(servePort)
46192
+ },
46193
+ isPidAlive: (pid) => {
46194
+ try {
46195
+ process.kill(pid, 0);
46196
+ return true;
46197
+ } catch {
46198
+ return false;
46199
+ }
46200
+ },
46201
+ scratch: (body) => acquireUseRelease$2(sync$1(() => mkdtempSync(join(tmpdir(), "gtd-tls-"))), (dir) => body(dir, (name) => readFileSync(join(dir, name), "utf8")), (dir) => sync$1(() => rmSync(dir, {
46202
+ recursive: true,
46203
+ force: true
46204
+ })))
46205
+ });
46206
+ }));
46207
+ //#endregion
46019
46208
  //#region src/ui/index.ts
46020
46209
  var ui_exports = /* @__PURE__ */ __exportAll({
46021
46210
  UiError: () => UiError,
46211
+ UiHost: () => UiHost,
46022
46212
  UiListener: () => UiListener,
46023
46213
  UiShell: () => UiShell,
46024
46214
  UiUsageError: () => UiUsageError,
@@ -46027,6 +46217,7 @@ var ui_exports = /* @__PURE__ */ __exportAll({
46027
46217
  generateSelfSignedCert: () => generateSelfSignedCert,
46028
46218
  liveHeadSha: () => liveHeadSha,
46029
46219
  liveReadFile: () => liveReadFile,
46220
+ liveUiHost: () => liveUiHost,
46030
46221
  parseTailscaleStatus: () => parseTailscaleStatus,
46031
46222
  pickBindHost: () => pickBindHost,
46032
46223
  readServeRecord: () => readServeRecord,
@@ -46036,6 +46227,7 @@ var ui_exports = /* @__PURE__ */ __exportAll({
46036
46227
  var init_ui = __esmMin((() => {
46037
46228
  init_Server();
46038
46229
  init_Ports();
46230
+ init_Host$1();
46039
46231
  init_Write();
46040
46232
  init_Serve();
46041
46233
  init_Bind();
@@ -57049,7 +57241,7 @@ var init_main = __esmMin((() => {
57049
57241
  }));
57050
57242
  //#endregion
57051
57243
  //#region src/lsp/Lsp.ts
57052
- var import_main, toDocumentSymbol, FOOTNOTE_DEFINITION_RE, THREAD_REPLY_RE, revealPositionFor, toCodeAction, toLocation, lineSpan, toDiagnostic, diagnosticsFor, toDocumentLink, documentLinksFor, basenameFallbackFormat, formatForDocument, resolveWorkspaceRoot, OPEN_STEERING_FILE_COMMAND, REVEAL_POSITION_COMMAND, steeringFileOutcome, errorText, revealPositionArgs, makeSteeringLanguageService, bindSteeringServer, run$1, optionalString, parseCurrentRest, makeNodeLspEnv, startLspServer;
57244
+ var import_main, toDocumentSymbol, FOOTNOTE_DEFINITION_RE, THREAD_REPLY_RE, revealPositionFor, toCodeAction, toLocation, lineSpan, toDiagnostic, diagnosticsFor, toDocumentLink, documentLinksFor, basenameFallbackFormat, formatForDocument, resolveWorkspaceRoot, OPEN_STEERING_FILE_COMMAND, REVEAL_POSITION_COMMAND, steeringFileOutcome, errorText, revealPositionArgs, makeSteeringLanguageService, bindSteeringServer, run$1, optionalString, parseCurrentRest, nodeLspIo, makeLspEnv, serve, serveLspOver, startLspServer;
57053
57245
  var init_Lsp = __esmMin((() => {
57054
57246
  init_esm();
57055
57247
  import_main = require_main();
@@ -57345,22 +57537,28 @@ var init_Lsp = __esmMin((() => {
57345
57537
  mode: optionalString(parsed?.["mode"])
57346
57538
  };
57347
57539
  };
57348
- makeNodeLspEnv = (gtd, retryAfterMs = 5e3) => {
57540
+ nodeLspIo = (gtd) => ({
57541
+ cwd: process.cwd(),
57542
+ topLevel: async (dir) => resolve(dir, (await run$1("git", ["rev-parse", "--show-cdup"], dir)).trim()),
57543
+ head: async (root) => (await run$1("git", ["rev-parse", "HEAD"], root)).trim(),
57544
+ next: (root) => run$1(gtd[0], [
57545
+ ...gtd.slice(1),
57546
+ "next",
57547
+ "--json"
57548
+ ], root)
57549
+ });
57550
+ makeLspEnv = (io, retryAfterMs = 5e3) => {
57349
57551
  const memo = /* @__PURE__ */ new Map();
57350
57552
  return {
57351
- cwd: process.cwd(),
57352
- gitTopLevel: async (dir) => resolve(dir, (await run$1("git", ["rev-parse", "--show-cdup"], dir)).trim()),
57553
+ cwd: io.cwd,
57554
+ gitTopLevel: (dir) => io.topLevel(dir),
57353
57555
  currentRest: async (root) => {
57354
- const head = await run$1("git", ["rev-parse", "HEAD"], root).then((out) => out.trim(), () => "no-head");
57556
+ const head = await io.head(root).catch(() => "no-head");
57355
57557
  const cached = memo.get(root);
57356
57558
  if (cached?.head === head && (cached.failedAt === void 0 || Date.now() - cached.failedAt < retryAfterMs)) return cached.rest;
57357
57559
  const entry = {
57358
57560
  head,
57359
- rest: run$1(gtd[0], [
57360
- ...gtd.slice(1),
57361
- "next",
57362
- "--json"
57363
- ], root).then(parseCurrentRest)
57561
+ rest: io.next(root).then(parseCurrentRest)
57364
57562
  };
57365
57563
  memo.set(root, entry);
57366
57564
  entry.rest.catch(() => {
@@ -57370,20 +57568,28 @@ var init_Lsp = __esmMin((() => {
57370
57568
  }
57371
57569
  };
57372
57570
  };
57373
- startLspServer = (options) => gen(function* () {
57374
- const connection = (0, import_main.createConnection)(import_main.ProposedFeatures.all, process.stdin, process.stdout);
57571
+ serve = (io, connection) => gen(function* () {
57375
57572
  const documents = new import_main.TextDocuments(TextDocument);
57376
57573
  const warn = (message) => connection.console.warn(`gtd lsp: ${message}`);
57377
- const service = makeSteeringLanguageService(makeNodeLspEnv(options.gtd), warn);
57378
- bindSteeringServer(connection, documents, service);
57574
+ bindSteeringServer(connection, documents, makeSteeringLanguageService(makeLspEnv(io), warn));
57379
57575
  yield* async((resume) => {
57380
57576
  connection.onExit(() => resume(_void));
57381
57577
  });
57382
57578
  });
57579
+ serveLspOver = (io, input, output) => {
57580
+ const connection = (0, import_main.createConnection)(import_main.ProposedFeatures.all, new import_main.StreamMessageReader(input), new import_main.StreamMessageWriter(output));
57581
+ runPromise(serve(io, connection));
57582
+ return { close: () => connection.dispose() };
57583
+ };
57584
+ startLspServer = (options) => suspend$5(() => serve(nodeLspIo(options.gtd), (0, import_main.createConnection)(import_main.ProposedFeatures.all, process.stdin, process.stdout)));
57383
57585
  }));
57384
57586
  //#endregion
57385
57587
  //#region src/lsp/index.ts
57386
- var lsp_exports = /* @__PURE__ */ __exportAll({ startLspServer: () => startLspServer });
57588
+ var lsp_exports = /* @__PURE__ */ __exportAll({
57589
+ nodeLspIo: () => nodeLspIo,
57590
+ serveLspOver: () => serveLspOver,
57591
+ startLspServer: () => startLspServer
57592
+ });
57387
57593
  var init_lsp = __esmMin((() => {
57388
57594
  init_Lsp();
57389
57595
  }));
@@ -57854,9 +58060,47 @@ var init_loop = __esmMin((() => {
57854
58060
  init_Host();
57855
58061
  }));
57856
58062
  //#endregion
58063
+ //#region src/judges/providers/io.ts
58064
+ var liveJudgeIo;
58065
+ var init_io = __esmMin((() => {
58066
+ liveJudgeIo = {
58067
+ readFile: (path) => readFile(path, "utf8"),
58068
+ fetch: (input, init) => fetch(input, init),
58069
+ claude: ({ argv, stdin, env, cwd, timeoutMs }) => new Promise((resolve) => {
58070
+ const child = execFile("claude", argv, {
58071
+ cwd,
58072
+ env,
58073
+ timeout: timeoutMs,
58074
+ killSignal: "SIGKILL",
58075
+ maxBuffer: 64 * 1024 * 1024
58076
+ }, (e, stdout, stderr) => {
58077
+ if (!e) return resolve({
58078
+ kind: "exited",
58079
+ code: 0,
58080
+ stdout,
58081
+ stderr
58082
+ });
58083
+ const { code, killed, message } = e;
58084
+ resolve(code === "ENOENT" ? { kind: "missing" } : killed ? { kind: "timeout" } : typeof code === "number" ? {
58085
+ kind: "exited",
58086
+ code,
58087
+ stdout,
58088
+ stderr
58089
+ } : {
58090
+ kind: "unstartable",
58091
+ message
58092
+ });
58093
+ });
58094
+ child.stdin?.on("error", () => {});
58095
+ child.stdin?.end(stdin);
58096
+ })
58097
+ };
58098
+ }));
58099
+ //#endregion
57857
58100
  //#region src/judges/providers/fixed.ts
57858
58101
  var fail$3, isAnswer, isProbability, validate, fixed;
57859
58102
  var init_fixed = __esmMin((() => {
58103
+ init_io();
57860
58104
  fail$3 = (message) => {
57861
58105
  throw new Error(`gtd judge run: ${message}`);
57862
58106
  };
@@ -57877,10 +58121,10 @@ var init_fixed = __esmMin((() => {
57877
58121
  p
57878
58122
  };
57879
58123
  };
57880
- fixed = ({ answersPath, env }) => async (questions) => {
58124
+ fixed = ({ answersPath, env, io = liveJudgeIo }) => async (questions) => {
57881
58125
  const inline = env["GTD_JUDGE_ANSWERS"];
57882
58126
  let raw;
57883
- if (answersPath !== void 0) raw = await readFile(answersPath, "utf8").catch((e) => fail$3(`cannot read --answers ${answersPath}: ${e instanceof Error ? e.message : String(e)}`));
58127
+ if (answersPath !== void 0) raw = await io.readFile(answersPath).catch((e) => fail$3(`cannot read --answers ${answersPath}: ${e instanceof Error ? e.message : String(e)}`));
57884
58128
  else if (inline !== void 0 && inline !== "") raw = inline;
57885
58129
  else return fail$3("provider \"fixed\" needs --answers <path> or GTD_JUDGE_ANSWERS");
57886
58130
  let parsed;
@@ -57917,6 +58161,7 @@ var init_criteria = __esmMin((() => {
57917
58161
  var DEFAULT_URL, MODEL, RETRIES, fail$2, translate, toRequest, clamp, unreadable$1, num, probs, toVerdict$1, toVerdicts, sleep, post, parse, jev;
57918
58162
  var init_jev = __esmMin((() => {
57919
58163
  init_criteria();
58164
+ init_io();
57920
58165
  DEFAULT_URL = "https://api.typesafe.ai/v1/systemone";
57921
58166
  MODEL = "jev-latest";
57922
58167
  RETRIES = 3;
@@ -58002,9 +58247,9 @@ var init_jev = __esmMin((() => {
58002
58247
  return questions.map((q) => toVerdict$1(q, map[q.id]));
58003
58248
  };
58004
58249
  sleep = (ms) => new Promise((r) => setTimeout(r, ms));
58005
- post = async (url, key, body, delayMs) => {
58250
+ post = async (io, url, key, body, delayMs) => {
58006
58251
  for (let attempt = 0;; attempt++) {
58007
- const res = await fetch(url, {
58252
+ const res = await io.fetch(url, {
58008
58253
  method: "POST",
58009
58254
  headers: {
58010
58255
  Authorization: `Bearer ${key}`,
@@ -58029,11 +58274,11 @@ var init_jev = __esmMin((() => {
58029
58274
  return unreadable$1("not JSON");
58030
58275
  }
58031
58276
  };
58032
- jev = ({ env, retryDelayMs = 2e3 }) => async (questions, state) => {
58277
+ jev = ({ env, retryDelayMs = 2e3, io = liveJudgeIo }) => async (questions, state) => {
58033
58278
  const key = env["TYPESAFE_API_KEY"];
58034
58279
  if (key === void 0 || key === "") return fail$2("--provider jev needs TYPESAFE_API_KEY");
58035
58280
  const url = env["JEV_BASE_URL"] || DEFAULT_URL;
58036
- const text = await post(url, key, JSON.stringify(toRequest(questions, state)), retryDelayMs);
58281
+ const text = await post(io, url, key, JSON.stringify(toRequest(questions, state)), retryDelayMs);
58037
58282
  return toVerdicts(questions, parse(text));
58038
58283
  };
58039
58284
  }));
@@ -58042,6 +58287,7 @@ var init_jev = __esmMin((() => {
58042
58287
  var DEFAULT_MODEL, TIMEOUT_MS, SYSTEM_PROMPT, fail$1, unreadable, levelsOf, optionsOf, describe, toPrompt, answerSchema, toSchema, isObject, toVerdict, toLlmVerdicts, run, llm;
58043
58288
  var init_llm = __esmMin((() => {
58044
58289
  init_criteria();
58290
+ init_io();
58045
58291
  DEFAULT_MODEL = "haiku";
58046
58292
  TIMEOUT_MS = 18e4;
58047
58293
  SYSTEM_PROMPT = "You are a strict, impartial judge. Answer each question from the supplied evidence alone.\nReply only with the structured answer; never use tools or ask questions.";
@@ -58116,40 +58362,35 @@ var init_llm = __esmMin((() => {
58116
58362
  if (missing.length > 0) return fail$1(`claude answered ${questions.length - missing.length} of ${questions.length} questions; missing ${missing.map((q) => q.id).join(", ")}`);
58117
58363
  return questions.map((q) => toVerdict(q, out[q.id]));
58118
58364
  };
58119
- run = (argv, stdin, { env, cwd, timeoutMs }) => new Promise((resolve, reject) => {
58120
- const child = execFile("claude", argv, {
58121
- cwd,
58122
- env,
58123
- timeout: timeoutMs,
58124
- killSignal: "SIGKILL",
58125
- maxBuffer: 64 * 1024 * 1024
58126
- }, (e, stdout, stderr) => {
58127
- if (!e) return resolve(stdout);
58128
- const { code, killed, message } = e;
58129
- reject(/* @__PURE__ */ new Error(code === "ENOENT" ? "gtd judge run: --provider llm needs `claude` on PATH" : killed ? `gtd judge run: claude timed out after ${timeoutMs} ms` : typeof code === "number" ? `gtd judge run: claude exited ${code}: ${stderr.slice(0, 2048)}` : `gtd judge run: claude failed to start: ${message}`));
58130
- });
58131
- child.stdin?.on("error", () => {});
58132
- child.stdin?.end(stdin);
58133
- });
58134
- llm = ({ env, cwd, model = DEFAULT_MODEL, timeoutMs = TIMEOUT_MS }) => async (questions, state) => {
58365
+ run = async (io, call) => {
58366
+ const outcome = await io.claude(call);
58367
+ if (outcome.kind === "missing") return fail$1("--provider llm needs `claude` on PATH");
58368
+ if (outcome.kind === "timeout") return fail$1(`claude timed out after ${call.timeoutMs} ms`);
58369
+ if (outcome.kind === "unstartable") return fail$1(`claude failed to start: ${outcome.message}`);
58370
+ if (outcome.code !== 0) return fail$1(`claude exited ${outcome.code}: ${outcome.stderr.slice(0, 2048)}`);
58371
+ return outcome.stdout;
58372
+ };
58373
+ llm = ({ env, cwd, model = DEFAULT_MODEL, timeoutMs = TIMEOUT_MS, io = liveJudgeIo }) => async (questions, state) => {
58135
58374
  const schema = JSON.stringify(toSchema(questions));
58136
58375
  const prompt = toPrompt(questions, state);
58137
- const stdout = await run([
58138
- "-p",
58139
- "--model",
58140
- model,
58141
- "--output-format",
58142
- "json",
58143
- "--json-schema",
58144
- schema,
58145
- "--system-prompt",
58146
- SYSTEM_PROMPT,
58147
- "--tools",
58148
- "",
58149
- "--no-session-persistence",
58150
- "--settings",
58151
- "{\"disableAllHooks\":true}"
58152
- ], prompt, {
58376
+ const stdout = await run(io, {
58377
+ argv: [
58378
+ "-p",
58379
+ "--model",
58380
+ model,
58381
+ "--output-format",
58382
+ "json",
58383
+ "--json-schema",
58384
+ schema,
58385
+ "--system-prompt",
58386
+ SYSTEM_PROMPT,
58387
+ "--tools",
58388
+ "",
58389
+ "--no-session-persistence",
58390
+ "--settings",
58391
+ "{\"disableAllHooks\":true}"
58392
+ ],
58393
+ stdin: prompt,
58153
58394
  env,
58154
58395
  cwd,
58155
58396
  timeoutMs
@@ -58161,6 +58402,7 @@ var init_llm = __esmMin((() => {
58161
58402
  //#region src/judges/run.ts
58162
58403
  var PROVIDERS, fail, envProvider, checkPairing, userConfigPath, readText, parseObject, decodeUserConfig, readUserConfig, selectJudge, answererFor, runJudge;
58163
58404
  var init_run = __esmMin((() => {
58405
+ init_io();
58164
58406
  init_fixed();
58165
58407
  init_jev();
58166
58408
  init_llm();
@@ -58184,9 +58426,9 @@ var init_run = __esmMin((() => {
58184
58426
  const home = env["HOME"];
58185
58427
  return home ? `${home}/.config/gtd/judge.json` : void 0;
58186
58428
  };
58187
- readText = async (path) => {
58429
+ readText = async (io, path) => {
58188
58430
  try {
58189
- return await readFile(path, "utf8");
58431
+ return await io.readFile(path);
58190
58432
  } catch (e) {
58191
58433
  if (e.code === "ENOENT") return void 0;
58192
58434
  return fail(`cannot read ${path}: ${e instanceof Error ? e.message : String(e)}`);
@@ -58212,9 +58454,9 @@ var init_run = __esmMin((() => {
58212
58454
  model
58213
58455
  };
58214
58456
  };
58215
- readUserConfig = async (env) => {
58457
+ readUserConfig = async (io, env) => {
58216
58458
  const path = userConfigPath(env);
58217
- const text = path === void 0 ? void 0 : await readText(path);
58459
+ const text = path === void 0 ? void 0 : await readText(io, path);
58218
58460
  return path === void 0 || text === void 0 ? void 0 : decodeUserConfig(path, text);
58219
58461
  };
58220
58462
  selectJudge = ({ provider, model, env }, user) => {
@@ -58235,17 +58477,22 @@ var init_run = __esmMin((() => {
58235
58477
  });
58236
58478
  };
58237
58479
  answererFor = async (opts) => {
58238
- const { answers, env, cwd } = opts;
58239
- const { provider, model } = selectJudge(opts, await readUserConfig(env));
58480
+ const { answers, env, cwd, io = liveJudgeIo } = opts;
58481
+ const { provider, model } = selectJudge(opts, await readUserConfig(io, env));
58240
58482
  if (provider === "fixed") return fixed({
58241
58483
  answersPath: answers,
58242
- env
58484
+ env,
58485
+ io
58486
+ });
58487
+ if (provider === "jev" || provider === void 0 && model === void 0 && env["TYPESAFE_API_KEY"]) return jev({
58488
+ env,
58489
+ io
58243
58490
  });
58244
- if (provider === "jev" || provider === void 0 && model === void 0 && env["TYPESAFE_API_KEY"]) return jev({ env });
58245
58491
  return llm({
58246
58492
  env,
58247
58493
  cwd,
58248
- model
58494
+ model,
58495
+ io
58249
58496
  });
58250
58497
  };
58251
58498
  runJudge = async (opts) => {
@@ -58264,11 +58511,13 @@ var init_run = __esmMin((() => {
58264
58511
  //#endregion
58265
58512
  //#region src/judges/index.ts
58266
58513
  var judges_exports = /* @__PURE__ */ __exportAll({
58514
+ liveJudgeIo: () => liveJudgeIo,
58267
58515
  runJudge: () => runJudge,
58268
58516
  toRequest: () => toRequest
58269
58517
  });
58270
58518
  var init_judges = __esmMin((() => {
58271
58519
  init_run();
58520
+ init_io();
58272
58521
  init_jev();
58273
58522
  }));
58274
58523
  //#endregion
@@ -58286,8 +58535,8 @@ const liveToolCommands = effect$1(ToolCommands, gen(function* () {
58286
58535
  const fs = yield* FileSystem;
58287
58536
  return {
58288
58537
  ui: (request, out) => lazy("ui", async () => {
58289
- const { runUiCommand, UiListener, UiShell, UiUsageError } = await Promise.resolve().then(() => (init_ui(), ui_exports));
58290
- return () => runUiCommand(request.flags, uiConfigOf(request.config), out, request.root).pipe(provideService(UiShell, shell), provideService(FileSystem, fs), provide$1(UiListener.Live), mapError$1((error) => error instanceof UiUsageError ? new GtdUsageError(error.message, error.detail) : new GtdError(error.message, error.detail)));
58538
+ const { runUiCommand, UiListener, UiShell, UiUsageError, liveUiHost } = await Promise.resolve().then(() => (init_ui(), ui_exports));
58539
+ return () => runUiCommand(request.flags, uiConfigOf(request.config), out, request.root).pipe(provideService(UiShell, shell), provideService(FileSystem, fs), provide$1(UiListener.Live), provide$1(liveUiHost), mapError$1((error) => error instanceof UiUsageError ? new GtdUsageError(error.message, error.detail) : new GtdError(error.message, error.detail)));
58291
58540
  }),
58292
58541
  lsp: (gtd) => lazy("lsp", async () => {
58293
58542
  const { startLspServer } = await Promise.resolve().then(() => (init_lsp(), lsp_exports));