wildcrane-runner 0.6.121 → 0.6.123

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/dist/plugin.mjs CHANGED
@@ -1,4 +1,4 @@
1
- // wildcrane-runner 0.6.121 — built by runner/scripts/build.mjs. Do not edit.
1
+ // wildcrane-runner 0.6.123 — built by runner/scripts/build.mjs. Do not edit.
2
2
  import { createRequire as __ai4kanbanRequire } from 'node:module'
3
3
  const require = __ai4kanbanRequire(import.meta.url)
4
4
  var __create = Object.create;
@@ -22405,7 +22405,7 @@ var require_registries = __commonJS({
22405
22405
  var _a5;
22406
22406
  Object.defineProperty(exports, "__esModule", { value: true });
22407
22407
  exports.globalRegistry = exports.$ZodRegistry = exports.$input = exports.$output = void 0;
22408
- exports.registry = registry4;
22408
+ exports.registry = registry3;
22409
22409
  exports.$output = /* @__PURE__ */ Symbol("ZodOutput");
22410
22410
  exports.$input = /* @__PURE__ */ Symbol("ZodInput");
22411
22411
  var $ZodRegistry3 = class {
@@ -22449,10 +22449,10 @@ var require_registries = __commonJS({
22449
22449
  }
22450
22450
  };
22451
22451
  exports.$ZodRegistry = $ZodRegistry3;
22452
- function registry4() {
22452
+ function registry3() {
22453
22453
  return new $ZodRegistry3();
22454
22454
  }
22455
- (_a5 = globalThis).__zod_globalRegistry ?? (_a5.__zod_globalRegistry = registry4());
22455
+ (_a5 = globalThis).__zod_globalRegistry ?? (_a5.__zod_globalRegistry = registry3());
22456
22456
  exports.globalRegistry = globalThis.__zod_globalRegistry;
22457
22457
  (function() {
22458
22458
  var keys = Object.getOwnPropertyNames(exports);
@@ -26737,21 +26737,21 @@ var require_json_schema_processors = __commonJS({
26737
26737
  };
26738
26738
  function toJSONSchema3(input2, params) {
26739
26739
  if ("_idmap" in input2) {
26740
- const registry4 = input2;
26740
+ const registry3 = input2;
26741
26741
  const ctx2 = (0, to_json_schema_js_1.initializeContext)({ ...params, processors: exports.allProcessors });
26742
26742
  const defs = {};
26743
- for (const entry of registry4._idmap.entries()) {
26743
+ for (const entry of registry3._idmap.entries()) {
26744
26744
  const [_, schema] = entry;
26745
26745
  (0, to_json_schema_js_1.processSchema)(schema, ctx2);
26746
26746
  }
26747
26747
  const schemas = {};
26748
26748
  const external = {
26749
- registry: registry4,
26749
+ registry: registry3,
26750
26750
  uri: params?.uri,
26751
26751
  defs
26752
26752
  };
26753
26753
  ctx2.external = external;
26754
- for (const entry of registry4._idmap.entries()) {
26754
+ for (const entry of registry3._idmap.entries()) {
26755
26755
  const [key, schema] = entry;
26756
26756
  (0, to_json_schema_js_1.extractDefs)(ctx2, schema);
26757
26757
  (0, util_js_1.assignProp)(schemas, key, (0, to_json_schema_js_1.finalize)(ctx2, schema));
@@ -88256,21 +88256,21 @@ var allProcessors = {
88256
88256
  };
88257
88257
  function toJSONSchema(input2, params) {
88258
88258
  if ("_idmap" in input2) {
88259
- const registry4 = input2;
88259
+ const registry3 = input2;
88260
88260
  const ctx2 = initializeContext({ ...params, processors: allProcessors });
88261
88261
  const defs = {};
88262
- for (const entry of registry4._idmap.entries()) {
88262
+ for (const entry of registry3._idmap.entries()) {
88263
88263
  const [_, schema] = entry;
88264
88264
  processSchema(schema, ctx2);
88265
88265
  }
88266
88266
  const schemas = {};
88267
88267
  const external = {
88268
- registry: registry4,
88268
+ registry: registry3,
88269
88269
  uri: params?.uri,
88270
88270
  defs
88271
88271
  };
88272
88272
  ctx2.external = external;
88273
- for (const entry of registry4._idmap.entries()) {
88273
+ for (const entry of registry3._idmap.entries()) {
88274
88274
  const [key, schema] = entry;
88275
88275
  extractDefs(ctx2, schema);
88276
88276
  assignProp(schemas, key, finalize(ctx2, schema));
@@ -91263,6 +91263,10 @@ var reviewNodeSchema = external_exports.object({
91263
91263
  previews: external_exports.array(id).max(50).default([]),
91264
91264
  kind: external_exports.literal("work").optional()
91265
91265
  }).strict();
91266
+ var flatReviewPlanSchema = external_exports.object({
91267
+ rule: external_exports.string().trim().max(2e4),
91268
+ previews: external_exports.array(id).max(50).transform((ids) => [...new Set(ids)])
91269
+ }).strict();
91266
91270
  function reviewLayers(plan) {
91267
91271
  const remaining = new Set(plan.map((n) => n.id));
91268
91272
  if (remaining.size !== plan.length) throw new Error("Review node IDs must be unique.");
@@ -91283,13 +91287,14 @@ function reviewLayers(plan) {
91283
91287
  }
91284
91288
  return layers;
91285
91289
  }
91286
- var reviewPlanSchema = external_exports.array(reviewNodeSchema).max(50).superRefine((nodes, ctx) => {
91290
+ var legacyReviewPlanSchema = external_exports.array(reviewNodeSchema).max(50).superRefine((nodes, ctx) => {
91287
91291
  try {
91288
91292
  reviewLayers(nodes);
91289
91293
  } catch (e) {
91290
91294
  ctx.addIssue({ code: "custom", message: e.message });
91291
91295
  }
91292
- }).nullable();
91296
+ });
91297
+ var reviewPlanSchema = external_exports.union([flatReviewPlanSchema, legacyReviewPlanSchema]).nullable();
91293
91298
 
91294
91299
  // src/plugin.ts
91295
91300
  import crypto11 from "node:crypto";
@@ -100748,21 +100753,21 @@ var allProcessors2 = {
100748
100753
  };
100749
100754
  function toJSONSchema2(input2, params) {
100750
100755
  if ("_idmap" in input2) {
100751
- const registry4 = input2;
100756
+ const registry3 = input2;
100752
100757
  const ctx2 = initializeContext2({ ...params, processors: allProcessors2 });
100753
100758
  const defs = {};
100754
- for (const entry of registry4._idmap.entries()) {
100759
+ for (const entry of registry3._idmap.entries()) {
100755
100760
  const [_, schema] = entry;
100756
100761
  processSchema2(schema, ctx2);
100757
100762
  }
100758
100763
  const schemas = {};
100759
100764
  const external = {
100760
- registry: registry4,
100765
+ registry: registry3,
100761
100766
  uri: params?.uri,
100762
100767
  defs
100763
100768
  };
100764
100769
  ctx2.external = external;
100765
- for (const entry of registry4._idmap.entries()) {
100770
+ for (const entry of registry3._idmap.entries()) {
100766
100771
  const [key, schema] = entry;
100767
100772
  extractDefs2(ctx2, schema);
100768
100773
  assignProp2(schemas, key, finalize2(ctx2, schema));
@@ -107820,16 +107825,6 @@ function alive(pid) {
107820
107825
  }
107821
107826
  var sleep = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
107822
107827
 
107823
- // ../cli/src/lib/agent/cloud-studios.ts
107824
- import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
107825
- import fs8 from "node:fs";
107826
- import path10 from "node:path";
107827
-
107828
- // ../cli/src/lib/lock.ts
107829
- import { randomUUID } from "node:crypto";
107830
- import fs3 from "node:fs";
107831
- import path5 from "node:path";
107832
-
107833
107828
  // ../cli/src/lib/paths.ts
107834
107829
  import path4 from "node:path";
107835
107830
 
@@ -107903,7 +107898,7 @@ function rootAbove(board) {
107903
107898
  var NESTED_STATE = /(^|[/\\])\.akb[/\\](?:(?:boards|hidden-boards)[/\\])?\.akb(?=[/\\]|$)/;
107904
107899
  var InvalidBoardStatePath = class extends BoardError {
107905
107900
  constructor(file3, state2, id2) {
107906
- const use = state2 ? `Use ${state2}${id2 ? ` or an .assets/${id2}/\u2026 reference` : ""}.` : "Use the board\u2019s project-local state directory.";
107901
+ const use = state2 ? `Use ${state2}${id2 ? ` or an asset:<path> reference` : ""}.` : "Use the board\u2019s project-local state directory.";
107907
107902
  super(`Invalid nested board state path: ${file3}. ${use}`, { kind: "board-state-path" });
107908
107903
  }
107909
107904
  };
@@ -108033,7 +108028,15 @@ function setBoardRoot(root2, named = false) {
108033
108028
  }
108034
108029
  setBoardRoot(process.cwd());
108035
108030
 
108031
+ // ../cli/src/lib/agent/cloud-studios.ts
108032
+ import { createHash as createHash2, randomUUID as randomUUID2 } from "node:crypto";
108033
+ import fs8 from "node:fs";
108034
+ import path10 from "node:path";
108035
+
108036
108036
  // ../cli/src/lib/lock.ts
108037
+ import { randomUUID } from "node:crypto";
108038
+ import fs3 from "node:fs";
108039
+ import path5 from "node:path";
108037
108040
  function pidAlive(pid) {
108038
108041
  if (!pid) return false;
108039
108042
  try {
@@ -108200,10 +108203,8 @@ function landSections(body, previews) {
108200
108203
  const start = heading.index;
108201
108204
  const end = start + heading[0].length;
108202
108205
  if (!/^ {0,3}##[ \t]+Land(?:[ \t]+#+)?[ \t]*$/.test(visible.slice(start, end))) return [];
108203
- return [{
108204
- offset: start + heading[0].indexOf("#"),
108205
- empty: !visible.slice(end, headings[index + 1]?.index).replace(comments, "").trim()
108206
- }];
108206
+ const text3 = visible.slice(end, headings[index + 1]?.index).replace(comments, "").trim();
108207
+ return [{ offset: start + heading[0].indexOf("#"), empty: !text3, text: text3 }];
108207
108208
  });
108208
108209
  }
108209
108210
  function parseStudioFile(id2, source, from, { requirePreviewCopy = false, requireLand = false } = {}) {
@@ -108780,10 +108781,44 @@ import fs19 from "node:fs";
108780
108781
  import path23 from "node:path";
108781
108782
  import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url";
108782
108783
 
108784
+ // ../cli/src/lib/agent/proxy.ts
108785
+ import { execFileSync } from "node:child_process";
108786
+ var PROXY_KEYS = ["HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"];
108787
+ function withSystemProxy(env2 = process.env, platform = process.platform, read3 = () => execFileSync("/usr/sbin/scutil", ["--proxy"], { encoding: "utf8", timeout: 1e3, stdio: ["ignore", "pipe", "ignore"] })) {
108788
+ const out = { ...env2 };
108789
+ if (platform !== "darwin" || PROXY_KEYS.some((key) => env2[key] !== void 0)) return out;
108790
+ let raw;
108791
+ try {
108792
+ raw = read3();
108793
+ } catch {
108794
+ return out;
108795
+ }
108796
+ const value = (key) => new RegExp(`^\\s*${key}\\s*:\\s*(.*?)\\s*$`, "m").exec(raw)?.[1];
108797
+ for (const [name, key, scheme] of [["HTTP", "HTTP_PROXY", "http"], ["HTTPS", "HTTPS_PROXY", "http"], ["SOCKS", "ALL_PROXY", "socks5"]]) {
108798
+ if (value(`${name}Enable`) !== "1") continue;
108799
+ const host2 = value(`${name}Proxy`);
108800
+ const port = Number(value(`${name}Port`));
108801
+ if (!host2 || /[\s/@?#]/.test(host2) || !Number.isInteger(port) || port < 1 || port > 65535) continue;
108802
+ try {
108803
+ out[key] = new URL(`${scheme}://${host2.includes(":") && !host2.startsWith("[") ? `[${host2}]` : host2}:${port}`).href.replace(/\/$/, "");
108804
+ } catch {
108805
+ }
108806
+ }
108807
+ if (PROXY_KEYS.some((key) => out[key]) && env2.NO_PROXY === void 0 && env2.no_proxy === void 0) {
108808
+ const exceptions = /ExceptionsList\s*:\s*<array>\s*\{([^}]+)\}/.exec(raw)?.[1];
108809
+ const bypass = exceptions?.split("\n").flatMap((line) => {
108810
+ const host2 = /^\s*\d+\s*:\s*(\S+)\s*$/.exec(line)?.[1];
108811
+ return host2 ? [host2.startsWith("*.") ? host2.slice(1) : host2] : [];
108812
+ });
108813
+ if (bypass?.length) out.NO_PROXY = bypass.join(",");
108814
+ }
108815
+ return out;
108816
+ }
108817
+
108783
108818
  // ../cli/src/lib/agent/harnesses/antigravity.ts
108784
108819
  import fs15 from "node:fs";
108785
108820
  import path17 from "node:path";
108786
- import { createHash as createHash5 } from "node:crypto";
108821
+ import { createHash as createHash6 } from "node:crypto";
108787
108822
  import { spawnSync as spawnSync2 } from "node:child_process";
108788
108823
 
108789
108824
  // ../cli/src/lib/agent/locate.ts
@@ -109453,7 +109488,22 @@ ${files.map((file3) => `- ${file3}`).join("\n")}` : "";
109453
109488
  import fs14 from "node:fs";
109454
109489
 
109455
109490
  // ../cli/src/lib/agent/wire/events.ts
109491
+ import { createHash as createHash5 } from "node:crypto";
109456
109492
  var TOOL_KINDS = ["read", "edit", "delete", "move", "search", "execute", "fetch", "other"];
109493
+ var isPollingTool = (title) => /^(?:.*\.)?(?:command_status|wait(?:_5_seconds|_agent)?|TaskOutput)$/i.test(title);
109494
+ var toolOutput = (text3) => text3.split(/\r?\n/).map((line) => line.trim()).filter(
109495
+ (line) => line && !/^(?:\[?heartbeat\]?(?:\b|\s|$)|(?:status:\s*)?(?:(?:command|task) (?:is )?(?:still )?running|running|in[_ ]progress|pending)[.!]?$)/i.test(line)
109496
+ ).join("\n");
109497
+ function progressSnapshots() {
109498
+ const seen = /* @__PURE__ */ new Set();
109499
+ return (key, text3) => {
109500
+ if (!text3) return false;
109501
+ const digest = createHash5("sha256").update(key).update("\0").update(text3).digest("base64");
109502
+ if (seen.has(digest)) return false;
109503
+ seen.add(digest);
109504
+ return true;
109505
+ };
109506
+ }
109457
109507
  var toolKind = (v) => TOOL_KINDS.includes(str2(v)) ? v : "other";
109458
109508
  function targetOf(raw) {
109459
109509
  const line = raw.split("\n")[0].trim();
@@ -109491,6 +109541,8 @@ function createEventCollector() {
109491
109541
  let queue = [];
109492
109542
  let said = "";
109493
109543
  let activity = 0;
109544
+ const fresh = progressSnapshots();
109545
+ const polls = /* @__PURE__ */ new Map();
109494
109546
  const todoCalls = /* @__PURE__ */ new Set();
109495
109547
  const held2 = /* @__PURE__ */ new Map();
109496
109548
  let todos = [];
@@ -109509,6 +109561,9 @@ function createEventCollector() {
109509
109561
  progress: () => {
109510
109562
  activity++;
109511
109563
  },
109564
+ progressSnapshot(key, text3) {
109565
+ if (fresh(key, toolOutput(text3))) activity++;
109566
+ },
109512
109567
  submitted() {
109513
109568
  queue.push({ kind: "phase", data: { phase: "submitted", at: (/* @__PURE__ */ new Date()).toISOString() } });
109514
109569
  },
@@ -109530,6 +109585,8 @@ function createEventCollector() {
109530
109585
  todoCalls.add(id2);
109531
109586
  return;
109532
109587
  }
109588
+ const title = str2(u.title);
109589
+ if (isPollingTool(title)) polls.set(id2, `${title}:${str2(obj2(u.rawInput).task_id) || str2(obj2(u.rawInput).CommandId)}`);
109533
109590
  const target = targetIn(u);
109534
109591
  const subagent = /^(?:Task|Agent|delegate_task|spawn_agent)$/i.test(str2(u.title)) || !!obj2(u.rawInput).subagent_type;
109535
109592
  const data = { toolCallId: id2, title: str2(u.title) || "tool", kind: toolKind(u.kind), status: str2(u.status) || "pending", ...subagent ? { subagent: true } : {}, ...target ? { target } : {} };
@@ -109545,7 +109602,9 @@ function createEventCollector() {
109545
109602
  return;
109546
109603
  }
109547
109604
  release(id2, targetIn(u));
109548
- const result = contentText(u.content);
109605
+ const result = contentText(u.content) || str2(obj2(u.rawOutput).output) || str2(u.rawOutput);
109606
+ const poll = polls.get(id2);
109607
+ if (poll && fresh(poll, toolOutput(result))) activity++;
109549
109608
  if (!u.status && !result) return;
109550
109609
  queue.push({
109551
109610
  kind: "tool_call_update",
@@ -109753,8 +109812,8 @@ function createTail(log) {
109753
109812
  // ../cli/package.json
109754
109813
  var package_default = {
109755
109814
  name: "wildcrane",
109756
- version: "0.11.103",
109757
- akbContract: 36,
109815
+ version: "0.11.105",
109816
+ akbContract: 39,
109758
109817
  canonicalCommands: true,
109759
109818
  description: "WildCrane's `akb` command \u2014 scaffold the Markdown board under docs/kanban/, put an agent on a card, and carry the flows the agent works by.",
109760
109819
  keywords: [
@@ -110521,11 +110580,22 @@ function createAntigravityRenderer(expectedSession, cwd = process.cwd()) {
110521
110580
  let out = "";
110522
110581
  if (!calls.has(id2)) {
110523
110582
  calls.add(id2);
110524
- events.toolCall(id2, name, KINDS[name] ?? "other", target);
110583
+ if (["invoke_subagent", "browser_subagent"].includes(name)) events.subagent(id2, target || name);
110584
+ else events.toolCall(id2, name, KINDS[name] ?? "other", target);
110525
110585
  out = `
110526
110586
  \u23FA ${name}${target ? ` ${target}` : ""}
110527
110587
  `;
110528
110588
  }
110589
+ const output3 = str2(tool.output);
110590
+ if (isPollingTool(name)) {
110591
+ const command = str2(p.CommandId) || str2(p.CommandID) || name;
110592
+ const commandOutput = /(?:^|\n)Command output:\s*([\s\S]*)/.exec(output3)?.[1].trim();
110593
+ const exit = /(?:^|\n)(Command exited with code -?\d+\.)/.exec(output3)?.[1];
110594
+ if (commandOutput) events.progressSnapshot(`command:${command}`, commandOutput);
110595
+ if (exit) events.progressSnapshot(`exit:${command}`, exit);
110596
+ } else if (!["DONE", "ERROR", "CANCELED", "INTERRUPTED"].includes(str2(step.state))) {
110597
+ events.progressSnapshot(id2, output3);
110598
+ }
110529
110599
  const error63 = obj2(tool.error);
110530
110600
  const reason = str2(error63.message) || str2(error63.type);
110531
110601
  if (["DONE", "ERROR", "CANCELED", "INTERRUPTED"].includes(str2(step.state)) && !closed.has(id2)) {
@@ -110543,7 +110613,7 @@ ${imageError(target, reason || str2(step.state))}
110543
110613
  imageErrors.delete(file3);
110544
110614
  }
110545
110615
  }
110546
- events.toolResult(id2, failed ? "failed" : "completed", str2(tool.output) || reason);
110616
+ events.toolResult(id2, failed ? "failed" : "completed", output3 || reason);
110547
110617
  }
110548
110618
  return out;
110549
110619
  }
@@ -110657,7 +110727,7 @@ function systemPrompt(text3, _argv, env2) {
110657
110727
  const rule = `${text3}
110658
110728
 
110659
110729
  The task working directory is ${env2.PWD ?? process.cwd()}. Use it as the base for project files and commands. This additional workspace contains only language rules; do not write task output here.`;
110660
- const hash2 = createHash5("sha256").update(rule).digest("hex").slice(0, 16);
110730
+ const hash2 = createHash6("sha256").update(rule).digest("hex").slice(0, 16);
110661
110731
  const root2 = path17.join(machineHome(), "prompts", `antigravity-${hash2}`);
110662
110732
  const file3 = path17.join(root2, ".agents", "rules", "language.md");
110663
110733
  fs15.mkdirSync(path17.dirname(file3), { recursive: true });
@@ -110909,6 +110979,7 @@ function createStreamRenderer() {
110909
110979
  const plans = /* @__PURE__ */ new Set();
110910
110980
  const subagents = /* @__PURE__ */ new Map();
110911
110981
  const detached = /* @__PURE__ */ new Set();
110982
+ const taskUsage = /* @__PURE__ */ new Map();
110912
110983
  const endSubagent = (id2, status2) => {
110913
110984
  if (subagents.get(id2) !== false) return;
110914
110985
  subagents.set(id2, true);
@@ -110920,8 +110991,18 @@ function createStreamRenderer() {
110920
110991
  if (!ev) return `${line}
110921
110992
  `;
110922
110993
  if (model === void 0) model = eventModel(ev);
110923
- if (str2(ev.parent_tool_use_id)) return "";
110924
- if (ev.type === "assistant" || ev.type === "stream_event" && obj2(ev.event).type === "content_block_delta") events.progress();
110994
+ const parent = str2(ev.parent_tool_use_id);
110995
+ const content = obj2(ev.message).content;
110996
+ const streamEvent = obj2(ev.event);
110997
+ const delta = obj2(streamEvent.delta);
110998
+ if (ev.type === "stream_event" && streamEvent.type === "content_block_delta" && (str2(delta.text) || str2(delta.thinking) || str2(delta.partial_json))) events.progress();
110999
+ if (parent) {
111000
+ if (["assistant", "user"].includes(str2(ev.type)) && Array.isArray(content)) {
111001
+ const useful = content.map(obj2).filter((block) => !!str2(block.text).trim() || !!str2(block.thinking).trim() || block.type === "tool_use" || block.type === "tool_result" && !!resultText(block.content).trim());
111002
+ if (useful.length) events.progressSnapshot(parent, JSON.stringify(useful));
111003
+ }
111004
+ return "";
111005
+ }
110925
111006
  switch (ev.type) {
110926
111007
  case "assistant": {
110927
111008
  apiFailure = typeof ev.error === "string" ? providerFailure({ type: ev.error }, "Claude could not complete the request.") : void 0;
@@ -110937,6 +111018,8 @@ function createStreamRenderer() {
110937
111018
 
110938
111019
  `);
110939
111020
  events.message(b.text);
111021
+ } else if (b?.type === "thinking" && str2(b.thinking).trim()) {
111022
+ events.progressSnapshot("thinking", str2(b.thinking));
110940
111023
  } else if (b?.type === "tool_use" && typeof b.name === "string") {
110941
111024
  out.push(`\u23FA ${b.name}${argHint(b.input, ARG_KEYS)}
110942
111025
  `);
@@ -110956,8 +111039,8 @@ function createStreamRenderer() {
110956
111039
  return out.join("");
110957
111040
  }
110958
111041
  case "user": {
110959
- const content = obj2(ev.message).content;
110960
- for (const raw of Array.isArray(content) ? content : []) {
111042
+ const content2 = obj2(ev.message).content;
111043
+ for (const raw of Array.isArray(content2) ? content2 : []) {
110961
111044
  const b = obj2(raw);
110962
111045
  if (b.type !== "tool_result" || plans.has(str2(b.tool_use_id))) continue;
110963
111046
  if (subagents.has(str2(b.tool_use_id))) {
@@ -111001,8 +111084,20 @@ function createStreamRenderer() {
111001
111084
  if (ev.subtype === "task_notification" && subagents.has(str2(ev.tool_use_id))) {
111002
111085
  endSubagent(str2(ev.tool_use_id), str2(ev.status) === "completed" ? "completed" : "failed");
111003
111086
  }
111004
- if (ev.subtype === "task_notification" && backgrounded.has(str2(ev.task_id)) && str2(ev.summary)) {
111005
- return `\u23FA ${str2(ev.summary)}
111087
+ const task = str2(ev.task_id);
111088
+ if (ev.subtype === "task_progress" && task) {
111089
+ const usage2 = obj2(ev.usage);
111090
+ const previous = taskUsage.get(task) ?? { tokens: 0, tools: 0 };
111091
+ const tokens = Math.max(previous.tokens, Number(usage2.total_tokens) || 0);
111092
+ const tools = Math.max(previous.tools, Number(usage2.tool_uses) || 0);
111093
+ if (tokens > previous.tokens || tools > previous.tools) {
111094
+ taskUsage.set(task, { tokens, tools });
111095
+ events.progress();
111096
+ }
111097
+ }
111098
+ if (ev.subtype === "task_notification" && backgrounded.delete(task)) {
111099
+ events.progress();
111100
+ if (str2(ev.summary)) return `\u23FA ${str2(ev.summary)}
111006
111101
  `;
111007
111102
  }
111008
111103
  return "";
@@ -111342,23 +111437,20 @@ function createCodexStreamRenderer(carried = false) {
111342
111437
  const started = /* @__PURE__ */ new Set();
111343
111438
  const background = createBackgroundTasks();
111344
111439
  const subagents = /* @__PURE__ */ new Set();
111345
- const collabItems = /* @__PURE__ */ new Set();
111346
- const collab = (item, done) => {
111440
+ const collab = (item) => {
111347
111441
  if (item.type !== "collab_tool_call") return;
111348
- const key = `${str2(item.id)}:${done}`;
111349
- if (collabItems.has(key)) return;
111350
- collabItems.add(key);
111351
111442
  for (const [id2, raw] of Object.entries(obj2(item.agents_states))) {
111352
111443
  const state2 = obj2(raw);
111353
111444
  const status2 = str2(state2.status);
111354
111445
  if (!["pending_init", "running", "completed", "interrupted", "errored", "shutdown", "not_found"].includes(status2)) continue;
111355
111446
  const previous = background.results().find((t2) => t2.id === id2);
111356
- if (["shutdown", "not_found"].includes(status2) && previous && previous.status !== "running") continue;
111447
+ const running = status2 === "pending_init" || status2 === "running";
111448
+ if ((running || ["shutdown", "not_found"].includes(status2)) && previous && previous.status !== "running") continue;
111357
111449
  if (!subagents.has(id2)) {
111358
111450
  subagents.add(id2);
111359
111451
  events.subagent(`agent:${id2}`, str2(item.prompt) || "Agent");
111360
111452
  }
111361
- const running = status2 === "pending_init" || status2 === "running";
111453
+ if (running) events.progressSnapshot(`agent:${id2}`, str2(state2.message));
111362
111454
  const failed = !running && status2 !== "completed";
111363
111455
  if (background.update(id2, running ? "running" : failed ? "failed" : "completed", str2(state2.message)) && !running) {
111364
111456
  events.toolResult(`agent:${id2}`, failed ? "failed" : "completed", str2(state2.message));
@@ -111391,15 +111483,21 @@ function createCodexStreamRenderer(carried = false) {
111391
111483
  if (!threadId) threadId = str2(ev.thread_id).trim() || void 0;
111392
111484
  return "";
111393
111485
  case "item.started":
111394
- collab(obj2(ev.item), false);
111486
+ collab(obj2(ev.item));
111395
111487
  itemEvents(events, started, obj2(ev.item), false);
111396
111488
  return renderStarted(obj2(ev.item));
111397
- case "item.updated":
111398
- if (obj2(ev.item).type === "todo_list") itemEvents(events, started, obj2(ev.item), false);
111489
+ case "item.updated": {
111490
+ const item = obj2(ev.item);
111491
+ collab(item);
111492
+ if (item.type === "todo_list") itemEvents(events, started, item, false);
111493
+ if (item.type === "command_execution" && started.has(str2(item.id))) {
111494
+ events.progressSnapshot(`command:${str2(item.id)}`, str2(item.aggregated_output));
111495
+ }
111399
111496
  return "";
111497
+ }
111400
111498
  case "item.completed": {
111401
111499
  const item = obj2(ev.item);
111402
- collab(item, true);
111500
+ collab(item);
111403
111501
  if (item.type === "mcp_tool_call" && !/view_image|read_image|open_image/.test(str2(item.tool))) {
111404
111502
  const content = obj2(item.result).content;
111405
111503
  for (const block of Array.isArray(content) ? content : []) {
@@ -111668,7 +111766,8 @@ function createKimiStreamRenderer(cwd, resumeId) {
111668
111766
  `;
111669
111767
  switch (row.role) {
111670
111768
  case "assistant": {
111671
- events.progress();
111769
+ const thought = str2(row.reasoning_content);
111770
+ if (thought) events.progressSnapshot("reasoning", thought);
111672
111771
  const said = str2(row.content).trim();
111673
111772
  if (said) final = said;
111674
111773
  if (said) events.message(said);
@@ -111765,7 +111864,7 @@ function modelOf2(ref) {
111765
111864
  const provider = str2(model.providerId);
111766
111865
  return provider ? `${provider}/${id2}` : id2;
111767
111866
  }
111768
- function createParts(tail) {
111867
+ function createParts(tail, activity) {
111769
111868
  const written = /* @__PURE__ */ new Map();
111770
111869
  const tools = /* @__PURE__ */ new Set();
111771
111870
  const named = /* @__PURE__ */ new Map();
@@ -111774,6 +111873,7 @@ function createParts(tail) {
111774
111873
  const fresh = text3.startsWith(before) ? text3.slice(before.length) : text3;
111775
111874
  if (!fresh) return;
111776
111875
  written.set(partId, text3);
111876
+ activity();
111777
111877
  if (kind === "reasoning" || kind === "thought") tail.thought(fresh);
111778
111878
  else tail.text(fresh);
111779
111879
  };
@@ -111785,7 +111885,10 @@ function createParts(tail) {
111785
111885
  const partId = str2(part.partId);
111786
111886
  if (type === "text" || type === "reasoning" || type === "thought") {
111787
111887
  if (partId) say(partId, type, str2(part.text));
111788
- else tail.text(str2(part.text));
111888
+ else if (str2(part.text)) {
111889
+ activity();
111890
+ tail.text(str2(part.text));
111891
+ }
111789
111892
  return;
111790
111893
  }
111791
111894
  if (type !== "tool") return;
@@ -111809,14 +111912,18 @@ function createParts(tail) {
111809
111912
  const delta = str2(event2.delta);
111810
111913
  if (!delta) return;
111811
111914
  written.set(partId, (written.get(partId) ?? "") + delta);
111915
+ activity();
111812
111916
  if (field === "reasoning") tail.thought(delta);
111813
111917
  else tail.text(delta);
111814
111918
  },
111815
111919
  /** A piece of the turn, as `model.streaming` sends it. */
111816
111920
  streaming(payload) {
111817
111921
  const kind = str2(payload.kind);
111818
- if (kind === "text_delta") return tail.text(str2(payload.delta));
111819
- if (kind === "reasoning_delta") return tail.thought(str2(payload.delta));
111922
+ const delta = str2(payload.delta);
111923
+ if (delta && (kind === "text_delta" || kind === "reasoning_delta")) {
111924
+ activity();
111925
+ return kind === "text_delta" ? tail.text(delta) : tail.thought(delta);
111926
+ }
111820
111927
  if (kind !== "tool_call") return;
111821
111928
  const callId = str2(payload.toolCallId);
111822
111929
  const name = str2(payload.toolName) || "tool";
@@ -111856,7 +111963,7 @@ function stopped(io, why) {
111856
111963
  }
111857
111964
  async function oneTurn2(io, options) {
111858
111965
  const tail = createTail(io.log);
111859
- const parts = createParts(tail);
111966
+ const parts = createParts(tail, () => io.activity?.());
111860
111967
  const activityEvents = createEventCollector();
111861
111968
  const activeCalls = /* @__PURE__ */ new Set();
111862
111969
  let live = false;
@@ -111883,7 +111990,6 @@ async function oneTurn2(io, options) {
111883
111990
  const part = obj2(payload.part);
111884
111991
  const state2 = obj2(part.state);
111885
111992
  const type = str2(envelope.type);
111886
- if (["part.delta", "model.streaming"].includes(type) && str2(payload.delta)) io.activity?.();
111887
111993
  const id2 = str2(payload.toolCallId) || str2(part.callId) || str2(part.partId);
111888
111994
  const name = str2(payload.toolName) || str2(part.tool) || str2(state2.title);
111889
111995
  if (id2 && name && !activeCalls.has(id2)) {
@@ -111892,7 +111998,21 @@ async function oneTurn2(io, options) {
111892
111998
  else activityEvents.toolCall(id2, name, /^(?:bash|shell|execute|run_command|terminal)$/i.test(name) ? "execute" : "other");
111893
111999
  }
111894
112000
  const status2 = str2(state2.status) || str2(payload.kind);
111895
- if (id2 && ["completed", "error", "result"].includes(status2)) activityEvents.toolResult(id2, status2 === "error" ? "failed" : "completed", "");
112001
+ const output3 = str2(state2.output) || str2(payload.output);
112002
+ if (type === "part.delta" && payload.field === "output") {
112003
+ const before = activityEvents.activity();
112004
+ activityEvents.progressSnapshot(id2 || str2(payload.partId), str2(payload.delta));
112005
+ if (activityEvents.activity() > before) io.activity?.();
112006
+ }
112007
+ if (id2 && ["completed", "error", "result"].includes(status2)) {
112008
+ activityEvents.toolResult(id2, status2 === "error" ? "failed" : "completed", output3);
112009
+ } else if (id2 && output3) {
112010
+ activityEvents.update({
112011
+ sessionUpdate: "tool_call_update",
112012
+ toolCallId: id2,
112013
+ content: [{ type: "content", content: { text: output3 } }]
112014
+ });
112015
+ }
111896
112016
  for (const e of activityEvents.events()) io.event?.(e);
111897
112017
  }
111898
112018
  event(envelope, parts, tail, live, ended);
@@ -111961,6 +112081,7 @@ async function oneTurn2(io, options) {
111961
112081
  });
111962
112082
  const before = io.resumeId ? await tokensOf(rpc, sessionId) : ZERO_USAGE;
111963
112083
  live = true;
112084
+ io.event?.({ kind: "phase", data: { phase: "submitted", at: (/* @__PURE__ */ new Date()).toISOString() } });
111964
112085
  const accepted = await rpc.call("session/send", { sessionId, content: io.prompt });
111965
112086
  if (accepted.accepted === false) throw new Error("the agent would not take the prompt");
111966
112087
  const done = await finished;
@@ -112042,9 +112163,8 @@ function decide2(params, tail) {
112042
112163
 
112043
112164
  // ../cli/src/lib/agent/idle.ts
112044
112165
  var IDLE_MS = 5 * 6e4;
112045
- var IDLE_ERROR = "No response for 5 minutes (idle timeout).";
112166
+ var IDLE_ERROR = "No verifiable progress for 5 minutes (idle timeout).";
112046
112167
  var IDLE_FAILURE = { code: "idle_timeout", source: "runtime", summary: IDLE_ERROR };
112047
- var PROVIDER_RETRY_MS = { announcement: 10 * 6e4, episode: 30 * 6e4 };
112048
112168
 
112049
112169
  // ../cli/src/lib/agent/wire/codex.ts
112050
112170
  import { randomUUID as randomUUID3 } from "node:crypto";
@@ -112373,6 +112493,7 @@ async function run(io, options, count2) {
112373
112493
  const offered = /* @__PURE__ */ new Map();
112374
112494
  const snapshot = (w) => JSON.stringify([w.threadId, w.processId, w.status, w.exitCode, w.result]);
112375
112495
  const childEvents = /* @__PURE__ */ new Map();
112496
+ const freshOutput = progressSnapshots();
112376
112497
  const seenItems = /* @__PURE__ */ new Set();
112377
112498
  const completedTurns = /* @__PURE__ */ new Set();
112378
112499
  const historicalTurns = /* @__PURE__ */ new Set();
@@ -112407,6 +112528,9 @@ async function run(io, options, count2) {
112407
112528
  io.stdout.off("close", closed);
112408
112529
  io.stdin.off("error", inputFailed);
112409
112530
  if (settlement) flushMessages(work.work().some((w) => !w.intentionalStop && !["running", "unknown"].includes(w.status) && presented.get(w.id) !== snapshot(w)));
112531
+ if (classified?.code === "codex_ownership_unconfirmed") {
112532
+ cleanup = { ...cleanup, status: "unconfirmed", detail: classified.detail ?? classified.summary };
112533
+ }
112410
112534
  cleanup.items = work.work().map(({ id: id2, threadId: threadId2, processId, status: status3, disposition }) => ({ id: id2, threadId: threadId2, processId, status: status3, disposition }));
112411
112535
  io.log(renderer.flush());
112412
112536
  const usage = ownUsage(total, baseline);
@@ -112467,7 +112591,9 @@ async function run(io, options, count2) {
112467
112591
  io.idleSignal?.addEventListener("abort", idle, { once: true });
112468
112592
  const childUpdates = () => {
112469
112593
  for (const w of work.entries.values()) {
112470
- if (w.kind !== "agent" || childEvents.get(w.id) === w.status) continue;
112594
+ if (w.kind !== "agent") continue;
112595
+ if (w.status === "running" && freshOutput(w.id, toolOutput(w.result))) io.activity?.();
112596
+ if (childEvents.get(w.id) === w.status) continue;
112471
112597
  if (!childEvents.has(w.id)) io.event?.({ kind: "tool_call", data: { toolCallId: w.id, title: "Agent", kind: "other", status: "in_progress", subagent: true } });
112472
112598
  if (w.status !== "running") io.event?.({ kind: "tool_call_update", data: { toolCallId: w.id, status: w.status === "completed" ? "completed" : "failed", result: w.result } });
112473
112599
  childEvents.set(w.id, w.status);
@@ -112705,7 +112831,26 @@ async function run(io, options, count2) {
112705
112831
  armCleanup();
112706
112832
  if (source === threadId && obj2(p.item).type !== "agentMessage") item(obj2(p.item), msg.method === "item/completed", false);
112707
112833
  }
112708
- if (source !== threadId) {
112834
+ const turnId = str2(p.turnId) || str2(obj2(p.turn).id);
112835
+ const main2 = source === threadId;
112836
+ const live = main2 ? !historicalTurns.has(turnId) && (!currentTurn2 || !turnId || currentTurn2 === turnId) : work.entries.get(`agent:${source}`)?.status === "running";
112837
+ const delta = str2(p.delta);
112838
+ if (submitted && live && delta) {
112839
+ if (["item/agentMessage/delta", "item/plan/delta", "item/reasoning/summaryTextDelta", "item/reasoning/textDelta"].includes(msg.method ?? "")) {
112840
+ if (main2) {
112841
+ if (msg.method?.startsWith("item/reasoning/")) thinking();
112842
+ else recovered();
112843
+ }
112844
+ io.activity?.();
112845
+ }
112846
+ const terminal = terminalKey(source, str2(p.itemId));
112847
+ if (msg.method === "item/commandExecution/outputDelta" && work.entries.get(terminal)?.status === "running" && freshOutput(terminal, toolOutput(delta))) io.activity?.();
112848
+ }
112849
+ if (!main2) {
112850
+ if (live && msg.method === "item/completed") {
112851
+ const item2 = obj2(p.item);
112852
+ if (freshOutput(`${source}:${str2(item2.id)}`, toolOutput(str2(item2.text) || str2(item2.aggregatedOutput)))) io.activity?.();
112853
+ }
112709
112854
  if (msg.method === "turn/completed") {
112710
112855
  work.observeTurn(source, obj2(p.turn));
112711
112856
  armCleanup();
@@ -112713,13 +112858,7 @@ async function run(io, options, count2) {
112713
112858
  childUpdates();
112714
112859
  return;
112715
112860
  }
112716
- const turnId = str2(p.turnId) || str2(obj2(p.turn).id);
112717
- if (historicalTurns.has(turnId) || currentTurn2 && turnId && currentTurn2 !== turnId) return;
112718
- if (submitted && ["item/agentMessage/delta", "item/plan/delta", "item/reasoning/summaryTextDelta", "item/reasoning/textDelta"].includes(msg.method ?? "") && str2(p.delta)) {
112719
- if (msg.method?.startsWith("item/reasoning/")) thinking();
112720
- else recovered();
112721
- io.activity?.();
112722
- }
112861
+ if (!live) return;
112723
112862
  if (msg.method === "turn/started") {
112724
112863
  if (!submitted || completedTurns.has(turnId)) return;
112725
112864
  currentTurn2 = turnId;
@@ -112821,7 +112960,6 @@ async function run(io, options, count2) {
112821
112960
  waiting2 = true;
112822
112961
  io.event?.({ kind: "log", data: { text: failure5.summary } });
112823
112962
  }
112824
- io.activity?.();
112825
112963
  await delay(500, void 0, { signal: io.signal });
112826
112964
  preparingUntil = Date.now() + CONVERSATION_MS.prepare;
112827
112965
  }
@@ -114163,43 +114301,8 @@ import path22 from "node:path";
114163
114301
 
114164
114302
  // src/proxy.ts
114165
114303
  var import_undici = __toESM(require_undici(), 1);
114166
-
114167
- // ../cli/src/lib/agent/proxy.ts
114168
- import { execFileSync } from "node:child_process";
114169
- var PROXY_KEYS = ["HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"];
114170
- function withSystemProxy(env2 = process.env, platform = process.platform, read3 = () => execFileSync("/usr/sbin/scutil", ["--proxy"], { encoding: "utf8", timeout: 1e3, stdio: ["ignore", "pipe", "ignore"] })) {
114171
- const out = { ...env2 };
114172
- if (platform !== "darwin" || PROXY_KEYS.some((key) => env2[key] !== void 0)) return out;
114173
- let raw;
114174
- try {
114175
- raw = read3();
114176
- } catch {
114177
- return out;
114178
- }
114179
- const value = (key) => new RegExp(`^\\s*${key}\\s*:\\s*(.*?)\\s*$`, "m").exec(raw)?.[1];
114180
- for (const [name, key, scheme] of [["HTTP", "HTTP_PROXY", "http"], ["HTTPS", "HTTPS_PROXY", "http"], ["SOCKS", "ALL_PROXY", "socks5"]]) {
114181
- if (value(`${name}Enable`) !== "1") continue;
114182
- const host2 = value(`${name}Proxy`);
114183
- const port = Number(value(`${name}Port`));
114184
- if (!host2 || /[\s/@?#]/.test(host2) || !Number.isInteger(port) || port < 1 || port > 65535) continue;
114185
- try {
114186
- out[key] = new URL(`${scheme}://${host2.includes(":") && !host2.startsWith("[") ? `[${host2}]` : host2}:${port}`).href.replace(/\/$/, "");
114187
- } catch {
114188
- }
114189
- }
114190
- if (PROXY_KEYS.some((key) => out[key]) && env2.NO_PROXY === void 0 && env2.no_proxy === void 0) {
114191
- const exceptions = /ExceptionsList\s*:\s*<array>\s*\{([^}]+)\}/.exec(raw)?.[1];
114192
- const bypass = exceptions?.split("\n").flatMap((line) => {
114193
- const host2 = /^\s*\d+\s*:\s*(\S+)\s*$/.exec(line)?.[1];
114194
- return host2 ? [host2.startsWith("*.") ? host2.slice(1) : host2] : [];
114195
- });
114196
- if (bypass?.length) out.NO_PROXY = bypass.join(",");
114197
- }
114198
- return out;
114199
- }
114200
-
114201
- // src/proxy.ts
114202
114304
  var LOOPBACK = "localhost,127.0.0.1,[::1]";
114305
+ var withLoopback = (value) => [value, LOOPBACK].filter(Boolean).join(",");
114203
114306
  var HOST_PROXY_ENV = "WILDCRANE_HOST_PROXY";
114204
114307
  var HOST = null;
114205
114308
  var current = {};
@@ -114220,7 +114323,7 @@ function followProxy(read3) {
114220
114323
  const route = {
114221
114324
  httpProxy,
114222
114325
  httpsProxy: current.HTTPS_PROXY || current.https_proxy || httpProxy,
114223
- noProxy: [current.NO_PROXY ?? current.no_proxy, LOOPBACK].filter(Boolean).join(",")
114326
+ noProxy: withLoopback(current.NO_PROXY ?? current.no_proxy)
114224
114327
  };
114225
114328
  const key = JSON.stringify(route);
114226
114329
  if (key !== applied) {
@@ -114261,8 +114364,8 @@ function machineId() {
114261
114364
  var machineName = () => os4.hostname().replace(/\.local$/, "");
114262
114365
 
114263
114366
  // src/protocol.ts
114264
- var VERSION = true ? "0.6.121" : "0.0.0";
114265
- var AKB_VERSION = true ? "0.11.103" : "0.0.0";
114367
+ var VERSION = true ? "0.6.123" : "0.0.0";
114368
+ var AKB_VERSION = true ? "0.11.105" : "0.0.0";
114266
114369
  var EXIT_OUTDATED = 11;
114267
114370
  var EXIT_UPDATE = 12;
114268
114371
  var EXIT_ALREADY_RUNNING = 13;
@@ -114708,26 +114811,71 @@ import fs24 from "node:fs";
114708
114811
  import path28 from "node:path";
114709
114812
  import zlib from "node:zlib";
114710
114813
  var PACKAGE = "wildcrane-runner";
114814
+ var OFFICIAL_REGISTRY = "https://registry.npmjs.org";
114711
114815
  var TIMEOUT_MS2 = 6e4;
114712
114816
  var versionsDir = () => path28.join(runnerHome(), "bin", "runner");
114713
114817
  var legacyVersionsDir = () => path28.join(runnerHome(), "runner");
114714
114818
  var versionDir = (version3) => path28.join(versionsDir(), version3);
114715
114819
  var entryOf = (dir) => path28.join(dir, "dist", "runner.mjs");
114716
114820
  var RUNNER = { name: PACKAGE, dirOf: versionDir, entryOf };
114717
- var registry3 = () => (process.env.npm_config_registry || "https://registry.npmjs.org").replace(/\/+$/, "");
114821
+ var testRegistryOverride = null;
114822
+ var cachedKeys = null;
114823
+ function resolveRegistry() {
114824
+ if (testRegistryOverride) return { ok: true, url: testRegistryOverride };
114825
+ const configured = process.env.npm_config_registry?.trim().replace(/\/+$/, "");
114826
+ if (configured && configured !== OFFICIAL_REGISTRY) {
114827
+ return { ok: false, detail: `untrusted npm_config_registry: ${configured}` };
114828
+ }
114829
+ return { ok: true, url: OFFICIAL_REGISTRY };
114830
+ }
114831
+ async function registryKeys(registryUrl) {
114832
+ if (cachedKeys?.source === registryUrl) return cachedKeys.keys;
114833
+ const answer = await fetch(`${registryUrl}/-/npm/v1/keys`, { signal: AbortSignal.timeout(TIMEOUT_MS2) });
114834
+ if (!answer.ok) throw new Error(`keys answered ${answer.status}`);
114835
+ const body = await answer.json();
114836
+ const keys = /* @__PURE__ */ new Map();
114837
+ for (const entry of body.keys ?? []) {
114838
+ if (!entry.keyid || !entry.key) continue;
114839
+ if (entry.expires && Date.parse(entry.expires) <= Date.now()) continue;
114840
+ keys.set(entry.keyid, crypto6.createPublicKey({ key: Buffer.from(entry.key, "base64"), format: "der", type: "spki" }));
114841
+ }
114842
+ cachedKeys = { source: registryUrl, keys };
114843
+ return keys;
114844
+ }
114845
+ async function verifySignature(registryUrl, pkgName, version3, integrity, signatures) {
114846
+ if (!Array.isArray(signatures) || signatures.length === 0) return false;
114847
+ const keys = await registryKeys(registryUrl);
114848
+ const payload = Buffer.from(`${pkgName}@${version3}:${integrity}`);
114849
+ for (const entry of signatures) {
114850
+ if (!entry.keyid || !entry.sig) continue;
114851
+ const key = keys.get(entry.keyid);
114852
+ if (!key) continue;
114853
+ try {
114854
+ if (crypto6.verify("sha256", payload, key, Buffer.from(entry.sig, "base64"))) return true;
114855
+ } catch {
114856
+ }
114857
+ }
114858
+ return false;
114859
+ }
114718
114860
  var install2 = (version3, nodeVersion) => installPackage(RUNNER, version3, nodeVersion);
114719
114861
  async function installPackage(pkg, version3, nodeVersion = process.versions.node) {
114720
114862
  const dir = pkg.dirOf(version3);
114721
114863
  if (fs24.existsSync(pkg.entryOf(dir))) return { ok: true, dir };
114864
+ const reg = resolveRegistry();
114865
+ if (!reg.ok) return { ok: false, why: "integrity", detail: reg.detail };
114866
+ const registryUrl = reg.url;
114722
114867
  let meta4;
114723
114868
  let tarball;
114724
114869
  try {
114725
- const answer = await fetch(`${registry3()}/${pkg.name}/${encodeURIComponent(version3)}`, { signal: AbortSignal.timeout(TIMEOUT_MS2) });
114870
+ const answer = await fetch(`${registryUrl}/${pkg.name}/${encodeURIComponent(version3)}`, { signal: AbortSignal.timeout(TIMEOUT_MS2) });
114726
114871
  if (!answer.ok) return { ok: false, why: "unreachable", detail: `registry answered ${answer.status}` };
114727
114872
  meta4 = await answer.json();
114728
114873
  const range = meta4.engines?.node;
114729
114874
  if (range && !satisfies(nodeVersion, range)) return { ok: false, why: "node", detail: range };
114730
114875
  if (!meta4.dist?.tarball) return { ok: false, why: "unreachable", detail: "no tarball" };
114876
+ if (!testRegistryOverride && !meta4.dist.tarball.startsWith(`${OFFICIAL_REGISTRY}/`)) {
114877
+ return { ok: false, why: "integrity", detail: "tarball outside official registry" };
114878
+ }
114731
114879
  const download = await fetch(meta4.dist.tarball, { signal: AbortSignal.timeout(TIMEOUT_MS2) });
114732
114880
  if (!download.ok) return { ok: false, why: "unreachable", detail: `download answered ${download.status}` };
114733
114881
  tarball = Buffer.from(await download.arrayBuffer());
@@ -114737,6 +114885,12 @@ async function installPackage(pkg, version3, nodeVersion = process.versions.node
114737
114885
  const expected = /^sha512-(.+)$/.exec(meta4.dist.integrity ?? "")?.[1];
114738
114886
  const actual = crypto6.createHash("sha512").update(tarball).digest("base64");
114739
114887
  if (!expected || expected !== actual) return { ok: false, why: "integrity", detail: "sha512 mismatch" };
114888
+ try {
114889
+ const signed = await verifySignature(registryUrl, pkg.name, version3, meta4.dist.integrity, meta4.dist.signatures);
114890
+ if (!signed) return { ok: false, why: "integrity", detail: "dist.signatures verification failed" };
114891
+ } catch (e) {
114892
+ return { ok: false, why: "unreachable", detail: e instanceof Error ? e.message : String(e) };
114893
+ }
114740
114894
  const staging = `${dir}.${process.pid}.tmp`;
114741
114895
  try {
114742
114896
  fs24.rmSync(staging, { recursive: true, force: true });
@@ -115863,16 +116017,36 @@ var PAGE = (outcome, lang, links) => {
115863
116017
  const top = links ? `<h1>${title}</h1><p>${body}</p><form id="f" novalidate><input id="e" type="email" autocomplete="email" placeholder="${c.email}" required><input id="c" inputmode="numeric" autocomplete="one-time-code" maxlength="10" placeholder="${c.code}" hidden><button id="b" class="dark">${c.send}</button><small id="m"></small><button id="x" type="button" class="link" hidden>${c.change}</button></form><div class="or">${c.or}</div><nav><a href="${links.github}">${GITHUB_ICON}${c.github}</a><a href="${links.google}">${GOOGLE_ICON}${c.google}</a></nav><script>${EMAIL_SCRIPT(c)}</script>` : `<span class="icon"><svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${icon2}</svg></span><h1 class="below">${title}</h1><p>${body}</p>`;
115864
116018
  return `<!doctype html><html lang="${lang === "zh" ? "zh-CN" : "en"}"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title} \xB7 WildCrane</title><style>*{margin:0;box-sizing:border-box}body{display:flex;flex-direction:column;min-height:100dvh;background:#fff;color:#24231f;font-family:ui-sans-serif,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif}header{padding:16px 36px 0}main{flex:1;display:flex;align-items:center;justify-content:center;padding:0 36px 64px;text-align:center}.icon{display:flex;margin:0 auto;width:44px;height:44px;border-radius:50%;align-items:center;justify-content:center;background:${ok ? "#e4f3ea" : "#f7ddce"};color:${ok ? "#2f6b46" : "#b83a12"}}h1{font-size:24px;font-weight:850;line-height:1.25;letter-spacing:-0.02em}h1.below{margin-top:16px}p{margin:8px auto 0;max-width:38ch;font-size:13px;line-height:19px;color:#565550}main>div.choose{width:100%;max-width:320px}nav{margin-top:28px;display:flex;flex-direction:column;gap:12px}nav a{display:flex;height:44px;align-items:center;justify-content:center;gap:8px;border-radius:10px;font-size:14.5px;font-weight:600;color:#24231f;text-decoration:none;background:#fff;border:1px solid rgba(36,35,31,0.14)}nav a.dark{background:#24231f;color:#fff;border-color:#24231f}form{margin-top:28px;display:flex;flex-direction:column;gap:12px}input{height:44px;padding:0 14px;border-radius:10px;border:1px solid rgba(36,35,31,0.14);font:inherit;font-size:14.5px}button{height:44px;border-radius:10px;border:0;font:inherit;font-size:14.5px;font-weight:600;cursor:pointer}button.dark{background:#24231f;color:#fff}button:disabled{opacity:.6}button.link{height:auto;background:none;color:#565550;font-size:13px;font-weight:500}small{font-size:13px;line-height:19px;color:#565550}small.bad{color:#b83a12}small:empty{display:none}.or{margin-top:20px;display:flex;align-items:center;gap:12px;font-size:13px;color:#8a8984}.or::before,.or::after{content:"";flex:1;height:1px;background:rgba(36,35,31,0.12)}.or+nav{margin-top:20px}</style><header><svg viewBox="2 4 56 52" width="23.7" height="22" aria-hidden="true"><path d="${CRANE}" fill="#24231f"/><path d="${CREST}" fill="#dd4f1e"/></svg></header><main><div${links ? ' class="choose"' : ""}>${top}</div></main></html>`;
115865
116019
  };
116020
+ function sameToken(a, b) {
116021
+ if (!a || a.length !== b.length) return false;
116022
+ return crypto8.timingSafeEqual(Buffer.from(a), Buffer.from(b));
116023
+ }
115866
116024
  async function signIn(options = {}) {
115867
116025
  const generation = accountGeneration();
115868
116026
  const verifier = base64url4(crypto8.randomBytes(32));
115869
116027
  const challenge = base64url4(crypto8.createHash("sha256").update(verifier).digest());
116028
+ const oauthState = base64url4(crypto8.randomBytes(24));
115870
116029
  let finish = () => {
115871
116030
  };
115872
116031
  const answered = new Promise((resolve2) => finish = resolve2);
115873
116032
  let answering = false;
116033
+ let expectedOrigin = "";
115874
116034
  const server2 = http.createServer(async (req, res) => {
116035
+ res.setHeader("cache-control", "no-store");
116036
+ res.setHeader("referrer-policy", "no-referrer");
116037
+ res.setHeader("x-content-type-options", "nosniff");
116038
+ const expectedHost = expectedOrigin.slice(7);
116039
+ const secFetchSite = req.headers["sec-fetch-site"] ? String(req.headers["sec-fetch-site"]) : null;
116040
+ if (req.headers.host !== expectedHost || req.headers.origin && req.headers.origin !== expectedOrigin) {
116041
+ res.writeHead(403, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify({ error: "forbidden" }));
116042
+ return;
116043
+ }
115875
116044
  const asked = new URL(req.url ?? "/", "http://127.0.0.1");
116045
+ const isCallback = asked.pathname === "/signed-in";
116046
+ if (secFetchSite && !(isCallback ? ["same-origin", "none", "cross-site"] : ["same-origin", "none"]).includes(secFetchSite)) {
116047
+ res.writeHead(403, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify({ error: "forbidden" }));
116048
+ return;
116049
+ }
115876
116050
  const lang = langOf(req.headers["accept-language"]);
115877
116051
  if (asked.pathname === "/" && !answering) {
115878
116052
  res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
@@ -115880,6 +116054,10 @@ async function signIn(options = {}) {
115880
116054
  return;
115881
116055
  }
115882
116056
  if (req.method === "POST" && (asked.pathname === "/send" || asked.pathname === "/verify") && !answering) {
116057
+ if (req.headers.origin !== expectedOrigin) {
116058
+ res.writeHead(403, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify({ error: "forbidden" }));
116059
+ return;
116060
+ }
115883
116061
  const asks = await readJson2(req);
115884
116062
  const answer = asked.pathname === "/send" ? await sendCode(asks.email ?? "", lang) : await verifyCode(asks.email ?? "", asks.code ?? "", generation, options.signal);
115885
116063
  const done = answer.ok && asked.pathname === "/verify";
@@ -115899,7 +116077,8 @@ async function signIn(options = {}) {
115899
116077
  const params = asked.searchParams;
115900
116078
  const code = params.get("code");
115901
116079
  const error63 = params.get("error");
115902
- const failure6 = code ? await exchange(code, verifier, generation, options.signal) : {
116080
+ const stateOk = sameToken(params.get("state"), oauthState);
116081
+ const failure6 = !stateOk ? { why: "other", detail: "invalid oauth state" } : code ? await exchange(code, verifier, generation, options.signal) : {
115903
116082
  why: error63 === "access_denied" ? "denied" : "other",
115904
116083
  detail: params.get("error_description") || error63 || "no code came back"
115905
116084
  };
@@ -115910,6 +116089,7 @@ async function signIn(options = {}) {
115910
116089
  });
115911
116090
  await new Promise((resolve2) => server2.listen(0, "127.0.0.1", resolve2));
115912
116091
  const { port } = server2.address();
116092
+ expectedOrigin = `http://127.0.0.1:${port}`;
115913
116093
  const { supabaseUrl } = cloudEndpoints();
115914
116094
  const authorize = (provider) => {
115915
116095
  const url2 = new URL(`${supabaseUrl}/auth/v1/authorize`);
@@ -115918,18 +116098,20 @@ async function signIn(options = {}) {
115918
116098
  if (provider === "github") url2.searchParams.set("scopes", "user:email");
115919
116099
  url2.searchParams.set("code_challenge", challenge);
115920
116100
  url2.searchParams.set("code_challenge_method", "s256");
116101
+ url2.searchParams.set("state", oauthState);
115921
116102
  return url2.toString().replace(/&/g, "&amp;");
115922
116103
  };
115923
116104
  const choose = `http://127.0.0.1:${port}/`;
115924
116105
  const onUrl = options.onUrl ?? ((u) => status(t.signIn(u)));
115925
116106
  onUrl(choose);
115926
- openBrowser(choose);
116107
+ if (!options.noBrowser) openBrowser(choose);
115927
116108
  const timer = setTimeout(() => finish({ why: "timeout", detail: "timed out" }), WAIT_MS);
115928
116109
  const cancel = () => finish({ why: "cancelled", detail: "cancelled" });
115929
116110
  options.signal?.addEventListener("abort", cancel);
115930
116111
  const failure5 = await answered;
115931
116112
  clearTimeout(timer);
115932
116113
  options.signal?.removeEventListener("abort", cancel);
116114
+ server2.closeAllConnections();
115933
116115
  server2.close();
115934
116116
  return failure5;
115935
116117
  }