teamhandbook-orchestrator 0.3.0 → 0.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.
package/bin/main.mjs CHANGED
@@ -2063,8 +2063,8 @@ var CUT_SCOPE_SENTENCE = new RegExp(
2063
2063
  `\\s*Applies ONLY in the(?: \\S*${openingsOf(" repository - do not use it elsewhere.")})?$`
2064
2064
  );
2065
2065
  function withoutScopeSentence(description) {
2066
- const cut2 = CUT_SCOPE_SENTENCE.exec(description.replace(/[\u2013\u2014]/g, "-"));
2067
- const whole = cut2 ? description.slice(0, cut2.index) : description;
2066
+ const cut3 = CUT_SCOPE_SENTENCE.exec(description.replace(/[\u2013\u2014]/g, "-"));
2067
+ const whole = cut3 ? description.slice(0, cut3.index) : description;
2068
2068
  return whole.replace(SCOPE_SENTENCE, "").trim();
2069
2069
  }
2070
2070
  function assembleSkillMd(draft, scope, from = false) {
@@ -2866,10 +2866,6 @@ function policyDenial(rules, call) {
2866
2866
  // server/plugin.ts
2867
2867
  init_queue();
2868
2868
 
2869
- // ../src/lib/task-lesson.ts
2870
- import { mkdirSync as mkdirSync6, readFileSync as readFileSync8, writeFileSync as writeFileSync6 } from "node:fs";
2871
- import { join as join12 } from "node:path";
2872
-
2873
2869
  // ../src/lib/deliver.ts
2874
2870
  import { existsSync as existsSync6, readFileSync as readFileSync7, rmdirSync, rmSync as rmSync4 } from "node:fs";
2875
2871
  import { homedir as homedir6 } from "node:os";
@@ -2945,6 +2941,15 @@ function deliverPersonal(dir, meta, decidedAt, skillsDir = personalSkillsDir(),
2945
2941
  };
2946
2942
  }
2947
2943
 
2944
+ // ../src/lib/lesson-review.ts
2945
+ init_queue();
2946
+ init_secrets();
2947
+ init_skill_index();
2948
+
2949
+ // ../src/lib/task-lesson.ts
2950
+ import { mkdirSync as mkdirSync6, readFileSync as readFileSync8, writeFileSync as writeFileSync6 } from "node:fs";
2951
+ import { join as join12 } from "node:path";
2952
+
2948
2953
  // ../src/lib/harvest.ts
2949
2954
  import { createHash as createHash2 } from "node:crypto";
2950
2955
  init_session_state();
@@ -3097,6 +3102,8 @@ function keepTaskLesson(home, slug, skillsDir, decidedAt, host) {
3097
3102
  const meta = taskLessons(home).find((m) => m.slug === slug);
3098
3103
  if (!meta) return { ok: false, error: `no lesson from a task named "${slug}"` };
3099
3104
  if (meta.status !== "pending") return { ok: false, error: `lesson "${slug}" is already ${meta.status}` };
3105
+ const secret = secretInSkillDir(join12(candidatesDir(home), slug));
3106
+ if (secret) return { ok: false, error: `lesson "${slug}" holds what looks like a credential (${secret.pattern} in ${secret.file}), so it is not kept; edit it with /handbook:review` };
3100
3107
  return deliverPersonal(join12(candidatesDir(home), slug), meta, decidedAt, skillsDir, { host });
3101
3108
  }
3102
3109
  function rejectTaskLesson(home, slug, decidedAt, never) {
@@ -3312,6 +3319,7 @@ var ForgeRefusal = class extends OrchestratorError {
3312
3319
  super("forge-refused", message, 409);
3313
3320
  }
3314
3321
  };
3322
+ var missingBranch = (branch, repoName) => `branch ${branch} is not in ${repoName}: it was not pushed there, or it was deleted since; push it again, then open the request`;
3315
3323
  function localDescriptionRef(branch) {
3316
3324
  return `refs/notes/orchestrator/${branch}`;
3317
3325
  }
@@ -3422,7 +3430,7 @@ function createLocalForge(workRoot, ledger, urlBase = "local://requests") {
3422
3430
  if (!BRANCH.test(pushed.branch) || pushed.branch.includes("..")) throw new Error(`invalid branch name ${JSON.stringify(pushed.branch)}`);
3423
3431
  return oneAtATime(bare, async () => {
3424
3432
  const headSha = (await gitAsyncMaybe(["rev-parse", "--verify", "--quiet", `refs/heads/${pushed.branch}^{commit}`], bare))?.trim();
3425
- if (!headSha) throw new ForgeRefusal(`branch ${pushed.branch} is not in ${repo.name}; the runner pushes it first`);
3433
+ if (!headSha) throw new ForgeRefusal(missingBranch(pushed.branch, repo.name));
3426
3434
  if (await gitAsyncMaybe(["merge-base", "--is-ancestor", pushed.baseSha, headSha], bare) === null) {
3427
3435
  throw new ForgeRefusal(`branch ${pushed.branch} does not start from the commit the task started from`);
3428
3436
  }
@@ -3684,7 +3692,7 @@ function startProcess(inv, options) {
3684
3692
  };
3685
3693
  let kill = () => {
3686
3694
  };
3687
- const outcome = new Promise((resolve14) => {
3695
+ const outcome = new Promise((resolve15) => {
3688
3696
  const child = spawn(inv.program, inv.args, { cwd: inv.cwd, env: inv.env, detached: true, stdio: ["pipe", "pipe", "pipe"] });
3689
3697
  if (child.pid !== void 0) options.onSpawn?.(child.pid);
3690
3698
  const max = options.maxStdout ?? MAX_STDOUT;
@@ -3741,14 +3749,14 @@ function startProcess(inv, options) {
3741
3749
  if (child.stdin.writable) child.stdin.end(last2 ?? "");
3742
3750
  };
3743
3751
  kill = onAbort;
3744
- const finish = (code) => {
3752
+ const finish = (code, signal = null) => {
3745
3753
  if (settled) return;
3746
3754
  settled = true;
3747
3755
  clearTimeout(timer);
3748
3756
  options.signal.removeEventListener("abort", onAbort);
3749
3757
  for (const stream2 of ["stdout", "stderr"]) if (pending[stream2]) options.onLine(stream2, pending[stream2]);
3750
3758
  killGroup("SIGKILL");
3751
- resolve14({ code, timedOut, cancelled, stdout: dropped2 ? `${stdout}
3759
+ resolve15({ code, ...code === null && signal ? { signal } : {}, timedOut, cancelled, stdout: dropped2 ? `${stdout}
3752
3760
  ${tail.slice(tail.indexOf("\n") + 1)}` : stdout + tail });
3753
3761
  };
3754
3762
  child.on("error", (err) => {
@@ -3756,7 +3764,7 @@ ${tail.slice(tail.indexOf("\n") + 1)}` : stdout + tail });
3756
3764
  finish(null);
3757
3765
  });
3758
3766
  child.on("exit", () => killGroup("SIGKILL"));
3759
- child.on("close", (code) => finish(code));
3767
+ child.on("close", (code, signal) => finish(code, signal));
3760
3768
  });
3761
3769
  return { outcome, write: (text) => write(text), end: (last2) => end(last2), kill: () => kill() };
3762
3770
  }
@@ -4047,7 +4055,8 @@ function opencodeMcp(id, servers) {
4047
4055
  function signInEvents(waiting) {
4048
4056
  if (!waiting.length) return [];
4049
4057
  const one = waiting.length === 1;
4050
- const names2 = one ? waiting[0] : `${waiting.slice(0, -1).join(", ")} and ${waiting.at(-1)}`;
4058
+ const said3 = waiting.map((name) => name.replace(PLUGIN_SERVER, ""));
4059
+ const names2 = one ? said3[0] : `${said3.slice(0, -1).join(", ")} and ${said3.at(-1)}`;
4051
4060
  return [
4052
4061
  { type: "mcp_status", needsSignIn: [...waiting] },
4053
4062
  { type: "notice", text: `${names2} ${one ? "needs" : "need"} a sign-in, so ${one ? "its" : "their"} tools are not in this task. Sign ${one ? "it" : "them"} in on this machine, then start the task again.` }
@@ -4174,7 +4183,7 @@ function claudeCodeDecoder(asked = null, work, opened = asked ? CLAUDE_MODE[aske
4174
4183
  let refusedSignIn = false;
4175
4184
  let resetAt;
4176
4185
  let spent = null;
4177
- let session = null;
4186
+ let session2 = null;
4178
4187
  let told = false;
4179
4188
  const running = /* @__PURE__ */ new Set();
4180
4189
  const calls = /* @__PURE__ */ new Map();
@@ -4200,7 +4209,7 @@ function claudeCodeDecoder(asked = null, work, opened = asked ? CLAUDE_MODE[aske
4200
4209
  decode(line) {
4201
4210
  const frame = parseLine(line);
4202
4211
  if (!frame) return outputLine(line);
4203
- if (typeof frame.session_id === "string") session = frame.session_id;
4212
+ if (typeof frame.session_id === "string") session2 = frame.session_id;
4204
4213
  if (frame.type === "system" && (frame.subtype === "task_started" || frame.subtype === "task_notification") && typeof frame.task_id === "string") {
4205
4214
  const before = running.size;
4206
4215
  if (frame.subtype === "task_started" && frame.is_backgrounded === true) running.add(frame.task_id);
@@ -4322,7 +4331,7 @@ function claudeCodeDecoder(asked = null, work, opened = asked ? CLAUDE_MODE[aske
4322
4331
  ];
4323
4332
  },
4324
4333
  finish(exitCode) {
4325
- const end = { summary: last2?.summary ?? "", ...session ? { nativeSessionId: session } : {} };
4334
+ const end = { summary: last2?.summary ?? "", ...session2 ? { nativeSessionId: session2 } : {} };
4326
4335
  if (exitCode === 0 && last2?.ok) return { type: "terminal", status: "completed", ...end };
4327
4336
  if (aborted) return { type: "terminal", status: "interrupted", ...end };
4328
4337
  const why = failed ?? (last2 ? null : failure("Claude Code", "transport", { code: exitCode === null ? "no exit code" : `exit ${exitCode}` }));
@@ -4395,7 +4404,7 @@ function refusalOf(frame) {
4395
4404
  }
4396
4405
  function signInNotice(servers) {
4397
4406
  if (!Array.isArray(servers)) return [];
4398
- return signInEvents(servers.flatMap((s) => s?.status === "needs-auth" && typeof s.name === "string" && s.name ? [s.name.replace(/^plugin_[^_]+_(?=.)/, "")] : []));
4407
+ return signInEvents(servers.flatMap((s) => s?.status === "needs-auth" && typeof s.name === "string" && s.name ? [s.name] : []));
4399
4408
  }
4400
4409
  var MCP_STATE = { connected: "connected", pending: "starting", "needs-auth": "needs-sign-in", failed: "failed", disabled: "off" };
4401
4410
  function loadedOf(frame) {
@@ -4693,9 +4702,9 @@ function callEvent2(id, tool, input, status2, work, servers = []) {
4693
4702
  function shellLines(id, output, sent, ended4) {
4694
4703
  const from = output.length < sent ? 0 : sent;
4695
4704
  const rest = output.slice(from);
4696
- const cut2 = ended4 ? rest.length : rest.lastIndexOf("\n") + 1;
4697
- const lines = outputLines(rest.slice(0, cut2));
4698
- return { events: lines.length ? [{ type: "tool_output", id, lines }] : [], sent: from + cut2 };
4705
+ const cut3 = ended4 ? rest.length : rest.lastIndexOf("\n") + 1;
4706
+ const lines = outputLines(rest.slice(0, cut3));
4707
+ return { events: lines.length ? [{ type: "tool_output", id, lines }] : [], sent: from + cut3 };
4699
4708
  }
4700
4709
  function callResult(id, tool, input, metadata, work) {
4701
4710
  if (tool === "edit") {
@@ -6040,6 +6049,7 @@ var RUNNER_PATHS = {
6040
6049
  progress: (taskId) => `/api/runner/tasks/${taskId}/progress`,
6041
6050
  forgeRequest: (taskId) => `/api/runner/tasks/${taskId}/request`,
6042
6051
  finish: (taskId) => `/api/runner/tasks/${taskId}/finish`,
6052
+ lateChanges: (taskId) => `/api/runner/tasks/${taskId}/late-changes`,
6043
6053
  /** The follow-ups that reached the task's agent. */
6044
6054
  followUpsDelivered: (taskId) => `/api/runner/tasks/${taskId}/follow-ups`,
6045
6055
  /** One of the task's attachments, its bytes, for the machine to put in the task's own folder. */
@@ -7801,10 +7811,10 @@ import { tmpdir as tmpdir2 } from "node:os";
7801
7811
  function cliEnv() {
7802
7812
  return Object.fromEntries(Object.entries(nonInteractiveEnv(process.env)).filter(([name]) => !name.startsWith("ORCHESTRATOR_") && name !== "GITEA_TOKEN" && name !== "GITEA_INSTANCE_URL"));
7803
7813
  }
7804
- var runOwnCli = (tool, args, input) => new Promise((resolve14) => {
7814
+ var runOwnCli = (tool, args, input) => new Promise((resolve15) => {
7805
7815
  const child = execFile3(tool, args, { cwd: tmpdir2(), env: cliEnv(), timeout: 6e4, maxBuffer: 1024 * 1024, encoding: "utf8" }, (err, stdout, stderr) => {
7806
7816
  const failure2 = err;
7807
- resolve14({ code: failure2 ? typeof failure2.code === "number" ? failure2.code : 1 : 0, stdout: String(stdout), stderr: String(stderr), missing: failure2?.code === "ENOENT" });
7817
+ resolve15({ code: failure2 ? typeof failure2.code === "number" ? failure2.code : 1 : 0, stdout: String(stdout), stderr: String(stderr), missing: failure2?.code === "ENOENT" });
7808
7818
  });
7809
7819
  child.stdin?.end(input ?? "");
7810
7820
  });
@@ -7974,6 +7984,21 @@ async function ownCliReady(kind, host, run2 = runOwnCli) {
7974
7984
  await signedIn(kind, host, run2);
7975
7985
  }
7976
7986
  var said = (text) => redactLine(text.replace(/\p{C}+/gu, " ").trim().slice(0, 300));
7987
+ function ownCliReader(kind, host, run2 = runOwnCli) {
7988
+ const t = TOOLS[kind];
7989
+ return {
7990
+ async request(method, path) {
7991
+ if (method !== "GET") throw new OwnCliRefused(`the orchestrator reads with your ${t.tool} sign-in alone`);
7992
+ const { as } = await signedIn(kind, host, run2);
7993
+ const read = await run2(t.tool, t.api(as, path.replace(/^\/+/, "")));
7994
+ const status2 = t.failed(read);
7995
+ if (status2 !== null) throw new ForgeHttpError(`${t.tool} did not read it: ${cliSaid(t, read)}`, status2);
7996
+ const body = parsed(read.stdout);
7997
+ if (!body) throw new ForgeHttpError(`${t.tool} answered with something other than JSON; update it (${t.install}), then try again`, 502);
7998
+ return body;
7999
+ }
8000
+ };
8001
+ }
7977
8002
  function ownCredentialConfig(kind) {
7978
8003
  return [["credential.helper", ""], ["credential.helper", TOOLS[kind].helper]];
7979
8004
  }
@@ -8068,7 +8093,7 @@ function createOwnCliForge(config, workRoot, mirror, gitEnv2, run2 = runOwnCli)
8068
8093
  const heads = await gitAsyncMaybe(["ls-remote", "--heads", repo.url, `refs/heads/${pushed.branch}`], tmpdir2(), { env: env2 });
8069
8094
  if (heads === null) throw new OwnCliRefused(`git did not reach ${repo.name} with your ${t.tool} sign-in; check it with \`${t.tool} auth status\``);
8070
8095
  const headSha = /^([0-9a-f]{40})\s/.exec(heads)?.[1];
8071
- if (!headSha) throw new ForgeRefusal(`branch ${pushed.branch} is not in ${repo.name}; the runner pushes it first`);
8096
+ if (!headSha) throw new ForgeRefusal(missingBranch(pushed.branch, repo.name));
8072
8097
  const assignment = pushed.assignment ?? NO_ASSIGNMENT;
8073
8098
  const answer = await createRequest(pushed.branch, pushed.target ?? await targetOf3(repo), pushed.title, pushed.body, assignment, as);
8074
8099
  if (answer.code !== 0) throw new OwnCliRefused(`${t.tool} did not open the request: ${cliSaid(t, answer)}; the branch stays as it was pushed, so open it again once \`${t.tool} auth status\` says you are signed in`);
@@ -8370,11 +8395,11 @@ ${change2.commitBody ?? change2.body}` : change2.title, change2.author) };
8370
8395
  async openForBranch(repo, pushed) {
8371
8396
  checkBranch(pushed.branch);
8372
8397
  const ref = await http.request("GET", `${repoPath}/git/ref/heads/${refPath(pushed.branch)}`).catch((err) => {
8373
- if (err instanceof ForgeHttpError && err.status === 404) throw new ForgeRefusal(`branch ${pushed.branch} is not in ${repo.name}; the runner pushes it first`);
8398
+ if (err instanceof ForgeHttpError && err.status === 404) throw new ForgeRefusal(missingBranch(pushed.branch, repo.name));
8374
8399
  throw err;
8375
8400
  });
8376
8401
  const headSha = ref.object?.sha;
8377
- if (typeof headSha !== "string") throw new ForgeRefusal(`branch ${pushed.branch} is not in ${repo.name}; the runner pushes it first`);
8402
+ if (typeof headSha !== "string") throw new ForgeRefusal(missingBranch(pushed.branch, repo.name));
8378
8403
  const base = pushed.target ?? (await http.request("GET", repoPath)).default_branch;
8379
8404
  const pull = await http.request("POST", `${repoPath}/pulls`, { title: pushed.title, head: pushed.branch, base, body: pushed.body });
8380
8405
  const notes = await assign(pull.number, pushed.assignment);
@@ -8385,7 +8410,7 @@ ${change2.commitBody ?? change2.body}` : change2.title, change2.author) };
8385
8410
  checkBranch(branch);
8386
8411
  if (!update.files.length) throw new Error("the change has no files");
8387
8412
  const ref = await http.request("GET", `${repoPath}/git/ref/heads/${refPath(branch)}`).catch((err) => {
8388
- if (err instanceof ForgeHttpError && err.status === 404) throw new ForgeRefusal(`branch ${branch} is not in ${repo.name}; open the request again`);
8413
+ if (err instanceof ForgeHttpError && err.status === 404) throw new ForgeRefusal(`branch ${branch} is no longer in ${repo.name} on GitHub: it was deleted there, so nothing was written to it; open the request again`);
8389
8414
  throw err;
8390
8415
  });
8391
8416
  if (ref.object?.sha !== update.expectedHead) throw new ForgeRefusal(`${branch} moved since the change was prepared; read the request again`);
@@ -8493,7 +8518,7 @@ function createGitLabForge(config, token2, fetchImpl = fetch, oauth = false) {
8493
8518
  checkBranch(branch);
8494
8519
  if (!update.files.length) throw new Error("the change has no files");
8495
8520
  const at2 = await http.request("GET", `${project}/repository/branches/${encodeURIComponent(branch)}`).catch((err) => {
8496
- if (err instanceof ForgeHttpError && err.status === 404) throw new ForgeRefusal(`branch ${branch} is not in ${repo.name}; open the request again`);
8521
+ if (err instanceof ForgeHttpError && err.status === 404) throw new ForgeRefusal(`branch ${branch} is no longer in ${repo.name} on GitLab: it was deleted there, so nothing was written to it; open the request again`);
8497
8522
  throw err;
8498
8523
  });
8499
8524
  if (at2.commit?.id !== update.expectedHead) throw new ForgeRefusal(`${branch} moved since the change was prepared; read the request again`);
@@ -8549,11 +8574,11 @@ ${change2.commitBody ?? change2.body}` : change2.title,
8549
8574
  async openForBranch(repo, pushed) {
8550
8575
  checkBranch(pushed.branch);
8551
8576
  const at2 = await http.request("GET", `${project}/repository/branches/${encodeURIComponent(pushed.branch)}`).catch((err) => {
8552
- if (err instanceof ForgeHttpError && err.status === 404) throw new ForgeRefusal(`branch ${pushed.branch} is not in ${repo.name}; the runner pushes it first`);
8577
+ if (err instanceof ForgeHttpError && err.status === 404) throw new ForgeRefusal(missingBranch(pushed.branch, repo.name));
8553
8578
  throw err;
8554
8579
  });
8555
8580
  const headSha = at2.commit?.id;
8556
- if (typeof headSha !== "string") throw new ForgeRefusal(`branch ${pushed.branch} is not in ${repo.name}; the runner pushes it first`);
8581
+ if (typeof headSha !== "string") throw new ForgeRefusal(missingBranch(pushed.branch, repo.name));
8557
8582
  const target = pushed.target ?? (await http.request("GET", project)).default_branch;
8558
8583
  const notes = [];
8559
8584
  const request = await http.request("POST", `${project}/merge_requests`, await mergeRequest2(pushed.branch, target, pushed.title, pushed.body, pushed.assignment, notes));
@@ -8597,7 +8622,7 @@ function pinnedFetch(host, address) {
8597
8622
  const send = url.protocol === "https:" ? httpsRequest : httpRequest;
8598
8623
  const headers = Object.fromEntries(new Headers(init.headers).entries());
8599
8624
  const body = typeof init.body === "string" ? init.body : init.body === void 0 || init.body === null ? void 0 : String(init.body);
8600
- return new Promise((resolve14, reject) => {
8625
+ return new Promise((resolve15, reject) => {
8601
8626
  const req = send(
8602
8627
  url,
8603
8628
  {
@@ -8627,7 +8652,7 @@ function pinnedFetch(host, address) {
8627
8652
  const status2 = res.statusCode ?? 0;
8628
8653
  const out = new Headers();
8629
8654
  for (const [k, v] of Object.entries(res.headers)) if (v !== void 0) out.set(k, Array.isArray(v) ? v.join(", ") : v);
8630
- resolve14(new Response([101, 204, 205, 304].includes(status2) ? null : Buffer.concat(chunks), { status: status2, headers: out }));
8655
+ resolve15(new Response([101, 204, 205, 304].includes(status2) ? null : Buffer.concat(chunks), { status: status2, headers: out }));
8631
8656
  });
8632
8657
  res.on("error", reject);
8633
8658
  }
@@ -8870,7 +8895,7 @@ var nativeRealpath = promisify2(realpath2.native);
8870
8895
  async function realOf(path) {
8871
8896
  return nativeRealpath(path).catch(() => null);
8872
8897
  }
8873
- async function projectFolder(path, { home = homedir7(), dataDir }, listing = false) {
8898
+ async function projectFolder(path, { home = homedir7(), dataDir }, listing2 = false) {
8874
8899
  const no = (refused) => ({ refused, message: MESSAGES[refused] });
8875
8900
  if (!isAbsolute5(path)) return no("not-absolute");
8876
8901
  const real = await realOf(path);
@@ -8879,12 +8904,12 @@ async function projectFolder(path, { home = homedir7(), dataDir }, listing = fal
8879
8904
  const homeReal2 = await realOf(home) ?? home;
8880
8905
  if (!within(homeReal2, real)) return { refused: "outside-home", message: onWindowsFromWsl(real) ?? MESSAGES["outside-home"] };
8881
8906
  const rel = relative3(homeReal2, real);
8882
- if (rel === "" && !listing) return no("home-itself");
8907
+ if (rel === "" && !listing2) return no("home-itself");
8883
8908
  const parts = rel ? rel.split(sep8) : [];
8884
8909
  if (parts.some((part) => part.startsWith("."))) return no("hidden");
8885
8910
  if (parts[0]?.toLowerCase() === "library") return no("library");
8886
8911
  const dataReal = await realOf(dataDir) ?? dataDir;
8887
- if (within(dataReal, real) || !listing && within(real, dataReal)) return no("data-dir");
8912
+ if (within(dataReal, real) || !listing2 && within(real, dataReal)) return no("data-dir");
8888
8913
  return { real };
8889
8914
  }
8890
8915
  var exists = (path) => lstat2(path).then(() => true, () => false);
@@ -8911,6 +8936,64 @@ async function shownProjects(ctx, user, listed) {
8911
8936
  async function isGitFolder(path) {
8912
8937
  return await exists(join20(path, ".git")) || await exists(join20(path, "HEAD")) && await exists(join20(path, "objects"));
8913
8938
  }
8939
+ function originOf(remote) {
8940
+ const scp = /^(?:ssh:\/\/)?[^@/\s]+@([^:/\s]+)(?::\d+)?[:/]([^\s]+?)(?:\.git)?\/?$/.exec(remote.trim());
8941
+ let host;
8942
+ let path;
8943
+ if (scp && !/^https?:/i.test(remote)) [host, path] = [scp[1], scp[2]];
8944
+ else if (URL.canParse(remote) && /^https?:$/.test(new URL(remote).protocol)) {
8945
+ const url = new URL(remote);
8946
+ [host, path] = [url.host, url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/, "")];
8947
+ } else return null;
8948
+ const forge = host === "github.com" ? "github" : host === "gitlab.com" ? "gitlab" : "other";
8949
+ return { forge, web: `https://${host}/${path}` };
8950
+ }
8951
+ function originInConfig(config) {
8952
+ let inOrigin = false;
8953
+ for (const raw of config.split("\n")) {
8954
+ const line = raw.trim();
8955
+ if (line.startsWith("[")) inOrigin = /^\[\s*remote\s+"origin"\s*\]$/.test(line);
8956
+ else if (inOrigin) {
8957
+ const set = /^url\s*=\s*(.+)$/.exec(line);
8958
+ if (set) return set[1].trim().replace(/^"(.*)"$/, "$1");
8959
+ }
8960
+ }
8961
+ return null;
8962
+ }
8963
+ async function gitDirsOf(real, where) {
8964
+ const dotGit = join20(real, ".git");
8965
+ const found = await lstat2(dotGit).catch(() => null);
8966
+ if (!found) return await exists(join20(real, "HEAD")) && await exists(join20(real, "objects")) ? { own: real, common: real } : void 0;
8967
+ if (found.isDirectory()) return { own: dotGit, common: dotGit };
8968
+ if (!found.isFile()) return null;
8969
+ const pointer = /^gitdir:\s*(.+)$/m.exec(await readFile3(dotGit, "utf8").catch(() => ""))?.[1]?.trim();
8970
+ if (!pointer) return null;
8971
+ const target = await realOf(isAbsolute5(pointer) ? pointer : join20(real, pointer));
8972
+ const homeReal2 = await realOf(where.home) ?? where.home;
8973
+ const dataReal = await realOf(where.dataDir) ?? where.dataDir;
8974
+ if (!target || !within(homeReal2, target) || within(dataReal, target) || within(target, dataReal)) return null;
8975
+ const common = (await readFile3(join20(target, "commondir"), "utf8").catch(() => "")).trim();
8976
+ return { own: target, common: common ? join20(target, common) : target };
8977
+ }
8978
+ async function noCommitYet(dirs) {
8979
+ const branch = /^ref:\s*(refs\/heads\/\S+)\s*$/.exec(await readFile3(join20(dirs.own, "HEAD"), "utf8").catch(() => ""))?.[1];
8980
+ if (!branch || branch.split("/").includes("..")) return false;
8981
+ if (await exists(join20(dirs.common, branch))) return false;
8982
+ const packed = await readFile3(join20(dirs.common, "packed-refs"), "utf8").catch(() => "");
8983
+ return !packed.split("\n").some((line) => line.endsWith(` ${branch}`));
8984
+ }
8985
+ async function projectFacts(real, { home = homedir7(), dataDir }) {
8986
+ const kind = await exists(join20(real, ".claude-plugin", "marketplace.json")) || await exists(join20(real, ".claude-plugin", "plugin.json")) ? "skills" : "code";
8987
+ const dirs = await gitDirsOf(real, { home, dataDir });
8988
+ if (dirs === void 0) {
8989
+ const repos = await repoCount(real);
8990
+ return { git: "none", origin: null, name: basename9(real), kind, empty: false, ...repos ? { repos } : {} };
8991
+ }
8992
+ const config = dirs ? await readFile3(join20(dirs.common, "config"), "utf8").catch(() => null) : null;
8993
+ const remote = config ? originInConfig(config) : null;
8994
+ const origin = remote ? originOf(remote) : null;
8995
+ return { git: origin ? "origin" : "repo", origin, name: basename9(real), kind, empty: dirs ? await noCommitYet(dirs) : false };
8996
+ }
8914
8997
  var MARKERS = [".git", "package.json", "pyproject.toml", "go.mod", "Cargo.toml", ".claude-plugin"];
8915
8998
  var ASKS_FIRST = /* @__PURE__ */ new Set(["desktop", "documents", "downloads", "pictures", "movies", "music"]);
8916
8999
  var SKIPPED2 = /* @__PURE__ */ new Set(["node_modules", "library"]);
@@ -9063,12 +9146,12 @@ var envProvider = defineSecretProvider(
9063
9146
  var OP_TIMEOUT_MS = 45e3;
9064
9147
  var OP_PART = "[A-Za-z0-9 ._-]{1,100}";
9065
9148
  var OP_REFERENCE = new RegExp(`^op://(${OP_PART})/${OP_PART}(?:/${OP_PART}){1,2}$`);
9066
- var runOp = (bin, args, env2, input) => new Promise((resolve14) => {
9149
+ var runOp = (bin, args, env2, input) => new Promise((resolve15) => {
9067
9150
  const child = spawn2(bin, [...args], { env: env2, stdio: ["pipe", "pipe", "ignore"], timeout: OP_TIMEOUT_MS });
9068
9151
  let stdout = "";
9069
9152
  child.stdout.setEncoding("utf8").on("data", (chunk) => void (stdout.length < 1048576 && (stdout += chunk)));
9070
- child.on("error", () => resolve14({ code: null, stdout: "" }));
9071
- child.on("close", (code) => resolve14({ code, stdout }));
9153
+ child.on("error", () => resolve15({ code: null, stdout: "" }));
9154
+ child.on("close", (code) => resolve15({ code, stdout }));
9072
9155
  child.stdin.end(input);
9073
9156
  });
9074
9157
  function opVaults(env2 = process.env) {
@@ -9527,7 +9610,7 @@ var USAGE_REQUESTS = {
9527
9610
  // ../package.json
9528
9611
  var package_default = {
9529
9612
  name: "teamhandbook",
9530
- version: "0.35.0",
9613
+ version: "0.36.0",
9531
9614
  description: "Manage your team's Claude Code setup from one git repository: approve a skill, an MCP server, or a slash command once, and every teammate's copy picks it up.",
9532
9615
  type: "module",
9533
9616
  private: true,
@@ -9944,7 +10027,7 @@ async function underLease(ctx, lease, sealed, renew, busy) {
9944
10027
  for (let waited = 0; ; waited += LEASE_POLL_MS) {
9945
10028
  const at2 = /* @__PURE__ */ new Date();
9946
10029
  if (await ctx.store.claimLease(ctx.tenant, lease, holder, new Date(at2.getTime() + LEASE_MS).toISOString(), at2.toISOString())) break;
9947
- await new Promise((resolve14) => setTimeout(resolve14, LEASE_POLL_MS));
10030
+ await new Promise((resolve15) => setTimeout(resolve15, LEASE_POLL_MS));
9948
10031
  const ready2 = await sealed();
9949
10032
  if (ready2) return ready2;
9950
10033
  if (waited > LEASE_MS) throw new ConnectionUnusable(busy);
@@ -11121,8 +11204,8 @@ async function toolChoiceOf(ctx, projectId, projectSkills, mcpServers2, confirme
11121
11204
 
11122
11205
  // server/tasks/check-sandbox.ts
11123
11206
  import { execFile as execFile4 } from "node:child_process";
11124
- import { access, realpath as realpath4, stat as stat3 } from "node:fs/promises";
11125
- import { dirname as dirname14, join as join26 } from "node:path";
11207
+ import { access, lstat as lstat6, readlink, realpath as realpath4, stat as stat3 } from "node:fs/promises";
11208
+ import { dirname as dirname14, join as join26, resolve as resolve11 } from "node:path";
11126
11209
  var TOOL_PLACES = [
11127
11210
  ".npm",
11128
11211
  ".cache",
@@ -11184,6 +11267,25 @@ async function resolved(places) {
11184
11267
  const kept2 = async (paths) => [...new Set((await Promise.all(paths.map((p) => realpath4(p).catch(() => null)))).filter((p) => p !== null))];
11185
11268
  return { hidden: await kept2(places.hidden), tools: await kept2(places.tools), secrets: await kept2(places.secrets), readable: await kept2(places.readable), writable: await kept2(places.writable) };
11186
11269
  }
11270
+ var LINK_HOPS = 40;
11271
+ async function linksTo(path) {
11272
+ const links = [];
11273
+ let rest = path.split("/").filter(Boolean);
11274
+ let at2 = "/";
11275
+ while (rest.length && links.length < LINK_HOPS) {
11276
+ const next = join26(at2, rest.shift());
11277
+ const info = await lstat6(next).catch(() => null);
11278
+ if (!info) break;
11279
+ if (!info.isSymbolicLink()) {
11280
+ at2 = next;
11281
+ continue;
11282
+ }
11283
+ links.push(next);
11284
+ rest = [...resolve11(at2, await readlink(next)).split("/").filter(Boolean), ...rest];
11285
+ at2 = "/";
11286
+ }
11287
+ return links;
11288
+ }
11187
11289
  function checkPlaces(task, person, dataDir, platform = process.platform) {
11188
11290
  const home = person.home;
11189
11291
  const under = (path) => Boolean(home) && path.startsWith(`${home}/`);
@@ -11197,7 +11299,7 @@ function checkPlaces(task, person, dataDir, platform = process.platform) {
11197
11299
  writable: [task.work, task.tmp, task.home]
11198
11300
  };
11199
11301
  }
11200
- function seatbeltProfile(places) {
11302
+ function seatbeltProfile(places, links = []) {
11201
11303
  const params = [];
11202
11304
  const names2 = (kind, paths) => paths.map((path, i) => {
11203
11305
  params.push("-D", `${kind}${i}=${path}`);
@@ -11206,6 +11308,10 @@ function seatbeltProfile(places) {
11206
11308
  const rule = (paths, make) => paths.length ? [make(paths.join(" "))] : [];
11207
11309
  const hidden = names2("HIDE", places.hidden);
11208
11310
  const tools = names2("TOOL", places.tools);
11311
+ const linked = links.map((path, i) => {
11312
+ params.push("-D", `LINK${i}=${path}`);
11313
+ return `(literal (param "LINK${i}"))`;
11314
+ });
11209
11315
  const secrets = names2("SECRET", places.secrets);
11210
11316
  const readable = names2("READ", places.readable);
11211
11317
  const writable = names2("WRITE", places.writable);
@@ -11227,6 +11333,7 @@ function seatbeltProfile(places) {
11227
11333
  '(allow network-outbound (remote unix-socket (path-literal "/private/var/run/mDNSResponder")))',
11228
11334
  ...rule(hidden, (f) => `(deny file-read* file-write* ${f})`),
11229
11335
  ...rule(tools, (f) => `(allow file-read* ${f})`),
11336
+ ...rule(linked, (f) => `(allow file-read* ${f})`),
11230
11337
  ...rule(secrets, (f) => `(deny file-read* file-write* ${f})`),
11231
11338
  ...rule(above, (f) => `(allow file-read-metadata ${f})`),
11232
11339
  ...rule(readable, (f) => `(allow file-read* ${f})`),
@@ -11272,7 +11379,8 @@ async function findCheckSandbox(platform = process.platform, path = process.env.
11272
11379
  async function sandboxed(box, places, inv) {
11273
11380
  const at2 = await resolved(places);
11274
11381
  if (box.tool === "seatbelt") {
11275
- const { profile, params } = seatbeltProfile(at2);
11382
+ const links = [...new Set((await Promise.all([...places.tools, ...places.readable, ...places.writable].map(linksTo))).flat())];
11383
+ const { profile, params } = seatbeltProfile(at2, links);
11276
11384
  return { ...inv, program: box.program, args: ["-p", profile, ...params, inv.program, ...inv.args] };
11277
11385
  }
11278
11386
  const hidden = [...at2.hidden, ...at2.secrets];
@@ -11331,7 +11439,16 @@ async function commandsOf(program, env2, cwd, timeoutMs) {
11331
11439
  await started.outcome;
11332
11440
  return commands;
11333
11441
  }
11334
- async function listedPlugins(program, env2, cwd, timeoutMs) {
11442
+ function listedPlugins(program, env2, cwd, timeoutMs) {
11443
+ const key = `${program}\0${env2.CLAUDE_CONFIG_DIR ?? ""}\0${env2.HOME ?? ""}`;
11444
+ const running = listing.get(key);
11445
+ if (running) return running;
11446
+ const run2 = readListedPlugins(program, env2, cwd, timeoutMs).finally(() => listing.delete(key));
11447
+ listing.set(key, run2);
11448
+ return run2;
11449
+ }
11450
+ var listing = /* @__PURE__ */ new Map();
11451
+ async function readListedPlugins(program, env2, cwd, timeoutMs) {
11335
11452
  const listed = await runProcess({ program, args: ["plugin", "list", "--json"], env: env2, cwd }, { timeoutMs, signal: new AbortController().signal, onLine: () => {
11336
11453
  } });
11337
11454
  if (listed.code !== 0) return null;
@@ -11391,11 +11508,11 @@ async function probePersonalSetup(program, env2, cwd, folders = [], timeoutMs =
11391
11508
  }
11392
11509
 
11393
11510
  // server/tasks/handbook-sources.ts
11394
- import { lstat as lstat6, open, readdir as readdir6, readFile as readFile7, realpath as realpath5, stat as stat5 } from "node:fs/promises";
11511
+ import { lstat as lstat7, open, readdir as readdir6, readFile as readFile7, realpath as realpath5, stat as stat5 } from "node:fs/promises";
11395
11512
  import { basename as basename11, dirname as dirname15, join as join29, relative as relative6, isAbsolute as isAbsolute8 } from "node:path";
11396
11513
 
11397
11514
  // server/forge/plugin-changes.ts
11398
- import { join as join28, resolve as resolve11, sep as sep10 } from "node:path";
11515
+ import { join as join28, resolve as resolve12, sep as sep10 } from "node:path";
11399
11516
 
11400
11517
  // server/forge/team-changes.ts
11401
11518
  var PATCH_MAX = 64 * 1024;
@@ -11404,9 +11521,9 @@ var PATCH_MAX = 64 * 1024;
11404
11521
  var PLUGIN_PART = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
11405
11522
  function pluginCopies(claudeDir, marketplace, plugin) {
11406
11523
  if (!PLUGIN_PART.test(marketplace) || !PLUGIN_PART.test(plugin)) return null;
11407
- const pluginsDir = resolve11(claudeDir, "plugins");
11524
+ const pluginsDir = resolve12(claudeDir, "plugins");
11408
11525
  const dirs = installedPluginDirs(pluginsDir, `${plugin}@${marketplace}`);
11409
- const inside = (dir) => resolve11(dir).startsWith(`${pluginsDir}${sep10}`);
11526
+ const inside = (dir) => resolve12(dir).startsWith(`${pluginsDir}${sep10}`);
11410
11527
  return dirs?.marketplaceDir && inside(dirs.installPath) && inside(dirs.marketplaceDir) ? { installed: dirs.installPath, available: dirs.marketplaceDir } : null;
11411
11528
  }
11412
11529
 
@@ -11586,7 +11703,7 @@ async function readSkill(read, sourceId, name) {
11586
11703
  var RULES_FILE = "CLAUDE.md";
11587
11704
  async function readPlain(file, bound) {
11588
11705
  try {
11589
- if (!(await lstat6(file)).isFile()) return { refused: "unreadable" };
11706
+ if (!(await lstat7(file)).isFile()) return { refused: "unreadable" };
11590
11707
  const real = await realpath5(file);
11591
11708
  if (!within2(await realpath5(bound), real)) return { refused: "unreadable" };
11592
11709
  const handle = await open(real, "r");
@@ -11610,10 +11727,10 @@ async function runs(root2) {
11610
11727
  }
11611
11728
 
11612
11729
  // server/tasks/folder-trust.ts
11613
- import { lstat as lstat7, stat as stat6 } from "node:fs/promises";
11730
+ import { lstat as lstat8, stat as stat6 } from "node:fs/promises";
11614
11731
  async function inPlaceFolder(repo) {
11615
11732
  const path = localRepoPath(repo.url);
11616
- if (!path || !await lstat7(path).then((found) => found.isDirectory(), () => false)) return null;
11733
+ if (!path || !await lstat8(path).then((found) => found.isDirectory(), () => false)) return null;
11617
11734
  return await isGitFolder(path) ? null : path;
11618
11735
  }
11619
11736
  async function opensInPlace(repo) {
@@ -11795,13 +11912,13 @@ function serveEnv(base, password) {
11795
11912
  return { ...env2, OPENCODE_SERVER_PASSWORD: password, OPENCODE_PASSWORD: password, OPENCODE_DISABLE_PROJECT_CONFIG: "1", OPENCODE_DISABLE_AUTOUPDATE: "1" };
11796
11913
  }
11797
11914
  function freePort() {
11798
- return new Promise((resolve14, reject) => {
11915
+ return new Promise((resolve15, reject) => {
11799
11916
  const probe = createServer();
11800
11917
  probe.once("error", reject);
11801
11918
  probe.listen(0, "127.0.0.1", () => {
11802
11919
  const address = probe.address();
11803
11920
  const port = typeof address === "object" && address ? address.port : 0;
11804
- probe.close(() => port ? resolve14(port) : reject(new Error("no free port on 127.0.0.1")));
11921
+ probe.close(() => port ? resolve15(port) : reject(new Error("no free port on 127.0.0.1")));
11805
11922
  });
11806
11923
  });
11807
11924
  }
@@ -11810,9 +11927,9 @@ async function startOpencodeServe({ program, cwd, env: env2, spawn: spawn3 = def
11810
11927
  const password = randomBytes6(32).toString("base64url");
11811
11928
  const port = await freePort();
11812
11929
  const child = spawn3(program, ["serve", "--hostname=127.0.0.1", `--port=${port}`], { cwd, env: serveEnv(env2, password) });
11813
- const exit = new Promise((resolve14) => child.once("exit", (code) => resolve14(code)));
11930
+ const exit = new Promise((resolve15) => child.once("exit", (code) => resolve15(code)));
11814
11931
  const auth = `Basic ${Buffer.from(`opencode:${password}`).toString("base64")}`;
11815
- const url = await new Promise((resolve14, reject) => {
11932
+ const url = await new Promise((resolve15, reject) => {
11816
11933
  const timer = setTimeout(() => reject(new Error(`OpenCode did not say where it listens within ${LISTEN_TIMEOUT_MS / 1e3} seconds`)), LISTEN_TIMEOUT_MS);
11817
11934
  const lines = createInterface({ input: child.stdout });
11818
11935
  lines.on("line", (line) => {
@@ -11821,7 +11938,7 @@ async function startOpencodeServe({ program, cwd, env: env2, spawn: spawn3 = def
11821
11938
  clearTimeout(timer);
11822
11939
  lines.close();
11823
11940
  if (match2[1] !== `http://127.0.0.1:${port}`) reject(new Error("OpenCode listens somewhere other than the address it was given"));
11824
- else resolve14(match2[1]);
11941
+ else resolve15(match2[1]);
11825
11942
  });
11826
11943
  void exit.then((code) => {
11827
11944
  clearTimeout(timer);
@@ -11878,7 +11995,7 @@ function serveTransport(url, auth, request, stop, exit, silenceMs) {
11878
11995
  void exit.then(() => ended4.abort());
11879
11996
  let connect3 = () => {
11880
11997
  };
11881
- let calls = new Promise((resolve14) => connect3 = resolve14);
11998
+ let calls = new Promise((resolve15) => connect3 = resolve15);
11882
11999
  async function* events() {
11883
12000
  while (!ended4.signal.aborted) {
11884
12001
  const quiet = new AbortController();
@@ -11962,23 +12079,23 @@ function contextWindows(answer) {
11962
12079
  return windows;
11963
12080
  }
11964
12081
  async function runOpencodeAsYou({ program, cwd, env: env2, rules, timeoutMs, signal, onProcess, onSession, resume, off, readOnly, talk, spawn: spawn3 }) {
11965
- const session = await startOpencodeSession({ program, cwd, env: env2, permission: rules, ...resume ? { resume } : {}, ...off ? { off } : {}, ...readOnly ? { readOnly } : {}, ...spawn3 ? { spawn: spawn3 } : {} });
11966
- if (session.pgid !== null) onProcess(session.pgid);
11967
- onSession?.(session.sessionId);
12082
+ const session2 = await startOpencodeSession({ program, cwd, env: env2, permission: rules, ...resume ? { resume } : {}, ...off ? { off } : {}, ...readOnly ? { readOnly } : {}, ...spawn3 ? { spawn: spawn3 } : {} });
12083
+ if (session2.pgid !== null) onProcess(session2.pgid);
12084
+ onSession?.(session2.sessionId);
11968
12085
  let timedOut = false;
11969
12086
  const timer = setTimeout(() => {
11970
12087
  timedOut = true;
11971
- session.stop();
12088
+ session2.stop();
11972
12089
  }, timeoutMs);
11973
- const cancel = () => session.stop();
12090
+ const cancel = () => session2.stop();
11974
12091
  signal.addEventListener("abort", cancel, { once: true });
11975
12092
  if (signal.aborted) cancel();
11976
12093
  try {
11977
- return { events: await talk(session.transport, session.codec), timedOut };
12094
+ return { events: await talk(session2.transport, session2.codec), timedOut };
11978
12095
  } finally {
11979
12096
  clearTimeout(timer);
11980
12097
  signal.removeEventListener("abort", cancel);
11981
- session.stop();
12098
+ session2.stop();
11982
12099
  }
11983
12100
  }
11984
12101
 
@@ -12038,7 +12155,7 @@ function openSession(codec, transport, { steer = false } = {}) {
12038
12155
  else if (done) {
12039
12156
  if (broken) throw broken;
12040
12157
  return;
12041
- } else await new Promise((resolve14) => wake = resolve14);
12158
+ } else await new Promise((resolve15) => wake = resolve15);
12042
12159
  }
12043
12160
  }
12044
12161
  return {
@@ -12122,7 +12239,7 @@ function processTransport(inv, options) {
12122
12239
  for (; ; ) {
12123
12240
  if (read.length) yield read.shift();
12124
12241
  else if (ended4) return;
12125
- else await new Promise((resolve14) => wake = resolve14);
12242
+ else await new Promise((resolve15) => wake = resolve15);
12126
12243
  }
12127
12244
  }
12128
12245
  return {
@@ -12302,6 +12419,9 @@ function httpLink(profile, fetchImpl = fetch) {
12302
12419
  async finish(taskId, leaseId, outcome) {
12303
12420
  await call(RUNNER_PATHS.finish(taskId), { leaseId, outcome });
12304
12421
  },
12422
+ async lateChanges(taskId, changes) {
12423
+ await call(RUNNER_PATHS.lateChanges(taskId), { changes });
12424
+ },
12305
12425
  async status(agents, started) {
12306
12426
  await call(RUNNER_PATHS.status, { agents, features: [...MACHINE_FEATURES], ...started ? { started: true } : {} });
12307
12427
  },
@@ -12471,7 +12591,7 @@ var LOST_LEASE = "This machine lost the task's lease; the orchestrator holds it
12471
12591
  var STOPPED = "Stopped by the person who started the task.";
12472
12592
  var IDLE_CLOSED = "The agent waited half an hour for an answer, so its session was closed to free this machine; Continue brings it back where it left off.";
12473
12593
  var SHUT_DOWN = "The task stopped when its runner stopped; Continue picks it up again.";
12474
- var delay = (ms) => new Promise((resolve14) => setTimeout(resolve14, ms));
12594
+ var delay = (ms) => new Promise((resolve15) => setTimeout(resolve15, ms));
12475
12595
  function runLeasedTask(lease, link, executor, { mask, state, now = Date.now }) {
12476
12596
  const { task, leaseId } = lease;
12477
12597
  const stop = new AbortController();
@@ -12544,8 +12664,8 @@ function runLeasedTask(lease, link, executor, { mask, state, now = Date.now }) {
12544
12664
  },
12545
12665
  ...link.attachment ? { attachment: (id) => link.attachment(task.id, leaseId, id) } : {},
12546
12666
  async decide(request) {
12547
- const answered = new Promise((resolve14, reject) => {
12548
- answers.set(request.id, resolve14);
12667
+ const answered = new Promise((resolve15, reject) => {
12668
+ answers.set(request.id, resolve15);
12549
12669
  stop.signal.addEventListener("abort", () => reject(stop.signal.reason), { once: true });
12550
12670
  });
12551
12671
  while (!stop.signal.aborted) {
@@ -12608,9 +12728,9 @@ function runLeasedTask(lease, link, executor, { mask, state, now = Date.now }) {
12608
12728
  else if (command.type === "follow_up") {
12609
12729
  if (!followUps.some((f) => f.id === command.followUp.id)) followUps.push(command.followUp);
12610
12730
  } else {
12611
- const resolve14 = answers.get(command.requestId);
12731
+ const resolve15 = answers.get(command.requestId);
12612
12732
  answers.delete(command.requestId);
12613
- resolve14?.({ decision: command.decision, ...command.note === void 0 ? {} : { note: command.note }, ...command.answers ? { answers: command.answers } : {}, ...command.plan === void 0 ? {} : { plan: command.plan } });
12733
+ resolve15?.({ decision: command.decision, ...command.note === void 0 ? {} : { note: command.note }, ...command.answers ? { answers: command.answers } : {}, ...command.plan === void 0 ? {} : { plan: command.plan } });
12614
12734
  }
12615
12735
  },
12616
12736
  shutDown() {
@@ -12620,8 +12740,69 @@ function runLeasedTask(lease, link, executor, { mask, state, now = Date.now }) {
12620
12740
  };
12621
12741
  }
12622
12742
 
12743
+ // server/work/gate.ts
12744
+ var TEAMS_KEY = "work.boards.teams";
12745
+ var PROJECTS_KEY = "work.boards.projects";
12746
+ async function readMap(ctx, key) {
12747
+ const raw = await ctx.store.getSetting(ctx.tenant, key);
12748
+ try {
12749
+ return raw ? JSON.parse(raw) : {};
12750
+ } catch {
12751
+ return {};
12752
+ }
12753
+ }
12754
+ var boardTeams = (ctx) => readMap(ctx, TEAMS_KEY);
12755
+ var boardProjects = (ctx) => readMap(ctx, PROJECTS_KEY);
12756
+ function issueProject(issue) {
12757
+ if (!issue.key) return null;
12758
+ if (issue.kind === "jira" || issue.kind === "linear") return issue.key.slice(0, issue.key.lastIndexOf("-"));
12759
+ return issue.key.slice(0, issue.key.lastIndexOf("#"));
12760
+ }
12761
+ async function trackerReadsFor(ctx, user, issue) {
12762
+ if (manages(user)) return true;
12763
+ const teams = await boardTeams(ctx);
12764
+ const project = issueProject(issue);
12765
+ if (!project) return false;
12766
+ const projects = await boardProjects(ctx);
12767
+ return Object.entries(teams).some(([id, team]) => seesTeamTasks(user, team) && projects[id] === project);
12768
+ }
12769
+
12770
+ // server/work/own-github.ts
12771
+ async function githubOrigins(ctx) {
12772
+ const repos = /* @__PURE__ */ new Map();
12773
+ for (const repo of await ctx.store.listRepos(ctx.tenant)) {
12774
+ const path = localRepoPath(repo.url);
12775
+ const origin = path ? (await projectFacts(path, { dataDir: ctx.dataDir }).catch(() => null))?.origin : null;
12776
+ if (origin?.forge !== "github") continue;
12777
+ const name = new URL(origin.web).pathname.slice(1);
12778
+ if (/^[A-Za-z0-9-]{1,39}\/[A-Za-z0-9._-]{1,100}$/.test(name)) repos.set(name, origin.web);
12779
+ }
12780
+ return [...repos].map(([name, url]) => ({ name, url })).sort((a, b) => a.name.localeCompare(b.name));
12781
+ }
12782
+
12783
+ // server/work/provider.ts
12784
+ var READ_TIMEOUT_MS = 1e4;
12785
+ function trackerRefusal(res, what) {
12786
+ if (res.status === 401 || res.status === 403) return `the tracker refused the token (${res.status}); check the token and its permissions under Integrations`;
12787
+ if (res.status === 404) return what === "board" ? "the tracker has no such board; it was removed, or the token cannot see it" : `${NO_SUCH_ISSUE}; it was deleted, or the token cannot see it`;
12788
+ if (res.status === 429) {
12789
+ const seconds = Number(res.headers.get("retry-after"));
12790
+ return `the tracker is limiting requests; try again ${Number.isFinite(seconds) && seconds > 0 ? `in ${Math.ceil(seconds)} seconds` : "in a minute"}`;
12791
+ }
12792
+ return null;
12793
+ }
12794
+ var NO_SUCH_ISSUE = "the tracker has no such issue";
12795
+ var NOT_REACHED = "the tracker was not reached; check the connection and try again";
12796
+
12797
+ // server/work/linear.ts
12798
+ function linearEndpoint(workspace) {
12799
+ const url = new URL(workspace);
12800
+ return url.hostname === "linear.app" ? "https://api.linear.app/graphql" : `${url.origin}/graphql`;
12801
+ }
12802
+
12623
12803
  // server/integrations/tracker.ts
12624
12804
  var TRACKER = "tracker";
12805
+ var TRACKER_TOKEN_SECRET = "integration.tracker.token";
12625
12806
  var JIRA_KEY = /^[A-Z][A-Z0-9]+-\d+$/;
12626
12807
  var PROJECT_KEY = /^((?:[A-Za-z0-9_.-]+\/)+[A-Za-z0-9_.-]+)#(\d+)$/;
12627
12808
  function issueAddress(given2, tracker) {
@@ -12646,9 +12827,123 @@ async function readTracker(ctx) {
12646
12827
  return (await readEnabled(ctx, TRACKER))?.config ?? null;
12647
12828
  }
12648
12829
 
12830
+ // server/integrations/mcp-client.ts
12831
+ var CALL_TIMEOUT_MS = 1e4;
12832
+ var PROTOCOL = "2025-06-18";
12833
+ var McpCallFailed = class extends Error {
12834
+ };
12835
+ async function answerOf(res, id) {
12836
+ const type = res.headers.get("content-type") ?? "";
12837
+ const text = await res.text();
12838
+ const messages = type.includes("text/event-stream") ? text.split(/\r?\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trim()).filter(Boolean) : [text];
12839
+ for (const raw of messages) {
12840
+ let message;
12841
+ try {
12842
+ message = JSON.parse(raw);
12843
+ } catch {
12844
+ continue;
12845
+ }
12846
+ if (message.id !== id) continue;
12847
+ if (message.error) throw new McpCallFailed(`the server answered with an error: ${String(message.error.message ?? "").slice(0, 200)}`);
12848
+ return message.result ?? {};
12849
+ }
12850
+ throw new McpCallFailed("the server's answer carried no reply to the call");
12851
+ }
12852
+ async function session(url, headers, send) {
12853
+ let id = null;
12854
+ let next = 1;
12855
+ const post = async (body) => {
12856
+ let res;
12857
+ try {
12858
+ res = await send(url, {
12859
+ method: "POST",
12860
+ headers: { "content-type": "application/json", accept: "application/json, text/event-stream", "mcp-protocol-version": PROTOCOL, ...id ? { "mcp-session-id": id } : {}, ...headers },
12861
+ body: JSON.stringify({ jsonrpc: "2.0", ...body }),
12862
+ redirect: "error",
12863
+ signal: AbortSignal.timeout(CALL_TIMEOUT_MS)
12864
+ });
12865
+ } catch (err) {
12866
+ throw new McpCallFailed(err.name === "TimeoutError" ? `the server did not answer within ${CALL_TIMEOUT_MS / 1e3} seconds` : "the server was not reached");
12867
+ }
12868
+ if (res.status === 401 || res.status === 403) throw new McpCallFailed(`the server refused the sign-in (${res.status}); connect it again`);
12869
+ if (!res.ok) throw new McpCallFailed(`the server answered ${res.status}`);
12870
+ return res;
12871
+ };
12872
+ const call = async (method, params) => {
12873
+ const n = next++;
12874
+ const res = await post({ id: n, method, params });
12875
+ id = res.headers.get("mcp-session-id") ?? id;
12876
+ return answerOf(res, n);
12877
+ };
12878
+ await call("initialize", { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: "teamhandbook-orchestrator", version: "1.0.0" } });
12879
+ await (await post({ method: "notifications/initialized" })).body?.cancel();
12880
+ return call;
12881
+ }
12882
+ async function readWithTools(url, headers, calls, send = fetch) {
12883
+ const call = await session(url, headers, send);
12884
+ const answers = [];
12885
+ for (let step2 = calls(answers); step2; step2 = calls(answers)) {
12886
+ const result = await call("tools/call", step2);
12887
+ if (result.isError) throw new McpCallFailed(`the server answered ${step2.name} with an error`);
12888
+ answers.push((result.content ?? []).filter((c) => c.type === "text").map((c) => c.text ?? "").join("\n"));
12889
+ }
12890
+ return answers;
12891
+ }
12892
+
12649
12893
  // server/integrations/mcp-oauth.ts
12650
12894
  import { createHash as createHash8, randomBytes as randomBytes7, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
12895
+ var OAUTH_TIMEOUT_MS = 1e4;
12651
12896
  var PENDING_MS = 10 * 6e4;
12897
+ var REFRESH_AHEAD_MS = 6e4;
12898
+ var OAuthFailed = class extends Error {
12899
+ /** The server's own OAuth error code, such as invalid_client, when it gave one. */
12900
+ constructor(message, code = null) {
12901
+ super(message);
12902
+ this.code = code;
12903
+ }
12904
+ };
12905
+ async function postForm2(url, form, send) {
12906
+ let res;
12907
+ try {
12908
+ res = await send(url, {
12909
+ method: "POST",
12910
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
12911
+ body: new URLSearchParams(form).toString(),
12912
+ redirect: "error",
12913
+ signal: AbortSignal.timeout(OAUTH_TIMEOUT_MS)
12914
+ });
12915
+ } catch {
12916
+ throw new OAuthFailed("the server's sign-in did not answer");
12917
+ }
12918
+ const body = await res.json().catch(() => ({}));
12919
+ if (!res.ok) throw new OAuthFailed(`the server's sign-in refused (${res.status}${typeof body.error === "string" ? `: ${body.error.slice(0, 60)}` : ""})`, typeof body.error === "string" ? body.error : null);
12920
+ return body;
12921
+ }
12922
+ function tokensOf2(body, previous, now) {
12923
+ if (typeof body.access_token !== "string" || !body.access_token) throw new OAuthFailed("the server's sign-in returned no access token");
12924
+ const seconds = Number(body.expires_in);
12925
+ return {
12926
+ accessToken: body.access_token,
12927
+ refreshToken: typeof body.refresh_token === "string" ? body.refresh_token : previous.refreshToken,
12928
+ expiresAt: Number.isFinite(seconds) && seconds > 0 ? new Date(now.getTime() + seconds * 1e3).toISOString() : null,
12929
+ tokenEndpoint: previous.tokenEndpoint,
12930
+ clientId: previous.clientId,
12931
+ clientSecret: previous.clientSecret,
12932
+ resource: previous.resource
12933
+ };
12934
+ }
12935
+ var clientAuth = (t) => ({ client_id: t.clientId, ...t.clientSecret ? { client_secret: t.clientSecret } : {} });
12936
+ async function freshTokens(tokens, send = fetch, now = /* @__PURE__ */ new Date()) {
12937
+ if (!tokens.expiresAt || Date.parse(tokens.expiresAt) - now.getTime() > REFRESH_AHEAD_MS) return tokens;
12938
+ if (!tokens.refreshToken) return null;
12939
+ try {
12940
+ const body = await postForm2(tokens.tokenEndpoint, { grant_type: "refresh_token", refresh_token: tokens.refreshToken, resource: tokens.resource, ...clientAuth(tokens) }, send);
12941
+ return tokensOf2(body, tokens, now);
12942
+ } catch (err) {
12943
+ if (err instanceof OAuthFailed) return null;
12944
+ throw err;
12945
+ }
12946
+ }
12652
12947
  var PendingSignIns = class {
12653
12948
  pending = /* @__PURE__ */ new Map();
12654
12949
  add(entry, now = Date.now()) {
@@ -12674,9 +12969,262 @@ var PendingSignIns = class {
12674
12969
  var READ_TOOLS = ["getAccessibleAtlassianResources", "getVisibleJiraProjects", "searchJiraIssuesUsingJql"];
12675
12970
 
12676
12971
  // server/integrations/personal-mcp.ts
12972
+ var listKey = (userId) => `mcp.personal.${userId}`;
12973
+ var secretName = (userId, server2, kind) => `mcp.personal.${userId}.${server2}.${kind}`;
12974
+ async function personalServers(ctx, userId) {
12975
+ const raw = await ctx.store.getSetting(ctx.tenant, listKey(userId));
12976
+ try {
12977
+ return raw ? JSON.parse(raw) : [];
12978
+ } catch {
12979
+ return [];
12980
+ }
12981
+ }
12982
+ async function readSealedTokens(ctx, name) {
12983
+ const sealed = await readSecret(ctx.store, ctx.vault ?? null, ctx.tenant, name);
12984
+ return sealed ? JSON.parse(sealed) : null;
12985
+ }
12986
+ async function sealedAccess(ctx, name, send = fetch) {
12987
+ const tokens = await readSealedTokens(ctx, name);
12988
+ if (!tokens) return null;
12989
+ const fresh = await freshTokens(tokens, send);
12990
+ if (!fresh) return null;
12991
+ if (fresh !== tokens) await storeSecret(ctx.store, ctx.vault ?? null, ctx.tenant, name, JSON.stringify(fresh), "orchestrator");
12992
+ return fresh.accessToken;
12993
+ }
12994
+ async function credentialFor(ctx, userId, server2, send = fetch) {
12995
+ if (server2.auth === "none") return void 0;
12996
+ if (server2.auth === "token") return readSecret(ctx.store, ctx.vault ?? null, ctx.tenant, secretName(userId, server2.name, "token"));
12997
+ return sealedAccess(ctx, secretName(userId, server2.name, "oauth"), send);
12998
+ }
12677
12999
  var PENDING_SIGN_INS = new PendingSignIns();
12678
13000
  var ATLASSIAN_READS = [...READ_TOOLS, "getJiraIssue"];
12679
13001
 
13002
+ // server/integrations/issue-read.ts
13003
+ var COMMENTS_READ = 5;
13004
+ var MAX_ISSUE_CHARS = 3e4;
13005
+ var MAX_PART_CHARS = 15e3;
13006
+ var MAX_COMMENT_CHARS = 2e3;
13007
+ var MAX_SUBTASKS = 50;
13008
+ function cut2(text, max) {
13009
+ return text.length > max ? `${text.slice(0, max)}
13010
+ [cut at ${max} characters]` : text;
13011
+ }
13012
+ function adfText(node) {
13013
+ if (typeof node === "string") return node;
13014
+ if (!node || typeof node !== "object") return "";
13015
+ const n = node;
13016
+ const inner = (n.content ?? []).map(adfText).join("");
13017
+ switch (n.type) {
13018
+ case "text":
13019
+ return n.text ?? "";
13020
+ case "hardBreak":
13021
+ return "\n";
13022
+ case "mention":
13023
+ case "emoji":
13024
+ return n.attrs?.text ?? "";
13025
+ case "listItem":
13026
+ return `- ${inner.trim()}
13027
+ `;
13028
+ case "paragraph":
13029
+ case "heading":
13030
+ case "codeBlock":
13031
+ case "blockquote":
13032
+ case "rule":
13033
+ return `${inner}
13034
+ `;
13035
+ default:
13036
+ return inner;
13037
+ }
13038
+ }
13039
+ var ReadFailed = class extends Error {
13040
+ };
13041
+ function issueGone(read, key) {
13042
+ return read && "problem" in read && read.problem.startsWith(NO_SUCH_ISSUE) ? `${key ?? "The issue"} was deleted, or this token cannot see it any more. Ask about another issue.` : null;
13043
+ }
13044
+ async function getJson(url, headers, send, body) {
13045
+ let res;
13046
+ try {
13047
+ const post = body === void 0 ? {} : { method: "POST", body: JSON.stringify(body) };
13048
+ res = await send(url, { ...post, headers: { accept: "application/json", ...body === void 0 ? {} : { "content-type": "application/json" }, ...headers }, redirect: "error", signal: AbortSignal.timeout(READ_TIMEOUT_MS) });
13049
+ } catch (err) {
13050
+ throw new ReadFailed(err.name === "TimeoutError" ? `the tracker did not answer within ${READ_TIMEOUT_MS / 1e3} seconds; try again` : NOT_REACHED);
13051
+ }
13052
+ const refused = trackerRefusal(res, "issue");
13053
+ if (refused) throw new ReadFailed(refused);
13054
+ if (!res.ok) throw new ReadFailed(`the tracker answered ${res.status}`);
13055
+ try {
13056
+ return await res.json();
13057
+ } catch {
13058
+ throw new ReadFailed("the tracker's answer is not JSON");
13059
+ }
13060
+ }
13061
+ async function readJira(tracker, key, token2, send) {
13062
+ const auth = { authorization: `Basic ${Buffer.from(`${tracker.email}:${token2}`).toString("base64")}` };
13063
+ const issue = await getJson(`${tracker.url}/rest/api/3/issue/${encodeURIComponent(key)}?expand=names`, auth, send);
13064
+ const comments = await getJson(`${tracker.url}/rest/api/3/issue/${encodeURIComponent(key)}/comment?orderBy=-created&maxResults=${COMMENTS_READ}`, auth, send);
13065
+ return jiraLines(key, issue.fields ?? {}, issue.names ?? {}, (comments.comments ?? []).slice(0, COMMENTS_READ));
13066
+ }
13067
+ function jiraLines(key, fields, names2, listed) {
13068
+ const name = (field) => field?.name ?? "";
13069
+ const criteria = Object.entries(names2).filter(([id, label]) => /acceptance/i.test(label) && fields[id] !== null && fields[id] !== void 0).map(([id]) => adfText(fields[id]).trim()).filter(Boolean);
13070
+ const subtasks = (fields.subtasks ?? []).slice(0, MAX_SUBTASKS);
13071
+ const lines = [
13072
+ `${key}: ${String(fields.summary ?? "")}`,
13073
+ `Status: ${name(fields.status)}${name(fields.issuetype) ? ` \xB7 Type: ${name(fields.issuetype)}` : ""}`,
13074
+ "",
13075
+ "Description:",
13076
+ cut2(adfText(fields.description).trim() || "(none)", MAX_PART_CHARS)
13077
+ ];
13078
+ if (criteria.length) lines.push("", "Acceptance criteria:", cut2(criteria.join("\n"), MAX_PART_CHARS));
13079
+ if (subtasks.length) lines.push("", "Sub-tasks:", ...subtasks.map((s) => `- ${s.key ?? ""} ${String(s.fields?.summary ?? "")} (${name(s.fields?.status)})`));
13080
+ if (listed.length) {
13081
+ lines.push("", "Latest comments, newest first:");
13082
+ for (const c of listed) lines.push(`- ${c.author?.displayName ?? "someone"}, ${String(c.created ?? "").slice(0, 10)}:`, cut2(adfText(c.body).trim(), MAX_COMMENT_CHARS));
13083
+ }
13084
+ return { lines, summary: `${criteria.length ? "acceptance criteria, " : ""}${subtasks.length} sub-task(s), ${listed.length} comment(s)`, title: String(fields.summary ?? ""), status: name(fields.status) };
13085
+ }
13086
+ async function readGitLab(tracker, key, token2, send) {
13087
+ const match2 = /^(.+)#(\d+)$/.exec(key);
13088
+ if (!match2) throw new ReadFailed("the issue's key is not group/project#number");
13089
+ const base = `${tracker.url}/api/v4/projects/${encodeURIComponent(match2[1])}/issues/${match2[2]}`;
13090
+ const auth = { "private-token": token2 };
13091
+ const issue = await getJson(base, auth, send);
13092
+ const notes = await getJson(`${base}/notes?sort=desc&order_by=created_at&per_page=20`, auth, send);
13093
+ const listed = (Array.isArray(notes) ? notes : []).filter((n) => !n.system).slice(0, COMMENTS_READ);
13094
+ const labels = Array.isArray(issue.labels) ? issue.labels : [];
13095
+ const lines = [
13096
+ `${key}: ${String(issue.title ?? "")}`,
13097
+ `State: ${String(issue.state ?? "")}${labels.length ? ` \xB7 Labels: ${labels.join(", ")}` : ""}`,
13098
+ "",
13099
+ "Description:",
13100
+ cut2(String(issue.description ?? "").trim() || "(none)", MAX_PART_CHARS)
13101
+ ];
13102
+ if (listed.length) {
13103
+ lines.push("", "Latest comments, newest first:");
13104
+ for (const n of listed) lines.push(`- ${n.author?.name ?? "someone"}, ${String(n.created_at ?? "").slice(0, 10)}:`, cut2(String(n.body ?? "").trim(), MAX_COMMENT_CHARS));
13105
+ }
13106
+ return { lines, summary: `${listed.length} comment(s)`, title: String(issue.title ?? ""), status: String(issue.state ?? "") };
13107
+ }
13108
+ var LINEAR_ISSUE = "query ($id: String!) { issue(id: $id) { identifier title description priority priorityLabel state { name } labels { nodes { name } } children(first: 50) { nodes { identifier title state { name } } } comments(first: 50) { nodes { body createdAt user { name } } } } }";
13109
+ async function readLinear(tracker, key, token2, send) {
13110
+ const answer = await getJson(linearEndpoint(tracker.url), { authorization: token2 }, send, { query: LINEAR_ISSUE, variables: { id: key } });
13111
+ const errors = answer.errors;
13112
+ if (errors?.length) throw new ReadFailed(`Linear refused the read: ${errors[0]?.message ?? "no reason given"}`);
13113
+ const issue = answer.data?.issue;
13114
+ if (!issue) throw new ReadFailed("the tracker has no such issue, or the token cannot see it");
13115
+ const labels = (issue.labels?.nodes ?? []).map((l) => l.name ?? "").filter(Boolean);
13116
+ const children = (issue.children?.nodes ?? []).slice(0, MAX_SUBTASKS);
13117
+ const listed = [...issue.comments?.nodes ?? []].sort((a, b) => String(b.createdAt ?? "").localeCompare(String(a.createdAt ?? ""))).slice(0, COMMENTS_READ);
13118
+ const status2 = issue.state?.name ?? "";
13119
+ const lines = [
13120
+ `${key}: ${String(issue.title ?? "")}`,
13121
+ `State: ${status2}${issue.priority ? ` \xB7 Priority: ${issue.priorityLabel ?? ""}` : ""}${labels.length ? ` \xB7 Labels: ${labels.join(", ")}` : ""}`,
13122
+ "",
13123
+ "Description:",
13124
+ cut2(String(issue.description ?? "").trim() || "(none)", MAX_PART_CHARS)
13125
+ ];
13126
+ if (children.length) lines.push("", "Sub-issues:", ...children.map((c) => `- ${c.identifier ?? ""} ${String(c.title ?? "")} (${c.state?.name ?? ""})`));
13127
+ if (listed.length) {
13128
+ lines.push("", "Latest comments, newest first:");
13129
+ for (const c of listed) lines.push(`- ${c.user?.name ?? "someone"}, ${String(c.createdAt ?? "").slice(0, 10)}:`, cut2(String(c.body ?? "").trim(), MAX_COMMENT_CHARS));
13130
+ }
13131
+ return { lines, summary: `${children.length} sub-issue(s), ${listed.length} comment(s)`, title: String(issue.title ?? ""), status: status2 };
13132
+ }
13133
+ async function readOwnGitHub(ctx, issue, run2) {
13134
+ const match2 = issue.key ? /^(.+)#(\d+)$/.exec(issue.key) : null;
13135
+ if (!match2 || new URL(issue.url).host !== "github.com" || !(await githubOrigins(ctx)).some((r) => r.name === match2[1])) return null;
13136
+ const gh = ownCliReader("github", "github.com", run2);
13137
+ const path = `repos/${match2[1]}/issues/${match2[2]}`;
13138
+ try {
13139
+ const found = await gh.request("GET", path);
13140
+ const comments = await gh.request("GET", `${path}/comments?per_page=100`);
13141
+ const listed = (Array.isArray(comments) ? comments : []).slice(-COMMENTS_READ).reverse();
13142
+ const labels = (found.labels ?? []).map((l) => typeof l === "string" ? l : l.name ?? "").filter(Boolean);
13143
+ const lines = [
13144
+ `${issue.key}: ${String(found.title ?? "")}`,
13145
+ `State: ${String(found.state ?? "")}${labels.length ? ` \xB7 Labels: ${labels.join(", ")}` : ""}`,
13146
+ "",
13147
+ "Description:",
13148
+ cut2(String(found.body ?? "").trim() || "(none)", MAX_PART_CHARS)
13149
+ ];
13150
+ if (listed.length) {
13151
+ lines.push("", "Latest comments, newest first:");
13152
+ for (const c of listed) lines.push(`- ${c.user?.login ?? "someone"}, ${String(c.created_at ?? "").slice(0, 10)}:`, cut2(String(c.body ?? "").trim(), MAX_COMMENT_CHARS));
13153
+ }
13154
+ const redactor = new Redactor();
13155
+ const text = cut2(lines.join("\n").split("\n").map((l) => redactor.line(l)).join("\n"), MAX_ISSUE_CHARS);
13156
+ return { text, summary: `${listed.length} comment(s)`, title: redactor.line(String(found.title ?? "")), status: redactor.line(String(found.state ?? "")) };
13157
+ } catch (err) {
13158
+ return { problem: err.message };
13159
+ }
13160
+ }
13161
+ var TOKEN_READS = ["jira", "gitlab", "linear"];
13162
+ function offTracker(tracker, issue) {
13163
+ if (issue.kind !== tracker.kind || new URL(issue.url).origin !== new URL(tracker.url).origin) return `the issue is not on the connected tracker (${new URL(tracker.url).host})`;
13164
+ if (issue.kind === "linear" && !new URL(issue.url).pathname.startsWith(`${new URL(tracker.url).pathname.replace(/\/$/, "")}/`)) {
13165
+ return `the issue is not in the connected Linear workspace (${new URL(tracker.url).pathname.slice(1)})`;
13166
+ }
13167
+ return null;
13168
+ }
13169
+ async function readIssue(ctx, issue, forUser, send = fetch, run2 = runOwnCli) {
13170
+ if (issue.kind === "github" && ctx.dataDir && await ownCliHere(ctx)) return readOwnGitHub({ ...ctx, dataDir: ctx.dataDir }, issue, run2);
13171
+ const read = await readWithToken(ctx, issue, forUser, send);
13172
+ if (read && "text" in read) return read;
13173
+ if (issue.kind === "jira") return await readJiraAsPerson(ctx, issue, forUser, send) ?? read;
13174
+ return read;
13175
+ }
13176
+ async function readJiraAsPerson(ctx, issue, forUser, send) {
13177
+ const server2 = (await personalServers(ctx, forUser.id)).find((s) => s.transport === "http" && s.url && s.tools.includes("getJiraIssue"));
13178
+ const key = issue.key;
13179
+ if (!server2 || !key) return null;
13180
+ const credential = await credentialFor(ctx, forUser.id, server2, send).catch(() => null);
13181
+ if (credential === null) return { problem: `${server2.name} is not signed in` };
13182
+ const origin = new URL(issue.url).origin;
13183
+ try {
13184
+ const [, answer] = await readWithTools(server2.url, credential ? { authorization: `Bearer ${credential}` } : {}, (previous) => {
13185
+ if (previous.length === 0) return { name: "getAccessibleAtlassianResources", arguments: {} };
13186
+ if (previous.length === 1) {
13187
+ const sites = JSON.parse(previous[0]);
13188
+ const site = sites.find((s) => typeof s.url === "string" && new URL(s.url).origin === origin);
13189
+ return site?.id ? { name: "getJiraIssue", arguments: { cloudId: site.id, issueIdOrKey: key, fields: ["summary", "status", "issuetype", "description", "subtasks", "comment"] } } : null;
13190
+ }
13191
+ return null;
13192
+ }, send);
13193
+ if (!answer) return { problem: `${server2.name} reaches no Jira site at ${new URL(issue.url).host}` };
13194
+ const fields = JSON.parse(answer).fields ?? {};
13195
+ const listed = (fields.comment?.comments ?? []).slice(-COMMENTS_READ).reverse();
13196
+ const read = jiraLines(key, fields, {}, listed);
13197
+ const redactor = new Redactor(credential ? [credential] : []);
13198
+ const text = cut2(read.lines.join("\n").split("\n").map((l) => redactor.line(l)).join("\n"), MAX_ISSUE_CHARS);
13199
+ return { text, summary: read.summary, title: redactor.line(read.title), status: redactor.line(read.status) };
13200
+ } catch (err) {
13201
+ return { problem: maskSecrets(`${server2.name} did not read it: ${err.message}`, credential ? [credential] : []) };
13202
+ }
13203
+ }
13204
+ async function readWithToken(ctx, issue, forUser, send) {
13205
+ const tracker = (await readEnabled(ctx, TRACKER))?.config;
13206
+ if (!tracker || !issue.key || !TOKEN_READS.includes(tracker.kind)) return null;
13207
+ let token2;
13208
+ try {
13209
+ token2 = await readSecret(ctx.store, ctx.vault ?? null, ctx.tenant, TRACKER_TOKEN_SECRET);
13210
+ } catch (err) {
13211
+ return { problem: err.message };
13212
+ }
13213
+ if (!token2) return null;
13214
+ const off = offTracker(tracker, issue);
13215
+ if (off) return { problem: off };
13216
+ if (!await trackerReadsFor(ctx, forUser, issue)) return { problem: "the issue's project is not on a board shown to this person" };
13217
+ try {
13218
+ const read = tracker.kind === "jira" ? await readJira(tracker, issue.key, token2, send) : tracker.kind === "linear" ? await readLinear(tracker, issue.key, token2, send) : await readGitLab(tracker, issue.key, token2, send);
13219
+ const redactor = new Redactor([token2]);
13220
+ const text = cut2(read.lines.join("\n").split("\n").map((l) => redactor.line(l)).join("\n"), MAX_ISSUE_CHARS);
13221
+ return { text, summary: read.summary, title: redactor.line(read.title), status: redactor.line(read.status) };
13222
+ } catch (err) {
13223
+ if (err instanceof ReadFailed) return { problem: maskSecrets(err.message, [token2]) };
13224
+ throw err;
13225
+ }
13226
+ }
13227
+
12680
13228
  // server/tasks/issue.ts
12681
13229
  var MAX_ISSUE_URL = 500;
12682
13230
  var JIRA = /^\/browse\/([A-Z][A-Z0-9]+-\d+)\/?$/;
@@ -12916,12 +13464,12 @@ function machineAsks(now = Date.now) {
12916
13464
  if (!mine.waiting.size && now() - mine.lastAt > ONLINE_MS) return Promise.resolve("offline");
12917
13465
  if ([...pending.values()].filter((p) => p.machineId === machineId).length >= ASKS_PER_MACHINE) return Promise.resolve("busy");
12918
13466
  const nonce = randomBytes8(18).toString("base64url");
12919
- return new Promise((resolve14) => {
13467
+ return new Promise((resolve15) => {
12920
13468
  const timer = setTimeout(() => settle(null), kind === "undos" ? UNDO_ASK_WAIT_MS : kind === "lessons" ? LESSON_ASK_WAIT_MS : kind === "checks" ? CHECKS_ASK_WAIT_MS : kind === "lessonOps" ? LESSON_OP_WAIT_MS : kind === "pushes" ? PUSH_ASK_WAIT_MS : kind === "setups" ? SETUP_ASK_WAIT_MS : FOLDER_ASK_WAIT_MS);
12921
13469
  const settle = (answer) => {
12922
13470
  clearTimeout(timer);
12923
13471
  pending.delete(nonce);
12924
- resolve14(answer);
13472
+ resolve15(answer);
12925
13473
  };
12926
13474
  pending.set(nonce, { kind, ask: { nonce, ...fields }, machineId, handed: false, settle });
12927
13475
  for (const waiting of mine.waiting) waiting.abort();
@@ -13017,7 +13565,7 @@ async function namingFor(code, mirror, sha) {
13017
13565
  var REPORT_BYTES = 1024 * 1024;
13018
13566
 
13019
13567
  // server/tasks/routes.ts
13020
- import { isAbsolute as isAbsolute10, join as join35, resolve as resolve13 } from "node:path";
13568
+ import { isAbsolute as isAbsolute10, join as join35, resolve as resolve14 } from "node:path";
13021
13569
 
13022
13570
  // server/tasks/verify-routes.ts
13023
13571
  import { join as join33 } from "node:path";
@@ -13117,7 +13665,7 @@ async function repoBranches(ctx, repo) {
13117
13665
  }
13118
13666
 
13119
13667
  // server/work-folders.ts
13120
- import { basename as basename12, dirname as dirname16, isAbsolute as isAbsolute9, join as join34, relative as relative7, resolve as resolve12, sep as sep12 } from "node:path";
13668
+ import { basename as basename12, dirname as dirname16, isAbsolute as isAbsolute9, join as join34, relative as relative7, resolve as resolve13, sep as sep12 } from "node:path";
13121
13669
  import { fileURLToPath } from "node:url";
13122
13670
  var OWN_CODE = dirname16(dirname16(fileURLToPath(import.meta.url)));
13123
13671
 
@@ -13205,6 +13753,8 @@ async function startTask(ctx, runner, user, body, parent, seedFrom) {
13205
13753
  if (body?.readOnly !== void 0 && typeof body.readOnly !== "boolean") return { error: "readOnly is true or false", status: 400 };
13206
13754
  const readOnly = body?.readOnly === true;
13207
13755
  if (readOnly && (template || targets)) return { error: "a question reads one repository or folder, from no template", status: 400 };
13756
+ const gone = readOnly && issue ? issueGone(await readIssue(ctx, issue, user), issue.key) : null;
13757
+ if (gone) return { error: gone, status: 409 };
13208
13758
  const baseBranch = typeof body?.baseBranch === "string" && body.baseBranch.trim() ? body.baseBranch.trim() : void 0;
13209
13759
  if (body?.baseBranch !== void 0 && body.baseBranch !== null && typeof body.baseBranch !== "string") return { error: "baseBranch is a branch's name", status: 400 };
13210
13760
  const branches = baseBranch ? await repoBranches(ctx, repo) : null;
@@ -13306,6 +13856,45 @@ async function startTask(ctx, runner, user, body, parent, seedFrom) {
13306
13856
  }
13307
13857
  var TASK_LIMIT_MINUTES_MAX = 24 * 60;
13308
13858
 
13859
+ // server/short-memory.ts
13860
+ function shortMemory(ttlMs, now = Date.now, staleMs = 0) {
13861
+ const kept2 = /* @__PURE__ */ new Map();
13862
+ const store = (key, load) => {
13863
+ const entry = { at: now(), value: load() };
13864
+ kept2.set(key, entry);
13865
+ entry.value.catch(() => {
13866
+ if (kept2.get(key) === entry) kept2.delete(key);
13867
+ });
13868
+ return entry;
13869
+ };
13870
+ return {
13871
+ read(key, load) {
13872
+ const held = kept2.get(key);
13873
+ const age = held ? now() - held.at : Infinity;
13874
+ if (held && age < ttlMs) return held.value;
13875
+ if (held && age < ttlMs + staleMs) {
13876
+ if (!held.reloading) {
13877
+ held.reloading = true;
13878
+ load().then(
13879
+ (value) => {
13880
+ if (kept2.get(key) === held) kept2.set(key, { at: now(), value: Promise.resolve(value) });
13881
+ },
13882
+ () => {
13883
+ held.reloading = false;
13884
+ }
13885
+ );
13886
+ }
13887
+ return held.value;
13888
+ }
13889
+ return store(key, load).value;
13890
+ },
13891
+ forget() {
13892
+ kept2.clear();
13893
+ }
13894
+ };
13895
+ }
13896
+ var handbookReads = shortMemory(6e4, Date.now, 10 * 6e4);
13897
+
13309
13898
  // server/lessons.ts
13310
13899
  var LOOK_BACK_MS = 14 * 864e5;
13311
13900
  var NOBODY = hostIdentityOf([]);
@@ -13354,7 +13943,7 @@ var MAX_BODY_BYTES = 64 * 1024;
13354
13943
  var HOURS_BACK = 31 * 24;
13355
13944
 
13356
13945
  // server/work/cache.ts
13357
- var WORK_TTL_MS = 6e4;
13946
+ var WORK_TTL_MS = 12e4;
13358
13947
  var FRESH_EVERY_MS = 15e3;
13359
13948
  var MAX_ENTRIES2 = 500;
13360
13949
  var WorkCache = class {
@@ -13362,6 +13951,7 @@ var WorkCache = class {
13362
13951
  this.now = now;
13363
13952
  }
13364
13953
  entries = /* @__PURE__ */ new Map();
13954
+ opening = /* @__PURE__ */ new Map();
13365
13955
  async read(key, load, fresh = false) {
13366
13956
  const entry = this.entries.get(key);
13367
13957
  const age = entry ? this.now() - entry.at : Infinity;
@@ -13370,12 +13960,18 @@ var WorkCache = class {
13370
13960
  this.reload(key, entry, load);
13371
13961
  return this.answer(entry, true);
13372
13962
  }
13373
- const value = await load();
13374
- const stored = { at: this.now(), value };
13375
- this.entries.delete(key);
13376
- this.entries.set(key, stored);
13377
- if (this.entries.size > MAX_ENTRIES2) this.entries.delete(this.entries.keys().next().value);
13378
- return this.answer(stored, false);
13963
+ let opening = this.opening.get(key);
13964
+ if (!opening) {
13965
+ opening = load().then((value) => {
13966
+ const stored = { at: this.now(), value };
13967
+ this.entries.delete(key);
13968
+ this.entries.set(key, stored);
13969
+ if (this.entries.size > MAX_ENTRIES2) this.entries.delete(this.entries.keys().next().value);
13970
+ return stored;
13971
+ }).finally(() => this.opening.delete(key));
13972
+ this.opening.set(key, opening);
13973
+ }
13974
+ return this.answer(await opening, false);
13379
13975
  }
13380
13976
  /** Drops every answer whose key starts with `prefix`, such as one tenant's tracker. */
13381
13977
  evict(prefix) {
@@ -13405,27 +14001,6 @@ var MAX_FILE_BYTES4 = 256 * 1024;
13405
14001
  // server/work/routes.ts
13406
14002
  var WORK_CACHE = new WorkCache();
13407
14003
 
13408
- // server/short-memory.ts
13409
- function shortMemory(ttlMs, now = Date.now) {
13410
- const kept2 = /* @__PURE__ */ new Map();
13411
- return {
13412
- read(key, load) {
13413
- const held = kept2.get(key);
13414
- if (held && now() - held.at < ttlMs) return held.value;
13415
- const value = load();
13416
- kept2.set(key, { at: now(), value });
13417
- value.catch(() => {
13418
- if (kept2.get(key)?.value === value) kept2.delete(key);
13419
- });
13420
- return value;
13421
- },
13422
- forget() {
13423
- kept2.clear();
13424
- }
13425
- };
13426
- }
13427
- var handbookReads = shortMemory(6e4);
13428
-
13429
14004
  // server/mcp/tools.ts
13430
14005
  var ToolRefused = class extends Error {
13431
14006
  };
@@ -13616,7 +14191,7 @@ var SIGN_IN_MS = 15 * 6e4;
13616
14191
 
13617
14192
  // server/tasks/handbook-files.ts
13618
14193
  import { createHash as createHash9, randomBytes as randomBytes9 } from "node:crypto";
13619
- import { lstat as lstat8, mkdir as mkdir5, open as open2, realpath as realpath6, rename, rm as rm6, writeFile as writeFile5 } from "node:fs/promises";
14194
+ import { lstat as lstat9, mkdir as mkdir5, open as open2, realpath as realpath6, rename, rm as rm6, writeFile as writeFile5 } from "node:fs/promises";
13620
14195
  import { dirname as dirname17, isAbsolute as isAbsolute11, join as join36, relative as relative8 } from "node:path";
13621
14196
  var SKILL_NAME2 = /^[a-z0-9][a-z0-9-]{0,63}$/;
13622
14197
  var COMMAND_NAME = /^[a-z0-9][a-z0-9:-]{0,63}$/;
@@ -13634,7 +14209,7 @@ function filePath(root2, kind, name) {
13634
14209
  async function readOwnFile(root2, kind, name) {
13635
14210
  const path = filePath(root2, kind, name);
13636
14211
  if (!path) return { refused: "bad-name" };
13637
- const found = await lstat8(path).catch(() => null);
14212
+ const found = await lstat9(path).catch(() => null);
13638
14213
  if (!found) return null;
13639
14214
  if (!found.isFile()) return { refused: "outside" };
13640
14215
  const realRoot = await realpath6(root2).catch(() => root2);
@@ -13665,7 +14240,7 @@ async function writeOwnFile(root2, kind, name, content, expected) {
13665
14240
  if (expected !== null && (!now || now.digest !== expected)) return { refused: now ? "changed" : "missing" };
13666
14241
  const realRoot = await realpath6(root2);
13667
14242
  let existing = dirname17(path);
13668
- while (!await lstat8(existing).then(() => true, () => false)) existing = dirname17(existing);
14243
+ while (!await lstat9(existing).then(() => true, () => false)) existing = dirname17(existing);
13669
14244
  if (!within3(realRoot, await realpath6(existing))) return { refused: "outside" };
13670
14245
  const problem = kind === "skill" ? skillProblem(name, content) : null;
13671
14246
  if (problem) return { refused: "bad-format", detail: problem };
@@ -13743,10 +14318,10 @@ function version(text) {
13743
14318
  var compare = (a, b) => a.map((n, i) => n - b[i]).find((d) => d !== 0) ?? 0;
13744
14319
 
13745
14320
  // runner/agent-status.ts
13746
- var runCli = (program, args) => new Promise((resolve14) => {
14321
+ var runCli = (program, args) => new Promise((resolve15) => {
13747
14322
  execFile5(program, [...args], { timeout: PROBE_TIMEOUT_MS, maxBuffer: 1024 * 1024, env: process.env }, (error, stdout) => {
13748
14323
  const code = error ? typeof error.code === "number" ? error.code : null : 0;
13749
- resolve14({ code, stdout: String(stdout ?? "") });
14324
+ resolve15({ code, stdout: String(stdout ?? "") });
13750
14325
  });
13751
14326
  });
13752
14327
  async function agentStatus(adapters, run2 = runCli) {
@@ -13934,13 +14509,13 @@ function gitEnvOf(hostEnv, extra) {
13934
14509
  return { ...kept2, GIT_TERMINAL_PROMPT: "0", GIT_ALLOW_PROTOCOL: "https:ssh", ...extra };
13935
14510
  }
13936
14511
  function gitCaller(env2, gitConfig2) {
13937
- return (cwd, args, options = {}) => new Promise((resolve14, reject) => {
14512
+ return (cwd, args, options = {}) => new Promise((resolve15, reject) => {
13938
14513
  execFile6("git", [...SAFE_GIT, ...gitConfig2, ...options.before ?? [], ...args], { cwd, env: { ...env2, ...options.extraEnv }, maxBuffer: 16 * 1024 * 1024, ...options.signal ? { signal: options.signal } : {} }, (error, stdout, stderr) => {
13939
14514
  if (error) {
13940
14515
  const said3 = String(stderr || error.message).trim().split("\n").map((line) => line.trim());
13941
14516
  const reason = said3.find((line) => line.startsWith("! [")) ?? said3.find((line) => /^(fatal|error):/.test(line)) ?? said3.pop() ?? "";
13942
14517
  reject(new Error(`git ${args[0] === "-C" ? args[2] : args[0]} failed: ${new Redactor().line(reason.replace(/\s+/g, " "))}`));
13943
- } else resolve14(String(stdout));
14518
+ } else resolve15(String(stdout));
13944
14519
  });
13945
14520
  });
13946
14521
  }
@@ -13969,6 +14544,7 @@ function machineExecutor({ dataDir, org, machineId, working = /* @__PURE__ */ ne
13969
14544
  } catch (error) {
13970
14545
  outcome = error instanceof Ended ? { ...ended3(error.status, error.message), ...error.kept } : ended3("failed", error instanceof Error ? error.message : String(error));
13971
14546
  }
14547
+ if (abortedAway(hooks)) outcome = { ...outcome, status: "interrupted", error: hooks.signal.reason.message };
13972
14548
  if (outcome.status !== "interrupted") {
13973
14549
  await releasePersonalGuard(root2);
13974
14550
  await rm8(root2, { recursive: true, force: true });
@@ -14090,6 +14666,7 @@ function machineExecutor({ dataDir, org, machineId, working = /* @__PURE__ */ ne
14090
14666
  } catch (error) {
14091
14667
  outcome = error instanceof Ended ? { ...ended3(error.status, error.message), ...error.kept } : ended3("failed", error instanceof Error ? error.message : String(error));
14092
14668
  }
14669
+ if (abortedAway(hooks)) outcome = { ...outcome, status: "interrupted", error: hooks.signal.reason.message };
14093
14670
  if (outcome.status !== "interrupted") {
14094
14671
  await releasePersonalGuard(root2);
14095
14672
  await rm8(root2, { recursive: true, force: true });
@@ -14328,10 +14905,10 @@ After a repair round: ${again.summary.trim()}`;
14328
14905
  }, onSpawn: (pgid) => hooks.onProcess(pgid, paths.root) }
14329
14906
  );
14330
14907
  hooks.log(`Starting ${adapter.label} with your own sign-in.`);
14331
- const session = openSession(launched ? launched.codec : adapter.decoder(paths.work), transport, { steer: false });
14332
- if (launched) session.sendTurn(prompt);
14333
- else session.close();
14334
- const result = await converse(session, hooks, work.limits.timeoutMs, stop, ownMcpTool(work.setup.mcpTools), ready2.masked, launched !== null, { turnText: (followUp) => turnText(followUp, ready2, hooks), sourced: ready2.sourced, off: ready2.setup.off ?? null });
14908
+ const session2 = openSession(launched ? launched.codec : adapter.decoder(paths.work), transport, { steer: false });
14909
+ if (launched) session2.sendTurn(prompt);
14910
+ else session2.close();
14911
+ const result = await converse(session2, hooks, work.limits.timeoutMs, stop, ownMcpTool(work.setup.mcpTools), ready2.masked, launched !== null, { turnText: (followUp) => turnText(followUp, ready2, hooks), sourced: ready2.sourced, off: ready2.setup.off ?? null });
14335
14912
  stopped(hooks);
14336
14913
  if (result.despite.length) throw new Ended("failed", stoppedDespite(result.despite));
14337
14914
  if (result.timedOut) throw new Ended("failed", `The agent ran past the task's ${Math.round(work.limits.timeoutMs / 6e4)} minutes and was stopped.`);
@@ -14369,9 +14946,9 @@ After a repair round: ${again.summary.trim()}`;
14369
14946
  },
14370
14947
  ...resume ? { resume } : {},
14371
14948
  talk: async (transport, codec) => {
14372
- const session = openSession(codec, transport, { steer: false });
14373
- session.sendTurn(prompt);
14374
- result = await converse(session, hooks, work.limits.timeoutMs, stop, ownMcpTool(work.setup.mcpTools), ready2.masked, true, { turnText: (followUp) => turnText(followUp, ready2, hooks), sourced: ready2.sourced, off: ready2.setup.off ?? null });
14949
+ const session2 = openSession(codec, transport, { steer: false });
14950
+ session2.sendTurn(prompt);
14951
+ result = await converse(session2, hooks, work.limits.timeoutMs, stop, ownMcpTool(work.setup.mcpTools), ready2.masked, true, { turnText: (followUp) => turnText(followUp, ready2, hooks), sourced: ready2.sourced, off: ready2.setup.off ?? null });
14375
14952
  return [];
14376
14953
  }
14377
14954
  }).catch((error) => {
@@ -14491,6 +15068,9 @@ function untilReset(work, failure2, nativeSessionId) {
14491
15068
  if (failure2?.class !== "usage_limit" || !failure2.resetAt || !nativeSessionId || "folder" in work) return null;
14492
15069
  return new Ended("interrupted", failure2.message, { nativeSessionId, limitResetAt: failure2.resetAt });
14493
15070
  }
15071
+ function abortedAway(hooks) {
15072
+ return hooks.signal.aborted && hooks.signal.reason instanceof Error && !stoppedByPerson(hooks);
15073
+ }
14494
15074
  function stoppedByPerson(hooks) {
14495
15075
  return hooks.signal.aborted && hooks.signal.reason instanceof Error && hooks.signal.reason.message === STOPPED;
14496
15076
  }
@@ -14522,7 +15102,7 @@ function testOutput(hooks, values, kept2) {
14522
15102
  }
14523
15103
  };
14524
15104
  }
14525
- async function converse(session, hooks, timeoutMs, stop, own, values, talks, { turnText = async (followUp) => followUpText(followUp), sourced = async (event) => event, off = null } = {}) {
15105
+ async function converse(session2, hooks, timeoutMs, stop, own, values, talks, { turnText = async (followUp) => followUpText(followUp), sourced = async (event) => event, off = null } = {}) {
14526
15106
  const redactor = new Redactor(values);
14527
15107
  const mask = (text) => redactor.line(text);
14528
15108
  let left = timeoutMs;
@@ -14536,7 +15116,7 @@ async function converse(session, hooks, timeoutMs, stop, own, values, talks, { t
14536
15116
  since = Date.now();
14537
15117
  timer = setTimeout(() => {
14538
15118
  timedOut = true;
14539
- session.stop();
15119
+ session2.stop();
14540
15120
  }, left);
14541
15121
  };
14542
15122
  const pause = () => {
@@ -14549,21 +15129,21 @@ async function converse(session, hooks, timeoutMs, stop, own, values, talks, { t
14549
15129
  if (--waiting === 0 && !timedOut) run2();
14550
15130
  };
14551
15131
  const closeIfDone = () => {
14552
- if (turnDone && background === 0) session.close();
15132
+ if (turnDone && background === 0) session2.close();
14553
15133
  };
14554
15134
  run2();
14555
- stop.signal.addEventListener("abort", () => session.stop(), { once: true });
15135
+ stop.signal.addEventListener("abort", () => session2.stop(), { once: true });
14556
15136
  let terminal = null;
14557
15137
  let despite = [];
14558
15138
  const answers = [];
14559
15139
  try {
14560
- for await (const event of session.events) {
15140
+ for await (const event of session2.events) {
14561
15141
  const kept2 = keepOwnToolsHere(event, own);
14562
15142
  const masked = kept2 && maskEvent(kept2, mask);
14563
15143
  if (event.type === "loaded" && off) {
14564
15144
  despite = loadedDespiteOff(off, event);
14565
15145
  if (despite.length) {
14566
- session.stop();
15146
+ session2.stop();
14567
15147
  break;
14568
15148
  }
14569
15149
  }
@@ -14574,9 +15154,9 @@ async function converse(session, hooks, timeoutMs, stop, own, values, talks, { t
14574
15154
  hooks.decide(own(event.request.tool) ? ownRequest2(event.request) : event.request).then(
14575
15155
  ({ decision, note, answers: given2, plan: plan2 }) => {
14576
15156
  resume();
14577
- if (given2) session.reply(event.request.id, given2);
14578
- else if (plan2 !== void 0 && decision !== "deny") session.approvePlan(event.request.id, plan2);
14579
- else session.respond(event.request.id, decision, note);
15157
+ if (given2) session2.reply(event.request.id, given2);
15158
+ else if (plan2 !== void 0 && decision !== "deny") session2.approvePlan(event.request.id, plan2);
15159
+ else session2.respond(event.request.id, decision, note);
14580
15160
  },
14581
15161
  () => resume()
14582
15162
  )
@@ -14590,7 +15170,7 @@ async function converse(session, hooks, timeoutMs, stop, own, values, talks, { t
14590
15170
  if (event.type === "turn_finished") {
14591
15171
  const [next] = talks ? hooks.followUps?.() ?? [] : [];
14592
15172
  if (next) {
14593
- session.sendTurn(await turnText(next));
15173
+ session2.sendTurn(await turnText(next));
14594
15174
  hooks.delivered?.([next.id]);
14595
15175
  hooks.log("Sent a follow-up to the agent.");
14596
15176
  hooks.onEvent({ type: "steer", text: next.text, by: next.createdBy });
@@ -14693,7 +15273,7 @@ async function setupHere(ask, where, hostEnv, program) {
14693
15273
  if ((ask.want === "skill" || ask.want === "file") && !FILE_NAME.test(ask.name)) return { refused: "that is not a name this runner takes" };
14694
15274
  if (ask.want === "plugin" && !NAME5.test(ask.plugin.slice("plugin:".length))) return { refused: "that is not a name this runner takes" };
14695
15275
  const home = await realpath9(where.home).catch(() => where.home);
14696
- const folder = ask.want === "plugin" ? null : ask.folder;
15276
+ const folder = ask.want === "plugin" || ask.want === "marketplaces" ? null : ask.folder;
14697
15277
  const place = folder ? await folderPlace(folder.path, folder.projectId, where) : null;
14698
15278
  if (place && "refused" in place) return place;
14699
15279
  const root2 = await mkdtemp2(join43(tmpdir4(), "handbook-setup-"));
@@ -14707,6 +15287,7 @@ async function setupHere(ask, where, hostEnv, program) {
14707
15287
  const personal = await probePersonalSetup(program, env2, root2, place ? [place.folder] : [], READ_TIMEOUT_MS2).catch(() => null);
14708
15288
  return readSources({ claudeDir: hostEnv.CLAUDE_CONFIG_DIR || join43(home, ".claude"), ...place && folder ? { folder: place.folder, folderTrusted: folder.trusted } : {}, plugins, personal });
14709
15289
  };
15290
+ if (ask.want === "marketplaces") return runPluginOp(program, env2, root2, "check", "", "user");
14710
15291
  if (ask.want === "sources") {
14711
15292
  const { sources } = await read();
14712
15293
  return { sources: sources.map((source2) => ({ ...source2, id: source2.id.startsWith(`folder:${home}${sep14}`) ? `folder:~/${source2.id.slice(`folder:${home}${sep14}`.length)}` : source2.id })) };
@@ -14742,21 +15323,40 @@ function startRunnerLoop(link, executor, options) {
14742
15323
  }, now = Date.now, listFolders: listFolders2, undoInFolder: undoInFolder2, queueLesson, readChecks, lessonOp, pushBranch: pushBranch2, setupHere: setupHere2, slots = () => 1, onRefused = () => {
14743
15324
  } } = options;
14744
15325
  const running = /* @__PURE__ */ new Map();
15326
+ const late = /* @__PURE__ */ new Map();
14745
15327
  const halt = new AbortController();
15328
+ const deliverLate = async () => {
15329
+ for (const [taskId, changes] of late) {
15330
+ try {
15331
+ await link.lateChanges(taskId, changes);
15332
+ late.delete(taskId);
15333
+ } catch (error) {
15334
+ if (error instanceof LeaseGone || error instanceof NotTaken) late.delete(taskId);
15335
+ else throw error;
15336
+ }
15337
+ }
15338
+ };
14746
15339
  let wakeSleep = null;
14747
- const sleep = (ms) => new Promise((resolve14) => {
14748
- const timer = setTimeout(resolve14, ms);
15340
+ let full = null;
15341
+ const sleep = (ms) => new Promise((resolve15) => {
15342
+ const timer = setTimeout(resolve15, ms);
14749
15343
  wakeSleep = () => {
14750
15344
  clearTimeout(timer);
14751
- resolve14();
15345
+ resolve15();
14752
15346
  };
14753
15347
  });
14754
15348
  const stopped2 = (async () => {
14755
15349
  let failures = 0;
14756
15350
  let stableSince = null;
14757
15351
  while (!halt.signal.aborted) {
15352
+ const turn = new AbortController();
15353
+ const endTurn = () => turn.abort();
15354
+ halt.signal.addEventListener("abort", endTurn, { once: true });
15355
+ const canTake = running.size < slots();
15356
+ full = canTake ? null : turn;
14758
15357
  try {
14759
- const { lease, commands, folders = [], undos = [], lessons = [], checks = [], lessonOps = [], pushes = [], setups = [] } = await link.poll(POLL_WAIT_MS, running.size < slots(), halt.signal);
15358
+ await deliverLate();
15359
+ const { lease, commands, folders = [], undos = [], lessons = [], checks = [], lessonOps = [], pushes = [], setups = [] } = await link.poll(POLL_WAIT_MS, canTake && late.size === 0, turn.signal);
14760
15360
  if (stableSince === null) stableSince = now();
14761
15361
  if (now() - stableSince >= STABLE_MS) failures = 0;
14762
15362
  for (const command of commands) running.get(command.taskId)?.command(command);
@@ -14777,12 +15377,16 @@ function startRunnerLoop(link, executor, options) {
14777
15377
  if (lease && !running.has(lease.task.id) && !halt.signal.aborted) {
14778
15378
  const task = runLeasedTask(lease, link, executor, options);
14779
15379
  running.set(lease.task.id, task);
14780
- void task.done.finally(() => {
15380
+ void task.done.then(({ outcome, reported }) => {
15381
+ if (!reported && outcome.changes && link.lateChanges) late.set(lease.task.id, outcome.changes);
15382
+ }).finally(() => {
14781
15383
  if (running.get(lease.task.id) === task) running.delete(lease.task.id);
15384
+ full?.abort();
14782
15385
  });
14783
15386
  }
14784
15387
  } catch (error) {
14785
15388
  if (halt.signal.aborted) break;
15389
+ if (turn.signal.aborted) continue;
14786
15390
  if (error instanceof MachineRefused || error instanceof ProtocolMismatch) {
14787
15391
  onRefused(error);
14788
15392
  for (const task of running.values()) task.shutDown();
@@ -14793,6 +15397,9 @@ function startRunnerLoop(link, executor, options) {
14793
15397
  const wait = backoffMs(failures, random);
14794
15398
  onPollFailed(error, wait);
14795
15399
  await sleep(wait);
15400
+ } finally {
15401
+ halt.signal.removeEventListener("abort", endTurn);
15402
+ if (full === turn) full = null;
14796
15403
  }
14797
15404
  }
14798
15405
  await Promise.all([...running.values()].map((task) => task.done));
@@ -15004,7 +15611,7 @@ async function runOrgs(orgs, io, tasks = DEFAULT_SLOTS) {
15004
15611
  }
15005
15612
  io.out(`Running the tasks you start in ${orgs.join(", ")} on this machine; Ctrl-C stops.
15006
15613
  `);
15007
- await Promise.race([new Promise((resolve14) => io.signal?.aborted ? resolve14() : io.signal?.addEventListener("abort", () => resolve14(), { once: true })), Promise.all(runners.map((r) => r.stopped))]);
15614
+ await Promise.race([new Promise((resolve15) => io.signal?.aborted ? resolve15() : io.signal?.addEventListener("abort", () => resolve15(), { once: true })), Promise.all(runners.map((r) => r.stopped))]);
15008
15615
  await Promise.all(runners.map((r) => r.stop()));
15009
15616
  held.forEach((r) => r());
15010
15617
  if (refused.length === orgs.length) return NOT_CONNECTED_EXIT;