@sjawhar/claude-envoy 2.18.0 → 2.19.1

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/dispatch.js CHANGED
@@ -17763,6 +17763,7 @@ function zodSchemaApi(zod) {
17763
17763
  var STDIN = "-";
17764
17764
  var BARE_WORD = /^[A-Za-z0-9_./:@%+=,-]+$/;
17765
17765
  var OPTION_SEPARATOR = ": ";
17766
+ var LOCAL_FILE_FIELD = { tool: "dispatch_artifact", field: "path" };
17766
17767
  function commandName(tool) {
17767
17768
  return tool.replace(/^dispatch_/, "").replaceAll("_", "-");
17768
17769
  }
@@ -18015,6 +18016,7 @@ function parseCommand(argv, io) {
18015
18016
  const args = {};
18016
18017
  const setBy = new Map;
18017
18018
  const problems = [];
18019
+ const bareDashes = new Set;
18018
18020
  let help = false;
18019
18021
  let dryRun = false;
18020
18022
  let stdinFlag;
@@ -18131,6 +18133,10 @@ function parseCommand(argv, io) {
18131
18133
  const parsed = info.kind === "number" ? number(flag, value) : value;
18132
18134
  if (claimed && parsed !== undefined)
18133
18135
  args[field] = parsed;
18136
+ if (info.kind === "string" && value === STDIN && !(tool === LOCAL_FILE_FIELD.tool && field === LOCAL_FILE_FIELD.field) && !bareDashes.has(flag)) {
18137
+ bareDashes.add(flag);
18138
+ problems.push(`${flag} - sends the one character "-". ${flag}-file <path> reads ${flag} from a file, and ${flag}-file - reads it from stdin. One flag of a call may read stdin.`);
18139
+ }
18134
18140
  break;
18135
18141
  }
18136
18142
  case "file": {
@@ -18162,8 +18168,9 @@ function parseCommand(argv, io) {
18162
18168
  }
18163
18169
  if (help)
18164
18170
  return { kind: "help", tool };
18165
- if (problems.length > 0)
18166
- return { kind: "refused", tool, problems };
18171
+ if (problems.length > 0) {
18172
+ return problems.length === bareDashes.size ? { kind: "refused", tool, problems, aboutAFlag: false } : { kind: "refused", tool, problems };
18173
+ }
18167
18174
  return { kind: "call", tool, args, dryRun };
18168
18175
  }
18169
18176
  function appendedItem(kind, flag, value, number) {
@@ -18269,1211 +18276,456 @@ function commandsHelp() {
18269
18276
  `);
18270
18277
  }
18271
18278
 
18272
- // ../envoy-client/src/dispatch-cwd.ts
18273
- import { execFile } from "child_process";
18274
- import { promisify } from "util";
18275
-
18276
- // ../envoy-client/src/machine.ts
18277
- import { hostname as hostname3 } from "os";
18278
- function machineID() {
18279
- return process.env["ENVOY_MACHINE_ID"] || process.env["AGENTBOX_HOST"] || hostname3();
18279
+ // ../contracts/src/trailing-slash.ts
18280
+ function withoutTrailingSlashes(url) {
18281
+ let end = url.length;
18282
+ while (end > 0 && url[end - 1] === "/")
18283
+ end -= 1;
18284
+ return url.slice(0, end);
18280
18285
  }
18281
18286
 
18282
- // ../envoy-client/src/dispatch-cwd.ts
18283
- var execFileAsync = promisify(execFile);
18284
- var defaultExec = (file, args, { cwd, signal }) => {
18285
- const call = execFileAsync(file, args, { cwd, signal });
18286
- const kill = () => call.child.kill("SIGKILL");
18287
- if (signal.aborted)
18288
- kill();
18289
- else
18290
- signal.addEventListener("abort", kill, { once: true });
18291
- return call;
18292
- };
18293
- var REMOTE_LOOKUP_MS = 5000;
18294
- var TMUX_PANE_LOOKUP_MS = 1000;
18295
- async function tryExec(exec, file, args, cwd, limitMs) {
18296
- const controller = new AbortController;
18297
- const expired = Promise.withResolvers();
18298
- const timer = setTimeout(() => {
18299
- controller.abort();
18300
- expired.resolve(null);
18301
- }, limitMs);
18302
- try {
18303
- const answer = await Promise.race([
18304
- exec(file, args, { cwd, signal: controller.signal }),
18305
- expired.promise
18306
- ]);
18307
- if (answer === null) {
18308
- return { failure: "timedOut", ok: false };
18309
- }
18310
- return { ok: true, stdout: answer.stdout };
18311
- } catch {
18312
- return { failure: "refused", ok: false };
18313
- } finally {
18314
- clearTimeout(timer);
18315
- }
18287
+ // ../envoy-client/src/ask-answer.ts
18288
+ var HEAD_LENGTH = 120;
18289
+ function textHead(text, length = HEAD_LENGTH) {
18290
+ const flat = text.replace(/\s+/g, " ").trim();
18291
+ return flat.length > length ? `${flat.slice(0, length)}\u2026` : flat;
18316
18292
  }
18317
- function parseRemoteList(stdout) {
18318
- const remotes = new Map;
18319
- for (const line of stdout.split(`
18320
- `)) {
18321
- const trimmed = line.trim();
18322
- if (!trimmed)
18323
- continue;
18324
- const match = trimmed.match(/^(\S+)\s+(\S+)/);
18325
- const [, name, url] = match ?? [];
18326
- if (name && url)
18327
- remotes.set(name, url);
18328
- }
18329
- return remotes;
18293
+ var QUESTION_HEAD = 200;
18294
+ var DISPATCH_WORDS_LABEL = "Dispatch's words:";
18295
+ function dispatchWordsText(words, render) {
18296
+ if (words === null || words === undefined || words === "")
18297
+ return;
18298
+ return `${DISPATCH_WORDS_LABEL} ${render === undefined ? words : render(words)}`;
18330
18299
  }
18331
- function selectRemoteUrl(remotes) {
18332
- const origin = remotes.get("origin");
18333
- if (origin)
18334
- return origin;
18335
- const candidates = [...remotes.entries()].filter(([name]) => name !== "upstream");
18336
- return candidates.length === 1 ? candidates[0]?.[1] ?? null : null;
18300
+ function askAnswerText(answer) {
18301
+ if (answer === null || answer === undefined)
18302
+ return "";
18303
+ const selected = (answer.selected ?? []).join(", ");
18304
+ const text = answer.text ?? "";
18305
+ if (text === "")
18306
+ return selected;
18307
+ if (selected === "")
18308
+ return text;
18309
+ return `${selected} - ${text}`;
18337
18310
  }
18338
- var GITHUB_REMOTE_PATTERNS = [
18339
- /^https:\/\/(?:[^@/\s]+@)?github\.com\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/i,
18340
- /^git@github\.com:([^/]+)\/([^/]+?)(?:\.git)?\/?$/i,
18341
- /^ssh:\/\/git@github\.com\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/i
18342
- ];
18343
- function parseGitHubRemoteUrl(url) {
18344
- const trimmed = url.trim();
18345
- for (const pattern of GITHUB_REMOTE_PATTERNS) {
18346
- const match = trimmed.match(pattern);
18347
- if (match)
18348
- return canonicalRepo(match[1] ?? "", match[2] ?? "");
18311
+
18312
+ // ../envoy-client/src/dispatch-http.ts
18313
+ class DispatchServiceError extends Error {
18314
+ code;
18315
+ status;
18316
+ candidates;
18317
+ current;
18318
+ mismatches;
18319
+ name = "DispatchServiceError";
18320
+ fromDispatch = true;
18321
+ constructor(code, status, message, candidates, current, mismatches) {
18322
+ super(message);
18323
+ this.code = code;
18324
+ this.status = status;
18325
+ this.candidates = candidates;
18326
+ this.current = current;
18327
+ this.mismatches = mismatches;
18349
18328
  }
18350
- return null;
18351
18329
  }
18352
- async function resolveCwdRepo(cwd, exec) {
18353
- const remoteList = await tryExec(exec, "jj", ["git", "remote", "list"], cwd, REMOTE_LOOKUP_MS);
18354
- if (remoteList.ok) {
18355
- const url = selectRemoteUrl(parseRemoteList(remoteList.stdout));
18356
- return url ? parseGitHubRemoteUrl(url) : null;
18330
+
18331
+ class DispatchGatewayError extends DispatchServiceError {
18332
+ answer;
18333
+ advice;
18334
+ fromDispatch = false;
18335
+ transient;
18336
+ mayHaveReachedDispatch;
18337
+ constructor(status, answer, advice, message = `${answer}, so ${advice}.`) {
18338
+ super(`HTTP_${status}`, status, message);
18339
+ this.answer = answer;
18340
+ this.advice = advice;
18341
+ this.transient = transientStatus(status);
18342
+ this.mayHaveReachedDispatch = reachesDispatch(status);
18357
18343
  }
18358
- const originRemote = await tryExec(exec, "git", ["remote", "get-url", "origin"], cwd, REMOTE_LOOKUP_MS);
18359
- return originRemote.ok ? parseGitHubRemoteUrl(originRemote.stdout) : null;
18360
18344
  }
18361
- async function resolveOrigin(env, exec, cwd) {
18362
- const origin = {
18363
- cwd,
18364
- machine: machineID()
18365
- };
18366
- const pane = env.TMUX_PANE;
18367
- if (pane) {
18368
- const answer = await tryExec(exec, "tmux", ["display-message", "-p", "-t", pane, "#S:#I.#P #{pane_id}"], cwd, TMUX_PANE_LOOKUP_MS);
18369
- const [target, paneId] = answer.ok ? answer.stdout.trim().split(" ") : [];
18370
- if (target)
18371
- origin.tmux = target;
18372
- if (paneId)
18373
- origin.pane = paneId;
18345
+
18346
+ class DispatchWriteUnsettledError extends Error {
18347
+ last;
18348
+ attempts;
18349
+ name = "DispatchWriteUnsettledError";
18350
+ constructor(last, attempts, unanswered, keyed = false) {
18351
+ let answer;
18352
+ let why = "an earlier attempt of the write may have reached Dispatch";
18353
+ if (last instanceof DispatchGatewayError) {
18354
+ answer = last.answer;
18355
+ } else if (last instanceof DispatchServiceError && last.code === IDEMPOTENCY_KEY_IN_FLIGHT) {
18356
+ answer = last.code;
18357
+ why = "Dispatch was still running an earlier attempt of the write";
18358
+ } else if (last instanceof DispatchServiceError) {
18359
+ answer = `${last.code}: ${last.message}`;
18360
+ } else {
18361
+ answer = unanswered ?? last.message;
18362
+ why = "an attempt of the write may have reached Dispatch";
18363
+ }
18364
+ const tried = attempts === 1 ? "its only attempt" : `the last of ${attempts} attempts`;
18365
+ const next = keyed ? ". Dispatch finishes an attempt it received whatever this command does, so read the " + "write back before you send it again: a new command sends it under a new key." : ": check whether it did before retrying it.";
18366
+ super(`${answer} (${tried}), and ${why}, so it may or may not have taken effect${next}`, {
18367
+ cause: last
18368
+ });
18369
+ this.last = last;
18370
+ this.attempts = attempts;
18374
18371
  }
18375
- return origin;
18376
18372
  }
18377
18373
 
18378
- // ../envoy-client/src/dispatch-owner.ts
18379
- function documentLabel(project, slug) {
18380
- return `${project}/${slug}`;
18374
+ class DispatchWriteLandedError extends Error {
18375
+ code;
18376
+ status;
18377
+ name = "DispatchWriteLandedError";
18378
+ constructor(code, status, method, url) {
18379
+ const lost = code === IDEMPOTENCY_ANSWER_NOT_KEPT ? "Dispatch kept no copy of its answer, which was too large" : "its answer was lost on the way back";
18380
+ super(`${method} ${url} was made, but ${lost} (${code}), so this command cannot print what it ` + "made: read it back with `dispatch read`, or with the matching list for something it created.");
18381
+ this.code = code;
18382
+ this.status = status;
18383
+ }
18381
18384
  }
18382
- function ownerTitle(owner) {
18383
- const { issue, document } = owner;
18384
- if (issue !== undefined)
18385
- return `${issue.key}: ${issue.title}`;
18386
- if (document !== undefined)
18387
- return `${document.project} / ${document.name}`;
18388
- return "";
18385
+ function asErrorShape(value) {
18386
+ return typeof value === "object" && value !== null ? value : {};
18389
18387
  }
18390
- function issueTopic(key) {
18391
- return { label: key, topic: dispatchIssueSubject(key, ">") };
18388
+ function isJson(response) {
18389
+ return response.headers.get("content-type")?.includes("application/json") ?? false;
18392
18390
  }
18393
- function documentTopicOf(project, slug) {
18394
- return {
18395
- label: documentLabel(project, slug),
18396
- topic: dispatchDocumentSubject(project, slug, ">")
18397
- };
18391
+ function isNoRoute(error) {
18392
+ return error instanceof DispatchServiceError && error.status === 404 && error.code === "NOT_FOUND" && error.message.startsWith("no route for ");
18398
18393
  }
18399
- function dispatchIssueRef(key) {
18400
- return `dispatch://${key}`;
18394
+ var ISSUE_EVENTS_PAGE_MAX = 200;
18395
+ var DISPATCH_TOOL_DEADLINE_MS = 60000;
18396
+ function requestSignal(signal) {
18397
+ const deadline = AbortSignal.timeout(DISPATCH_TOOL_DEADLINE_MS);
18398
+ return signal === undefined ? deadline : AbortSignal.any([signal, deadline]);
18401
18399
  }
18402
- function dispatchDocumentRef(owner, slug) {
18403
- return `dispatch://${owner}/artifact/${slug}`;
18400
+ var DISPATCH_WRITE_RETRY = {
18401
+ pausesMs: [1000, 2000, 4000, 8000],
18402
+ withinMs: 30000,
18403
+ silenceMs: 20000,
18404
+ inFlightPauseMs: 3000,
18405
+ inFlightWithinMs: 55000
18406
+ };
18407
+ function pauseFor(ms, signal) {
18408
+ const { promise, resolve, reject } = Promise.withResolvers();
18409
+ if (signal.aborted) {
18410
+ reject(signal.reason);
18411
+ return promise;
18412
+ }
18413
+ const stop = () => {
18414
+ clearTimeout(timer);
18415
+ reject(signal.reason);
18416
+ };
18417
+ const timer = setTimeout(() => {
18418
+ signal.removeEventListener("abort", stop);
18419
+ resolve();
18420
+ }, ms);
18421
+ signal.addEventListener("abort", stop, { once: true });
18422
+ return promise;
18404
18423
  }
18405
- var ITEM_KINDS = ["ask", "comment", "message"];
18406
- function dispatchChildRef(ownerRef, kind, id) {
18407
- return `${ownerRef}/${kind}/${id}`;
18424
+ function retryAfterMs(response) {
18425
+ const value = response.headers.get("Retry-After")?.trim() ?? "";
18426
+ if (/^\d+$/.test(value))
18427
+ return Number(value) * 1000;
18428
+ const at = Date.parse(value);
18429
+ return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
18408
18430
  }
18409
- function parseBlockRef(holder, fragment) {
18410
- const target = holder.includes("@") ? undefined : parseBlockFragment(fragment);
18411
- const parsed = parseDispatchRef(holder);
18412
- if (target === undefined || parsed === null) {
18413
- return null;
18414
- }
18415
- const pin = target.pin === undefined ? {} : { pin: target.pin };
18416
- const artifact = parsed.artifact === undefined ? {} : { artifact: parsed.artifact };
18417
- if (parsed.kind === "ask" || parsed.kind === "comment" || parsed.kind === "message" && target.pin === undefined) {
18418
- return {
18419
- owner: parsed.owner,
18420
- kind: "block",
18421
- id: parsed.id,
18422
- block: target.block,
18423
- item: { kind: parsed.kind, id: parsed.id },
18424
- ...artifact,
18425
- ...pin
18426
- };
18427
- }
18428
- if (parsed.kind !== "spec" && parsed.kind !== "artifact") {
18429
- return null;
18430
- }
18431
- return {
18432
- owner: parsed.owner,
18433
- kind: "block",
18434
- id: parsed.id,
18435
- block: target.block,
18436
- document: holder,
18437
- ...parsed.owner.kind === "project" ? { artifact: parsed.id } : {},
18438
- ...pin
18439
- };
18440
- }
18441
- function parseDispatchRef(ref) {
18442
- const hash = ref.indexOf("#");
18443
- if (hash !== -1 && ref.startsWith("b-", hash + 1)) {
18444
- return parseBlockRef(ref.slice(0, hash), ref.slice(hash + 3));
18445
- }
18446
- const projectDocument = ref.match(/^dispatch:\/\/([A-Z][A-Z0-9]{1,9})\/artifact\/([^/@]+)(?:@v(\d+))?(?:\/(ask|comment)\/([^/]+))?$/);
18447
- if (projectDocument) {
18448
- const [, project, artifact, version, targetKind, targetID] = projectDocument;
18449
- if (project === undefined || artifact === undefined || version !== undefined && Number(version) < 1) {
18450
- return null;
18451
- }
18452
- if (targetKind === undefined) {
18453
- return {
18454
- owner: { kind: "project", project },
18455
- kind: "artifact",
18456
- id: artifact,
18457
- ...version === undefined ? {} : { version: Number(version) }
18458
- };
18431
+ var KEYED_LAYER_MEMORY_MS = 5 * 60000;
18432
+ var KEYED_LAYER_SEEN = new Map;
18433
+ var KEYED_LAYER_PROBES = new Map;
18434
+ var KEY_LAYER_PROBE_MS = 5000;
18435
+ function keyedLayerMemory() {
18436
+ const wall = Date.now();
18437
+ const now = performance.now();
18438
+ const kept = {};
18439
+ for (const [origin, seen] of KEYED_LAYER_SEEN) {
18440
+ const age = now - seen;
18441
+ if (age >= 0 && age < KEYED_LAYER_MEMORY_MS) {
18442
+ kept[origin] = new Date(wall - age).toISOString();
18459
18443
  }
18460
- if (version !== undefined)
18461
- return null;
18462
- if (targetID === undefined || targetKind !== "ask" && targetKind !== "comment")
18463
- return null;
18464
- return {
18465
- owner: { kind: "project", project },
18466
- kind: targetKind,
18467
- id: targetID,
18468
- artifact
18469
- };
18470
18444
  }
18471
- const issueReference = ref.match(/^dispatch:\/\/([A-Z][A-Z0-9]{1,9}-[1-9][0-9]*)(?:\/(spec)|\/(log|activity)|\/(children)|\/artifact\/([^/@]+)(?:@v(\d+))?|\/ask\/([^/]+)|\/comment\/([^/]+)|\/message\/([^/]+))?$/);
18472
- if (!issueReference)
18473
- return null;
18474
- const [, issue, spec, log, children, artifact, version, ask, comment, message] = issueReference;
18475
- if (!issue || version !== undefined && Number(version) < 1)
18476
- return null;
18477
- const owner = { kind: "issue", issue };
18478
- if (spec)
18479
- return { owner, kind: "spec", id: spec };
18480
- if (log)
18481
- return { owner, kind: "log", id: log };
18482
- if (children)
18483
- return { owner, kind: "children", id: children };
18484
- if (artifact) {
18485
- return {
18486
- owner,
18487
- kind: "artifact",
18488
- id: artifact,
18489
- ...version === undefined ? {} : { version: Number(version) }
18490
- };
18445
+ return kept;
18446
+ }
18447
+ function rememberKeyedLayer(saved) {
18448
+ if (typeof saved !== "object" || saved === null)
18449
+ return;
18450
+ const wall = Date.now();
18451
+ const now = performance.now();
18452
+ for (const [origin, at] of Object.entries(saved)) {
18453
+ if (typeof at !== "string")
18454
+ continue;
18455
+ const age = wall - Date.parse(at);
18456
+ if (!(age >= 0 && age < KEYED_LAYER_MEMORY_MS))
18457
+ continue;
18458
+ const seen = now - age;
18459
+ const known = KEYED_LAYER_SEEN.get(origin);
18460
+ if (known === undefined || known < seen)
18461
+ KEYED_LAYER_SEEN.set(origin, seen);
18491
18462
  }
18492
- if (ask)
18493
- return { owner, kind: "ask", id: ask };
18494
- if (comment)
18495
- return { owner, kind: "comment", id: comment };
18496
- if (message)
18497
- return { owner, kind: "message", id: message };
18498
- return { owner, kind: "issue", id: issue };
18499
18463
  }
18500
-
18501
- // ../envoy-client/src/dispatch-picture-tools.ts
18502
- import { basename, resolve as resolvePath } from "path";
18503
-
18504
- // ../../node_modules/.bun/@toon-format+toon@4.1.1/node_modules/@toon-format/toon/dist/index.mjs
18505
- var NULL_LITERAL = "null";
18506
- var DELIMITERS = {
18507
- comma: ",",
18508
- tab: "\t",
18509
- pipe: "|"
18510
- };
18511
- var DEFAULT_DELIMITER = DELIMITERS.comma;
18512
- function escapeString(value) {
18513
- return value.replace(/\\/g, `\\\\`).replace(/"/g, `\\"`).replace(/\n/g, `\\n`).replace(/\r/g, `\\r`).replace(/\t/g, `\\t`).replace(/[\u0000-\u001F]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
18464
+ function keyEchoed(response, key) {
18465
+ const echoed = response.headers.get(IDEMPOTENCY_KEY_HEADER)?.trim() ?? "";
18466
+ return echoed.replace(/^"(.*)"$/, "$1") === key;
18514
18467
  }
18515
- var FETCH_LINE = Symbol("fetch-line");
18516
- function isBooleanOrNullLiteral(token) {
18517
- return token === "true" || token === "false" || token === "null";
18468
+ var STREAMED_BODY_MIN = 1 << 20;
18469
+ var STREAMED_BODY_CHUNK = 64 << 10;
18470
+ function attemptBody(body, headers, progress) {
18471
+ const bytes = typeof body.content === "string" ? new TextEncoder().encode(body.content) : body.content;
18472
+ if (bytes.byteLength < STREAMED_BODY_MIN)
18473
+ return { body: body.content, headers };
18474
+ let sent = 0;
18475
+ const stream = new ReadableStream({
18476
+ pull(controller) {
18477
+ progress();
18478
+ if (sent >= bytes.byteLength) {
18479
+ controller.close();
18480
+ return;
18481
+ }
18482
+ const end = Math.min(sent + STREAMED_BODY_CHUNK, bytes.byteLength);
18483
+ controller.enqueue(bytes.subarray(sent, end));
18484
+ sent = end;
18485
+ }
18486
+ });
18487
+ return { body: stream, headers: { ...headers, "Content-Length": String(bytes.byteLength) } };
18518
18488
  }
18519
- function setOwnProperty(target, key, value) {
18520
- if (key === "__proto__") {
18521
- Object.defineProperty(target, key, {
18522
- value,
18523
- enumerable: true,
18524
- writable: true,
18525
- configurable: true
18526
- });
18527
- return;
18489
+
18490
+ class WriteAttemptSilent extends Error {
18491
+ name = "WriteAttemptSilent";
18492
+ constructor(silenceMs) {
18493
+ super(`made no progress for ${silenceMs / 1000} s, so it was cut off`);
18528
18494
  }
18529
- target[key] = value;
18530
18495
  }
18531
- var COMMENT_LINE_PATTERN = new RegExp(`(?:^\uFEFF?|\\n) *#`);
18532
- var RawString = class {
18533
- constructor(value) {
18534
- if (COMMENT_LINE_PATTERN.test(value))
18535
- throw new TypeError(`Raw string must not contain a line starting with "#": ${JSON.stringify(value)}`);
18536
- this.value = value;
18496
+ var NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
18497
+ async function writeAnswer(response, key) {
18498
+ const echoed = keyEchoed(response, key);
18499
+ if (response.ok || NULL_BODY_STATUSES.has(response.status)) {
18500
+ return { response, again: false, reached: false, running: false, echoed, unjudged: false };
18537
18501
  }
18538
- };
18539
- function isRawString(value) {
18540
- return value instanceof RawString;
18502
+ const { status } = response;
18503
+ const text = await response.text();
18504
+ let shape = {};
18505
+ if (isJson(response)) {
18506
+ try {
18507
+ shape = asErrorShape(JSON.parse(text));
18508
+ } catch {
18509
+ shape = {};
18510
+ }
18511
+ }
18512
+ const again = retriesUnderKey(status, shape.code);
18513
+ const running = again && status === 409;
18514
+ return {
18515
+ response: new Response(text, {
18516
+ status,
18517
+ statusText: response.statusText,
18518
+ headers: response.headers
18519
+ }),
18520
+ again,
18521
+ reached: status >= 500 || running,
18522
+ running,
18523
+ echoed,
18524
+ unjudged: !echoed && typeof shape.error === "string"
18525
+ };
18541
18526
  }
18542
- var SURROGATE_PATTERN = /[\uD800-\uDFFF]/;
18543
- function normalizeValue(value) {
18544
- if (value === null)
18545
- return null;
18546
- if (isRawString(value))
18547
- return value;
18548
- if (typeof value === "object" && value !== null && "toJSON" in value && typeof value.toJSON === "function") {
18549
- const next = value.toJSON();
18550
- if (next !== value)
18551
- return normalizeValue(next);
18527
+ function whyNotAPage(answer) {
18528
+ if (typeof answer === "string") {
18529
+ return `text that is not a JSON page, ${GATEWAY_PAGE}, so a retry may succeed.`;
18552
18530
  }
18553
- if (typeof value === "string") {
18554
- assertNoLoneSurrogate(value, "string value");
18555
- return value;
18531
+ let what;
18532
+ if (Array.isArray(answer)) {
18533
+ what = `a bare array of ${answer.length} entries, the unpaged listing, which means that Dispatch ` + "is older than sjawhar/legion#1612 or that change has regressed";
18534
+ } else if (answer === null || typeof answer !== "object") {
18535
+ what = answer === null ? "null" : `a ${typeof answer}`;
18536
+ } else {
18537
+ const fields = answer;
18538
+ const lacking = [
18539
+ ...Array.isArray(fields.issues) ? [] : ["an issues array"],
18540
+ ...["total", "limit", "offset"].filter((name) => typeof fields[name] !== "number").map((name) => `a numeric ${name}`)
18541
+ ];
18542
+ if (lacking.length === 0)
18543
+ return;
18544
+ what = `an object without ${lacking.join(" or ")}`;
18556
18545
  }
18557
- if (typeof value === "boolean")
18558
- return value;
18559
- if (typeof value === "number") {
18560
- if (Object.is(value, -0))
18561
- return 0;
18562
- if (!Number.isFinite(value))
18563
- return null;
18564
- return value;
18546
+ return `${what}. Retrying will not help: the same request gets the same answer until that ` + "Dispatch is upgraded or fixed.";
18547
+ }
18548
+ function whyNotAnArray(answer) {
18549
+ if (typeof answer === "string")
18550
+ return `text that is not JSON, ${GATEWAY_PAGE}, so a retry may succeed`;
18551
+ if (answer === null)
18552
+ return "null";
18553
+ if (typeof answer !== "object")
18554
+ return `a ${typeof answer}`;
18555
+ if ("issues" in answer && Array.isArray(answer.issues)) {
18556
+ return "a page, so this Dispatch pages a request that carries no limit and no offset";
18565
18557
  }
18566
- if (typeof value === "bigint") {
18567
- if (value >= Number.MIN_SAFE_INTEGER && value <= Number.MAX_SAFE_INTEGER)
18568
- return Number(value);
18569
- return value.toString();
18570
- }
18571
- if (value instanceof Date)
18572
- return value.toISOString();
18573
- if (Array.isArray(value))
18574
- return value.map(normalizeValue);
18575
- if (value instanceof Set)
18576
- return Array.from(value).map(normalizeValue);
18577
- if (value instanceof Map)
18578
- return Object.fromEntries(Array.from(value, ([k, v]) => [String(k), normalizeValue(v)]));
18579
- if (isPlainObject2(value)) {
18580
- const encodedValues = {};
18581
- for (const key in value)
18582
- if (Object.hasOwn(value, key)) {
18583
- assertNoLoneSurrogate(key, "object key");
18584
- setOwnProperty(encodedValues, key, normalizeValue(value[key]));
18585
- }
18586
- return encodedValues;
18587
- }
18588
- return null;
18558
+ return "an object that is not the listing";
18589
18559
  }
18590
- function assertNoLoneSurrogate(value, context) {
18591
- if (!SURROGATE_PATTERN.test(value))
18592
- return;
18593
- for (let index = 0;index < value.length; index++) {
18594
- const code = value.charCodeAt(index);
18595
- if (code < 55296 || code > 57343)
18596
- continue;
18597
- const isHighSurrogate = code <= 56319;
18598
- const next = value.charCodeAt(index + 1);
18599
- if (isHighSurrogate && next >= 56320 && next <= 57343) {
18600
- index++;
18601
- continue;
18602
- }
18603
- throw new TypeError(`Cannot encode ${context} containing an unpaired surrogate U+${code.toString(16).toUpperCase()} at index ${index}`);
18560
+ var GATEWAY_PAGE = "which looks like a proxy or gateway page rather than Dispatch's own answer";
18561
+ function gatewayAdvice(method, status) {
18562
+ if (!transientStatus(status)) {
18563
+ return "a retry gets the same answer until the Dispatch URL, or whatever answers in its place, is fixed";
18604
18564
  }
18565
+ if (method === "GET")
18566
+ return "a retry may succeed";
18567
+ return reachesDispatch(status) ? "the write may or may not have reached Dispatch: check whether it took effect before retrying it" : "the write did not reach Dispatch, and a retry may succeed";
18605
18568
  }
18606
- function isJsonPrimitive(value) {
18607
- return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
18608
- }
18609
- function isEncodablePrimitive(value) {
18610
- return isJsonPrimitive(value) || isRawString(value);
18611
- }
18612
- function isJsonArray(value) {
18613
- return Array.isArray(value);
18614
- }
18615
- function isJsonObject(value) {
18616
- return value !== null && typeof value === "object" && !Array.isArray(value) && !isRawString(value);
18617
- }
18618
- function isEmptyObject(value) {
18619
- return Object.keys(value).length === 0;
18620
- }
18621
- function isPlainObject2(value) {
18622
- if (value === null || typeof value !== "object")
18623
- return false;
18624
- const prototype = Object.getPrototypeOf(value);
18625
- return prototype === null || prototype === Object.prototype;
18626
- }
18627
- function isArrayOfPrimitives(value) {
18628
- return value.length === 0 || value.every((item) => isEncodablePrimitive(item));
18629
- }
18630
- function isArrayOfArrays(value) {
18631
- return value.length === 0 || value.every((item) => isJsonArray(item));
18632
- }
18633
- function isArrayOfObjects(value) {
18634
- return value.length === 0 || value.every((item) => isJsonObject(item));
18635
- }
18636
- var NUMERIC_LIKE_PATTERN = /^[+-]?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i;
18637
- function assertValidDelimiter(delimiter) {
18638
- if (!Object.values(DELIMITERS).includes(delimiter))
18639
- throw new TypeError(`Invalid delimiter ${JSON.stringify(delimiter)}. Valid delimiters are: comma (,), tab (\\t), pipe (|)`);
18640
- }
18641
- function isValidUnquotedKey(key) {
18642
- return /^[A-Z_][\w.]*$/i.test(key);
18643
- }
18644
- function isSafeUnquoted(value, delimiter = DEFAULT_DELIMITER) {
18645
- if (!value)
18646
- return false;
18647
- if (/^[ \t]|[ \t]$/.test(value))
18648
- return false;
18649
- if (isBooleanOrNullLiteral(value) || isNumericLike(value))
18650
- return false;
18651
- if (value.includes(":"))
18652
- return false;
18653
- if (value.includes('"') || value.includes("\\"))
18654
- return false;
18655
- if (/[[\]{}]/.test(value))
18656
- return false;
18657
- if (/[\u0000-\u001F]/.test(value))
18658
- return false;
18659
- if (value.includes(delimiter))
18660
- return false;
18661
- if (value.startsWith("-"))
18662
- return false;
18663
- if (value.startsWith("#"))
18664
- return false;
18665
- return true;
18666
- }
18667
- function isNumericLike(value) {
18668
- return NUMERIC_LIKE_PATTERN.test(value);
18669
- }
18670
- function encodePrimitive(value, delimiter) {
18671
- if (isRawString(value))
18672
- return value.value;
18673
- if (value === null)
18674
- return NULL_LITERAL;
18675
- if (typeof value === "boolean")
18676
- return String(value);
18677
- if (typeof value === "number")
18678
- return String(value);
18679
- return encodeStringLiteral(value, delimiter);
18680
- }
18681
- function encodeStringLiteral(value, delimiter = DEFAULT_DELIMITER) {
18682
- if (isSafeUnquoted(value, delimiter))
18683
- return value;
18684
- return `"${escapeString(value)}"`;
18685
- }
18686
- function encodeKey(key) {
18687
- if (isValidUnquotedKey(key))
18688
- return key;
18689
- return `"${escapeString(key)}"`;
18690
- }
18691
- function encodeAndJoinPrimitives(values, delimiter = DEFAULT_DELIMITER) {
18692
- return values.map((v) => encodePrimitive(v, delimiter)).join(delimiter);
18693
- }
18694
- function formatHeader(length, options) {
18695
- const key = options?.key;
18696
- const fields = options?.fields;
18697
- const delimiter = options?.delimiter ?? ",";
18698
- let header = "";
18699
- if (key != null)
18700
- header += encodeKey(key);
18701
- header += `[${length}${options?.keyed ? ":" : ""}${delimiter !== DEFAULT_DELIMITER ? delimiter : ""}]`;
18702
- if (fields)
18703
- header += `{${formatFieldSegment(fields, delimiter)}}`;
18704
- header += ":";
18705
- return header;
18569
+ function transientStatus(status) {
18570
+ return status >= 500 || status === 408 || status === 429;
18706
18571
  }
18707
- function formatFieldSegment(fields, delimiter) {
18708
- return fields.map((field) => encodeKey(field.name) + (field.children ? `{${formatFieldSegment(field.children, delimiter)}}` : "")).join(delimiter);
18572
+ function reachesDispatch(status) {
18573
+ return status >= 500;
18709
18574
  }
18710
- function extractTabularFields(rows) {
18711
- if (rows.length === 0)
18712
- return;
18713
- const firstKeys = Object.keys(rows[0]);
18714
- if (firstKeys.length === 0)
18715
- return;
18716
- for (const row of rows) {
18717
- if (Object.keys(row).length !== firstKeys.length)
18718
- return;
18719
- for (const key of firstKeys)
18720
- if (!Object.hasOwn(row, key))
18721
- return;
18575
+ var REDACTED = "[redacted]";
18576
+ var EXCERPT_SCAN_LIMIT = 64 * 1024;
18577
+ var BEARER_PIECE = 8;
18578
+ function redactBearer(text, bearer) {
18579
+ if (bearer === "")
18580
+ return text.slice(0, EXCERPT_SCAN_LIMIT);
18581
+ const length = Math.min(BEARER_PIECE, bearer.length);
18582
+ const scanned = text.slice(0, EXCERPT_SCAN_LIMIT + length - 1);
18583
+ const covered = new Uint8Array(scanned.length);
18584
+ const pieces = new Set;
18585
+ for (let at = 0;at + length <= bearer.length; at++)
18586
+ pieces.add(bearer.slice(at, at + length));
18587
+ for (const piece of pieces) {
18588
+ let found = scanned.indexOf(piece);
18589
+ while (found !== -1) {
18590
+ covered.fill(1, found, found + length);
18591
+ found = scanned.indexOf(piece, found + 1);
18592
+ }
18722
18593
  }
18723
- const fieldNodes = [];
18724
- for (const key of firstKeys) {
18725
- const fieldNode = classifyColumn(key, rows.map((row) => row[key]));
18726
- if (!fieldNode)
18727
- return;
18728
- fieldNodes.push(fieldNode);
18594
+ let redacted = "";
18595
+ let kept = 0;
18596
+ for (let start = covered.indexOf(1);start !== -1; start = covered.indexOf(1, kept)) {
18597
+ redacted += `${scanned.slice(kept, start)}${REDACTED}`;
18598
+ const end = covered.indexOf(0, start);
18599
+ kept = end === -1 ? scanned.length : end;
18729
18600
  }
18730
- return fieldNodes;
18731
- }
18732
- function extractKeyedTabularFields(value) {
18733
- const entryValues = Object.values(value);
18734
- if (entryValues.length < 2)
18735
- return;
18736
- if (!entryValues.every((entryValue) => isJsonObject(entryValue) && !isEmptyObject(entryValue)))
18737
- return;
18738
- return extractTabularFields(entryValues);
18739
- }
18740
- function collectRowLeaves(row, fields) {
18741
- const leaves = [];
18742
- collectLeafValues(row, fields, leaves);
18743
- return leaves;
18601
+ return `${redacted}${scanned.slice(kept, EXCERPT_SCAN_LIMIT)}`.slice(0, EXCERPT_SCAN_LIMIT);
18744
18602
  }
18745
- function classifyColumn(name, values) {
18746
- if (values.every((value) => isEncodablePrimitive(value)))
18747
- return { name };
18748
- if (!values.every((value) => isJsonObject(value) && !isEmptyObject(value)))
18749
- return;
18750
- const children = extractTabularFields(values);
18751
- if (!children)
18752
- return;
18753
- return {
18754
- name,
18755
- children
18756
- };
18603
+ function excerpt(text, token) {
18604
+ const plain = redactBearer(text, token.trim()).replace(/<(script|style)\b[^<>]*>(?:[\s\S]*?<\/\1\s*>|[\s\S]*$)/gi, " ").replace(/<[^<>]*>/g, " ");
18605
+ return textHead(plain.replace(/(\bauthorization["']?\s*[:=]\s*["']?(?:(?:bearer|basic|digest|token)\s+)?)[^\s"'<>,;]+/gi, `$1${REDACTED}`).replace(/(\bbearer\s+)[^\s"'<>,;]+/gi, `$1${REDACTED}`));
18757
18606
  }
18758
- function collectLeafValues(row, fields, leaves) {
18759
- for (const field of fields) {
18760
- const value = row[field.name];
18761
- if (field.children)
18762
- collectLeafValues(value, field.children, leaves);
18763
- else
18764
- leaves.push(value);
18607
+
18608
+ class DispatchClient {
18609
+ fetchImpl;
18610
+ writeRetry;
18611
+ #baseUrl;
18612
+ #resolvedIssues = new Map;
18613
+ #signal;
18614
+ #credential;
18615
+ #madeAt;
18616
+ constructor(baseUrl, credential, fetchImpl = fetch, signal, writeRetry = DISPATCH_WRITE_RETRY) {
18617
+ this.fetchImpl = fetchImpl;
18618
+ this.writeRetry = writeRetry;
18619
+ this.#credential = credential;
18620
+ this.#baseUrl = withoutTrailingSlashes(baseUrl);
18621
+ this.#signal = requestSignal(signal);
18622
+ this.#madeAt = this.#now();
18765
18623
  }
18766
- }
18767
- function* encodeJsonValue(value, options, depth) {
18768
- if (isEncodablePrimitive(value)) {
18769
- const encodedPrimitive = encodePrimitive(value, options.delimiter);
18770
- if (encodedPrimitive !== "")
18771
- yield encodedPrimitive;
18772
- return;
18624
+ get token() {
18625
+ return this.#credential.secret();
18773
18626
  }
18774
- if (isJsonArray(value))
18775
- yield* encodeArrayLines(undefined, value, depth, options);
18776
- else if (isJsonObject(value)) {
18777
- const keyedFields = extractKeyedTabularFields(value);
18778
- if (keyedFields) {
18779
- yield* encodeKeyedObjectLines(undefined, value, keyedFields, depth, options);
18780
- return;
18781
- }
18782
- yield* encodeObjectLines(value, depth, options);
18627
+ async issue(input) {
18628
+ const answer = await this.#jsonAnswer("POST", ["api", "v1", "issues"], input);
18629
+ return { ...answer.payload, created: answer.status === 201 };
18783
18630
  }
18784
- }
18785
- function* encodeObjectLines(value, depth, options) {
18786
- for (const [key, val] of Object.entries(value))
18787
- yield* encodeKeyValuePairLines(key, val, depth, options);
18788
- }
18789
- function* encodeKeyValuePairLines(key, value, depth, options) {
18790
- const encodedKey = encodeKey(key);
18791
- if (isEncodablePrimitive(value))
18792
- yield indentedLine(depth, `${encodedKey}: ${encodePrimitive(value, options.delimiter)}`, options.indentSize);
18793
- else if (isJsonArray(value))
18794
- yield* encodeArrayLines(key, value, depth, options);
18795
- else if (isJsonObject(value)) {
18796
- const keyedFields = extractKeyedTabularFields(value);
18797
- if (keyedFields) {
18798
- yield* encodeKeyedObjectLines(key, value, keyedFields, depth, options);
18799
- return;
18800
- }
18801
- yield indentedLine(depth, `${encodedKey}:`, options.indentSize);
18802
- if (!isEmptyObject(value))
18803
- yield* encodeObjectLines(value, depth + 1, options);
18631
+ async resolveIssue(issueReference) {
18632
+ return this.#resolveIssue(issueReference);
18804
18633
  }
18805
- }
18806
- function* encodeKeyedObjectLines(key, value, fields, depth, options) {
18807
- const entries = Object.entries(value);
18808
- yield indentedLine(depth, formatHeader(entries.length, {
18809
- key,
18810
- fields,
18811
- delimiter: options.delimiter,
18812
- keyed: true
18813
- }), options.indentSize);
18814
- yield* encodeKeyedEntryRowsLines(entries, fields, depth + 1, options);
18815
- }
18816
- function* encodeKeyedEntryRowsLines(entries, fields, depth, options) {
18817
- for (const [entryKey, entryValue] of entries) {
18818
- const leaves = collectRowLeaves(entryValue, fields);
18819
- yield indentedLine(depth, `${encodeKey(entryKey)}: ${encodeAndJoinPrimitives(leaves, options.delimiter)}`, options.indentSize);
18634
+ async listIssuePage(options, page) {
18635
+ const path = ["api", "v1", "issues"];
18636
+ const query = { ...options, limit: page.limit, offset: page.offset };
18637
+ const answer = await this.#json("GET", path, undefined, query);
18638
+ const refusal = whyNotAPage(answer);
18639
+ if (refusal === undefined)
18640
+ return answer;
18641
+ throw new Error(`GET ${this.#url(path, query)} asked for a page ({issues, total, limit, offset}) and got ` + refusal);
18820
18642
  }
18821
- }
18822
- function* encodeArrayLines(key, value, depth, options) {
18823
- if (value.length === 0) {
18824
- yield indentedLine(depth, key != null ? `${encodeKey(key)}: []` : "[]", options.indentSize);
18825
- return;
18643
+ async listAllIssues(options) {
18644
+ const path = ["api", "v1", "issues"];
18645
+ const query = { ...options };
18646
+ const answer = await this.#json("GET", path, undefined, query);
18647
+ if (Array.isArray(answer))
18648
+ return answer;
18649
+ throw new Error(`GET ${this.#url(path, query)} asked for the unpaged listing and got ${whyNotAnArray(answer)}.`);
18826
18650
  }
18827
- if (isArrayOfPrimitives(value)) {
18828
- yield indentedLine(depth, encodeInlineArrayLine(value, options.delimiter, key), options.indentSize);
18829
- return;
18651
+ async listIssueArtifacts(issue) {
18652
+ return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "artifacts"]);
18830
18653
  }
18831
- if (isArrayOfArrays(value)) {
18832
- if (value.every((arr) => isArrayOfPrimitives(arr))) {
18833
- yield* encodeArrayOfArraysAsListItemsLines(key, value, depth, options);
18834
- return;
18835
- }
18654
+ async markdownRoundTrip(markdown) {
18655
+ const answer = await this.#json("POST", ["api", "v1", "markdown", "round-trip"], { markdown });
18656
+ return answer.markdown;
18836
18657
  }
18837
- if (isArrayOfObjects(value)) {
18838
- const fields = extractTabularFields(value);
18839
- if (fields)
18840
- yield* encodeArrayOfObjectsAsTabularLines(key, value, fields, depth, options);
18841
- else
18842
- yield* encodeMixedArrayAsListItemsLines(key, value, depth, options);
18843
- return;
18658
+ async listProjectArtifacts(project, unlinked = false) {
18659
+ return this.#json("GET", ["api", "v1", "projects", project, "artifacts"], undefined, unlinked ? { unlinked: "true" } : undefined);
18844
18660
  }
18845
- yield* encodeMixedArrayAsListItemsLines(key, value, depth, options);
18846
- }
18847
- function* encodeArrayOfArraysAsListItemsLines(prefix, values, depth, options) {
18848
- yield indentedLine(depth, formatHeader(values.length, {
18849
- key: prefix,
18850
- delimiter: options.delimiter
18851
- }), options.indentSize);
18852
- for (const arr of values)
18853
- if (isArrayOfPrimitives(arr)) {
18854
- const arrayLine = encodeInlineArrayLine(arr, options.delimiter);
18855
- yield indentedListItem(depth + 1, arrayLine, options.indentSize);
18856
- }
18857
- }
18858
- function encodeInlineArrayLine(values, delimiter, prefix) {
18859
- const header = formatHeader(values.length, {
18860
- key: prefix,
18861
- delimiter
18862
- });
18863
- const joinedValue = encodeAndJoinPrimitives(values, delimiter);
18864
- if (values.length === 0)
18865
- return header;
18866
- return `${header} ${joinedValue}`;
18867
- }
18868
- function* encodeArrayOfObjectsAsTabularLines(prefix, rows, fields, depth, options) {
18869
- yield indentedLine(depth, formatHeader(rows.length, {
18870
- key: prefix,
18871
- fields,
18872
- delimiter: options.delimiter
18873
- }), options.indentSize);
18874
- yield* writeTabularRowsLines(rows, fields, depth + 1, options);
18875
- }
18876
- function* writeTabularRowsLines(rows, fields, depth, options) {
18877
- for (const row of rows)
18878
- yield indentedLine(depth, encodeAndJoinPrimitives(collectRowLeaves(row, fields), options.delimiter), options.indentSize);
18879
- }
18880
- function* encodeMixedArrayAsListItemsLines(prefix, items, depth, options) {
18881
- yield indentedLine(depth, formatHeader(items.length, {
18882
- key: prefix,
18883
- delimiter: options.delimiter
18884
- }), options.indentSize);
18885
- for (const item of items)
18886
- yield* encodeListItemValueLines(item, depth + 1, options);
18887
- }
18888
- function* encodeObjectAsListItemLines(obj, depth, options) {
18889
- if (isEmptyObject(obj)) {
18890
- yield indentedLine(depth, "-", options.indentSize);
18891
- return;
18661
+ async projectArtifact(project, input, key) {
18662
+ return this.#upload(["api", "v1", "projects", project, "artifacts"], input, key);
18892
18663
  }
18893
- const entries = Object.entries(obj);
18894
- const [firstKey, firstValue] = entries[0];
18895
- const restEntries = entries.slice(1);
18896
- if (isJsonArray(firstValue) && isArrayOfObjects(firstValue)) {
18897
- const fields = extractTabularFields(firstValue);
18898
- if (fields) {
18899
- yield indentedListItem(depth, formatHeader(firstValue.length, {
18900
- key: firstKey,
18901
- fields,
18902
- delimiter: options.delimiter
18903
- }), options.indentSize);
18904
- yield* writeTabularRowsLines(firstValue, fields, depth + 2, options);
18905
- if (restEntries.length > 0)
18906
- yield* encodeObjectLines(Object.fromEntries(restEntries), depth + 1, options);
18907
- return;
18908
- }
18664
+ async getProjectArtifact(project, slug) {
18665
+ return this.#json("GET", ["api", "v1", "projects", project, "artifacts", slug]);
18909
18666
  }
18910
- if (isJsonObject(firstValue)) {
18911
- const keyedFields = extractKeyedTabularFields(firstValue);
18912
- if (keyedFields) {
18913
- const keyedEntries = Object.entries(firstValue);
18914
- yield indentedListItem(depth, formatHeader(keyedEntries.length, {
18915
- key: firstKey,
18916
- fields: keyedFields,
18917
- delimiter: options.delimiter,
18918
- keyed: true
18919
- }), options.indentSize);
18920
- yield* encodeKeyedEntryRowsLines(keyedEntries, keyedFields, depth + 2, options);
18921
- if (restEntries.length > 0)
18922
- yield* encodeObjectLines(Object.fromEntries(restEntries), depth + 1, options);
18923
- return;
18924
- }
18667
+ async agentArtifact(sessionId, input) {
18668
+ return this.#upload(["api", "v1", "agents", sessionId, "artifacts"], input);
18925
18669
  }
18926
- const encodedKey = encodeKey(firstKey);
18927
- if (isEncodablePrimitive(firstValue))
18928
- yield indentedListItem(depth, `${encodedKey}: ${encodePrimitive(firstValue, options.delimiter)}`, options.indentSize);
18929
- else if (isJsonArray(firstValue))
18930
- if (firstValue.length === 0)
18931
- yield indentedListItem(depth, `${encodedKey}: []`, options.indentSize);
18932
- else if (isArrayOfPrimitives(firstValue))
18933
- yield indentedListItem(depth, `${encodedKey}${encodeInlineArrayLine(firstValue, options.delimiter)}`, options.indentSize);
18934
- else {
18935
- yield indentedListItem(depth, `${encodedKey}${formatHeader(firstValue.length, { delimiter: options.delimiter })}`, options.indentSize);
18936
- for (const item of firstValue)
18937
- yield* encodeListItemValueLines(item, depth + 2, options);
18938
- }
18939
- else if (isJsonObject(firstValue)) {
18940
- yield indentedListItem(depth, `${encodedKey}:`, options.indentSize);
18941
- if (!isEmptyObject(firstValue))
18942
- yield* encodeObjectLines(firstValue, depth + 2, options);
18670
+ async getAgentArtifact(sessionId, slug) {
18671
+ return this.#json("GET", ["api", "v1", "agents", sessionId, "artifacts", slug]);
18943
18672
  }
18944
- if (restEntries.length > 0)
18945
- yield* encodeObjectLines(Object.fromEntries(restEntries), depth + 1, options);
18946
- }
18947
- function* encodeListItemValueLines(value, depth, options) {
18948
- if (isEncodablePrimitive(value))
18949
- yield indentedListItem(depth, encodePrimitive(value, options.delimiter), options.indentSize);
18950
- else if (isJsonArray(value))
18951
- if (isArrayOfPrimitives(value))
18952
- yield indentedListItem(depth, encodeInlineArrayLine(value, options.delimiter), options.indentSize);
18953
- else {
18954
- yield indentedListItem(depth, formatHeader(value.length, { delimiter: options.delimiter }), options.indentSize);
18955
- for (const item of value)
18956
- yield* encodeListItemValueLines(item, depth + 1, options);
18957
- }
18958
- else if (isJsonObject(value))
18959
- yield* encodeObjectAsListItemLines(value, depth, options);
18960
- }
18961
- function indentedLine(depth, content, indentSize) {
18962
- return " ".repeat(indentSize * depth) + content;
18963
- }
18964
- function indentedListItem(depth, content, indentSize) {
18965
- return indentedLine(depth, "- " + content, indentSize);
18966
- }
18967
- function applyReplacer(root, replacer) {
18968
- const replacedRoot = replacer("", root, []);
18969
- if (replacedRoot === undefined)
18970
- return transformChildren(root, replacer, []);
18971
- return transformReplaced(root, replacedRoot, replacer, []);
18972
- }
18973
- function transformReplaced(original, replaced, replacer, path) {
18974
- if (isRawString(replaced) && !isEncodablePrimitive(original))
18975
- return transformChildren(original, replacer, path);
18976
- return transformChildren(normalizeValue(replaced), replacer, path);
18977
- }
18978
- function transformChildren(value, replacer, path) {
18979
- if (isJsonObject(value))
18980
- return transformObject(value, replacer, path);
18981
- if (isJsonArray(value))
18982
- return transformArray(value, replacer, path);
18983
- return value;
18984
- }
18985
- function transformObject(obj, replacer, path) {
18986
- const result = {};
18987
- for (const [key, value] of Object.entries(obj)) {
18988
- const childPath = [...path, key];
18989
- const replacedValue = replacer(key, value, childPath);
18990
- if (replacedValue === undefined)
18991
- continue;
18992
- setOwnProperty(result, key, transformReplaced(value, replacedValue, replacer, childPath));
18673
+ async getIssueArtifact(issue, slug) {
18674
+ return this.#json("GET", [
18675
+ "api",
18676
+ "v1",
18677
+ "issues",
18678
+ await this.#resolveIssue(issue),
18679
+ "artifacts",
18680
+ slug
18681
+ ]);
18993
18682
  }
18994
- return result;
18995
- }
18996
- function transformArray(arr, replacer, path) {
18997
- const result = [];
18998
- for (let i = 0;i < arr.length; i++) {
18999
- const value = arr[i];
19000
- const childPath = [...path, i];
19001
- const replacedValue = replacer(String(i), value, childPath);
19002
- if (replacedValue === undefined)
19003
- continue;
19004
- result.push(transformReplaced(value, replacedValue, replacer, childPath));
18683
+ async search(query, options = {}) {
18684
+ const request = { q: query, ...options };
18685
+ const path = everyBuildReadsSearch(request) ? ["api", "v1", "search"] : ["api", "v1", "search", "results"];
18686
+ return this.#json("GET", path, undefined, request);
19005
18687
  }
19006
- return result;
19007
- }
19008
- function encode3(input, options) {
19009
- return Array.from(encodeLines(input, options)).join(`
19010
- `);
19011
- }
19012
- function encodeLines(input, options) {
19013
- const normalizedValue = normalizeValue(input);
19014
- const resolvedOptions = resolveOptions(options);
19015
- return encodeJsonValue(resolvedOptions.replacer ? applyReplacer(normalizedValue, resolvedOptions.replacer) : normalizedValue, resolvedOptions, 0);
19016
- }
19017
- function resolveOptions(options) {
19018
- const delimiter = options?.delimiter ?? DEFAULT_DELIMITER;
19019
- assertValidDelimiter(delimiter);
19020
- return {
19021
- indentSize: options?.indentSize ?? options?.indent ?? 2,
19022
- delimiter,
19023
- replacer: options?.replacer
19024
- };
19025
- }
19026
-
19027
- // ../envoy-client/src/ask-answer.ts
19028
- var HEAD_LENGTH = 120;
19029
- function textHead(text, length = HEAD_LENGTH) {
19030
- const flat = text.replace(/\s+/g, " ").trim();
19031
- return flat.length > length ? `${flat.slice(0, length)}\u2026` : flat;
19032
- }
19033
- var QUESTION_HEAD = 200;
19034
- var DISPATCH_WORDS_LABEL = "Dispatch's words:";
19035
- function dispatchWordsText(words, render) {
19036
- if (words === null || words === undefined || words === "")
19037
- return;
19038
- return `${DISPATCH_WORDS_LABEL} ${render === undefined ? words : render(words)}`;
19039
- }
19040
- function askAnswerText(answer) {
19041
- if (answer === null || answer === undefined)
19042
- return "";
19043
- const selected = (answer.selected ?? []).join(", ");
19044
- const text = answer.text ?? "";
19045
- if (text === "")
19046
- return selected;
19047
- if (selected === "")
19048
- return text;
19049
- return `${selected} - ${text}`;
19050
- }
19051
-
19052
- // ../contracts/src/trailing-slash.ts
19053
- function withoutTrailingSlashes(url) {
19054
- let end = url.length;
19055
- while (end > 0 && url[end - 1] === "/")
19056
- end -= 1;
19057
- return url.slice(0, end);
19058
- }
19059
-
19060
- // ../envoy-client/src/dispatch-http.ts
19061
- class DispatchServiceError extends Error {
19062
- code;
19063
- status;
19064
- candidates;
19065
- current;
19066
- mismatches;
19067
- name = "DispatchServiceError";
19068
- fromDispatch = true;
19069
- constructor(code, status, message, candidates, current, mismatches) {
19070
- super(message);
19071
- this.code = code;
19072
- this.status = status;
19073
- this.candidates = candidates;
19074
- this.current = current;
19075
- this.mismatches = mismatches;
18688
+ async related(project, input) {
18689
+ return this.#json("POST", ["api", "v1", "projects", project, "related"], input);
19076
18690
  }
19077
- }
19078
-
19079
- class DispatchGatewayError extends DispatchServiceError {
19080
- answer;
19081
- advice;
19082
- fromDispatch = false;
19083
- transient;
19084
- mayHaveReachedDispatch;
19085
- constructor(status, answer, advice, message = `${answer}, so ${advice}.`) {
19086
- super(`HTTP_${status}`, status, message);
19087
- this.answer = answer;
19088
- this.advice = advice;
19089
- this.transient = transientStatus(status);
19090
- this.mayHaveReachedDispatch = reachesDispatch(status);
18691
+ async getIssue(issue) {
18692
+ return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue)]);
19091
18693
  }
19092
- }
19093
-
19094
- class DispatchWriteUnsettledError extends Error {
19095
- last;
19096
- attempts;
19097
- name = "DispatchWriteUnsettledError";
19098
- constructor(last, attempts, unanswered, keyed = false) {
19099
- let answer;
19100
- let why = "an earlier attempt of the write may have reached Dispatch";
19101
- if (last instanceof DispatchGatewayError) {
19102
- answer = last.answer;
19103
- } else if (last instanceof DispatchServiceError && last.code === IDEMPOTENCY_KEY_IN_FLIGHT) {
19104
- answer = last.code;
19105
- why = "Dispatch was still running an earlier attempt of the write";
19106
- } else if (last instanceof DispatchServiceError) {
19107
- answer = `${last.code}: ${last.message}`;
19108
- } else {
19109
- answer = unanswered ?? last.message;
19110
- why = "an attempt of the write may have reached Dispatch";
19111
- }
19112
- const tried = attempts === 1 ? "its only attempt" : `the last of ${attempts} attempts`;
19113
- const next = keyed ? ". Dispatch finishes an attempt it received whatever this command does, so read the " + "write back before you send it again: a new command sends it under a new key." : ": check whether it did before retrying it.";
19114
- super(`${answer} (${tried}), and ${why}, so it may or may not have taken effect${next}`, {
19115
- cause: last
19116
- });
19117
- this.last = last;
19118
- this.attempts = attempts;
18694
+ async updateIssue(issue, input) {
18695
+ return this.#json("PATCH", ["api", "v1", "issues", await this.#resolveIssue(issue)], input);
19119
18696
  }
19120
- }
19121
-
19122
- class DispatchWriteLandedError extends Error {
19123
- code;
19124
- status;
19125
- name = "DispatchWriteLandedError";
19126
- constructor(code, status, method, url) {
19127
- const lost = code === IDEMPOTENCY_ANSWER_NOT_KEPT ? "Dispatch kept no copy of its answer, which was too large" : "its answer was lost on the way back";
19128
- super(`${method} ${url} was made, but ${lost} (${code}), so this command cannot print what it ` + "made: read it back with `dispatch read`, or with the matching list for something it created.");
19129
- this.code = code;
19130
- this.status = status;
18697
+ async claimIssue(issue, input = {}) {
18698
+ return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "claim"], input);
19131
18699
  }
19132
- }
19133
- function asErrorShape(value) {
19134
- return typeof value === "object" && value !== null ? value : {};
19135
- }
19136
- function isJson(response) {
19137
- return response.headers.get("content-type")?.includes("application/json") ?? false;
19138
- }
19139
- function isNoRoute(error) {
19140
- return error instanceof DispatchServiceError && error.status === 404 && error.code === "NOT_FOUND" && error.message.startsWith("no route for ");
19141
- }
19142
- var ISSUE_EVENTS_PAGE_MAX = 200;
19143
- var DISPATCH_TOOL_DEADLINE_MS = 60000;
19144
- function requestSignal(signal) {
19145
- const deadline = AbortSignal.timeout(DISPATCH_TOOL_DEADLINE_MS);
19146
- return signal === undefined ? deadline : AbortSignal.any([signal, deadline]);
19147
- }
19148
- var DISPATCH_WRITE_RETRY = {
19149
- pausesMs: [1000, 2000, 4000, 8000],
19150
- withinMs: 30000,
19151
- silenceMs: 20000,
19152
- inFlightPauseMs: 3000,
19153
- inFlightWithinMs: 55000
19154
- };
19155
- function pauseFor(ms, signal) {
19156
- const { promise, resolve, reject } = Promise.withResolvers();
19157
- if (signal.aborted) {
19158
- reject(signal.reason);
19159
- return promise;
18700
+ async releaseIssueClaim(issue, input = {}) {
18701
+ return this.#json("DELETE", ["api", "v1", "issues", await this.#resolveIssue(issue), "claim"], input);
19160
18702
  }
19161
- const stop = () => {
19162
- clearTimeout(timer);
19163
- reject(signal.reason);
19164
- };
19165
- const timer = setTimeout(() => {
19166
- signal.removeEventListener("abort", stop);
19167
- resolve();
19168
- }, ms);
19169
- signal.addEventListener("abort", stop, { once: true });
19170
- return promise;
19171
- }
19172
- function retryAfterMs(response) {
19173
- const value = response.headers.get("Retry-After")?.trim() ?? "";
19174
- if (/^\d+$/.test(value))
19175
- return Number(value) * 1000;
19176
- const at = Date.parse(value);
19177
- return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
19178
- }
19179
- var KEYED_LAYER_MEMORY_MS = 5 * 60000;
19180
- var KEYED_LAYER_SEEN = new Map;
19181
- var KEYED_LAYER_PROBES = new Map;
19182
- var KEY_LAYER_PROBE_MS = 5000;
19183
- function keyedLayerMemory() {
19184
- const wall = Date.now();
19185
- const now = performance.now();
19186
- const kept = {};
19187
- for (const [origin, seen] of KEYED_LAYER_SEEN) {
19188
- const age = now - seen;
19189
- if (age >= 0 && age < KEYED_LAYER_MEMORY_MS) {
19190
- kept[origin] = new Date(wall - age).toISOString();
18703
+ async getIssueEvents(issue, after = 0, limit = ISSUE_EVENTS_PAGE_MAX) {
18704
+ return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "events"], undefined, { after, limit });
18705
+ }
18706
+ async read(issueReference, options = {}) {
18707
+ const issueKey = await this.#resolveIssue(issueReference);
18708
+ const issue = await this.getIssue(issueKey);
18709
+ const requested = options.events;
18710
+ const count = requested === undefined ? DEFAULT_ISSUE_READ_EVENTS : requested === "all" ? issue.last_seq : Math.min(requested, issue.last_seq);
18711
+ const events = [];
18712
+ let after = Math.max(0, issue.last_seq - count);
18713
+ while (events.length < count) {
18714
+ const limit = Math.min(ISSUE_EVENTS_PAGE_MAX, count - events.length);
18715
+ const page = await this.getIssueEvents(issueKey, after, limit);
18716
+ events.push(...page);
18717
+ const last = page.at(-1);
18718
+ if (page.length < limit || last === undefined || events.length >= count)
18719
+ break;
18720
+ if (last.seq <= after) {
18721
+ throw new Error(`GET /api/v1/issues/${issueKey}/events?after=${after} answered no event after seq ${after}`);
18722
+ }
18723
+ after = last.seq;
19191
18724
  }
18725
+ return { issue, events };
19192
18726
  }
19193
- return kept;
19194
- }
19195
- function rememberKeyedLayer(saved) {
19196
- if (typeof saved !== "object" || saved === null)
19197
- return;
19198
- const wall = Date.now();
19199
- const now = performance.now();
19200
- for (const [origin, at] of Object.entries(saved)) {
19201
- if (typeof at !== "string")
19202
- continue;
19203
- const age = wall - Date.parse(at);
19204
- if (!(age >= 0 && age < KEYED_LAYER_MEMORY_MS))
19205
- continue;
19206
- const seen = now - age;
19207
- const known = KEYED_LAYER_SEEN.get(origin);
19208
- if (known === undefined || known < seen)
19209
- KEYED_LAYER_SEEN.set(origin, seen);
19210
- }
19211
- }
19212
- function keyEchoed(response, key) {
19213
- const echoed = response.headers.get(IDEMPOTENCY_KEY_HEADER)?.trim() ?? "";
19214
- return echoed.replace(/^"(.*)"$/, "$1") === key;
19215
- }
19216
- var STREAMED_BODY_MIN = 1 << 20;
19217
- var STREAMED_BODY_CHUNK = 64 << 10;
19218
- function attemptBody(body, headers, progress) {
19219
- const bytes = typeof body.content === "string" ? new TextEncoder().encode(body.content) : body.content;
19220
- if (bytes.byteLength < STREAMED_BODY_MIN)
19221
- return { body: body.content, headers };
19222
- let sent = 0;
19223
- const stream = new ReadableStream({
19224
- pull(controller) {
19225
- progress();
19226
- if (sent >= bytes.byteLength) {
19227
- controller.close();
19228
- return;
19229
- }
19230
- const end = Math.min(sent + STREAMED_BODY_CHUNK, bytes.byteLength);
19231
- controller.enqueue(bytes.subarray(sent, end));
19232
- sent = end;
19233
- }
19234
- });
19235
- return { body: stream, headers: { ...headers, "Content-Length": String(bytes.byteLength) } };
19236
- }
19237
-
19238
- class WriteAttemptSilent extends Error {
19239
- name = "WriteAttemptSilent";
19240
- constructor(silenceMs) {
19241
- super(`made no progress for ${silenceMs / 1000} s, so it was cut off`);
19242
- }
19243
- }
19244
- var NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
19245
- async function writeAnswer(response, key) {
19246
- const echoed = keyEchoed(response, key);
19247
- if (response.ok || NULL_BODY_STATUSES.has(response.status)) {
19248
- return { response, again: false, reached: false, running: false, echoed, unjudged: false };
19249
- }
19250
- const { status } = response;
19251
- const text = await response.text();
19252
- let shape = {};
19253
- if (isJson(response)) {
19254
- try {
19255
- shape = asErrorShape(JSON.parse(text));
19256
- } catch {
19257
- shape = {};
19258
- }
19259
- }
19260
- const again = retriesUnderKey(status, shape.code);
19261
- const running = again && status === 409;
19262
- return {
19263
- response: new Response(text, {
19264
- status,
19265
- statusText: response.statusText,
19266
- headers: response.headers
19267
- }),
19268
- again,
19269
- reached: status >= 500 || running,
19270
- running,
19271
- echoed,
19272
- unjudged: !echoed && typeof shape.error === "string"
19273
- };
19274
- }
19275
- function whyNotAPage(answer) {
19276
- if (typeof answer === "string") {
19277
- return `text that is not a JSON page, ${GATEWAY_PAGE}, so a retry may succeed.`;
19278
- }
19279
- let what;
19280
- if (Array.isArray(answer)) {
19281
- what = `a bare array of ${answer.length} entries, the unpaged listing, which means that Dispatch ` + "is older than sjawhar/legion#1612 or that change has regressed";
19282
- } else if (answer === null || typeof answer !== "object") {
19283
- what = answer === null ? "null" : `a ${typeof answer}`;
19284
- } else {
19285
- const fields = answer;
19286
- const lacking = [
19287
- ...Array.isArray(fields.issues) ? [] : ["an issues array"],
19288
- ...["total", "limit", "offset"].filter((name) => typeof fields[name] !== "number").map((name) => `a numeric ${name}`)
19289
- ];
19290
- if (lacking.length === 0)
19291
- return;
19292
- what = `an object without ${lacking.join(" or ")}`;
19293
- }
19294
- return `${what}. Retrying will not help: the same request gets the same answer until that ` + "Dispatch is upgraded or fixed.";
19295
- }
19296
- function whyNotAnArray(answer) {
19297
- if (typeof answer === "string")
19298
- return `text that is not JSON, ${GATEWAY_PAGE}, so a retry may succeed`;
19299
- if (answer === null)
19300
- return "null";
19301
- if (typeof answer !== "object")
19302
- return `a ${typeof answer}`;
19303
- if ("issues" in answer && Array.isArray(answer.issues)) {
19304
- return "a page, so this Dispatch pages a request that carries no limit and no offset";
19305
- }
19306
- return "an object that is not the listing";
19307
- }
19308
- var GATEWAY_PAGE = "which looks like a proxy or gateway page rather than Dispatch's own answer";
19309
- function gatewayAdvice(method, status) {
19310
- if (!transientStatus(status)) {
19311
- return "a retry gets the same answer until the Dispatch URL, or whatever answers in its place, is fixed";
19312
- }
19313
- if (method === "GET")
19314
- return "a retry may succeed";
19315
- return reachesDispatch(status) ? "the write may or may not have reached Dispatch: check whether it took effect before retrying it" : "the write did not reach Dispatch, and a retry may succeed";
19316
- }
19317
- function transientStatus(status) {
19318
- return status >= 500 || status === 408 || status === 429;
19319
- }
19320
- function reachesDispatch(status) {
19321
- return status >= 500;
19322
- }
19323
- var REDACTED = "[redacted]";
19324
- var EXCERPT_SCAN_LIMIT = 64 * 1024;
19325
- var BEARER_PIECE = 8;
19326
- function redactBearer(text, bearer) {
19327
- if (bearer === "")
19328
- return text.slice(0, EXCERPT_SCAN_LIMIT);
19329
- const length = Math.min(BEARER_PIECE, bearer.length);
19330
- const scanned = text.slice(0, EXCERPT_SCAN_LIMIT + length - 1);
19331
- const covered = new Uint8Array(scanned.length);
19332
- const pieces = new Set;
19333
- for (let at = 0;at + length <= bearer.length; at++)
19334
- pieces.add(bearer.slice(at, at + length));
19335
- for (const piece of pieces) {
19336
- let found = scanned.indexOf(piece);
19337
- while (found !== -1) {
19338
- covered.fill(1, found, found + length);
19339
- found = scanned.indexOf(piece, found + 1);
19340
- }
19341
- }
19342
- let redacted = "";
19343
- let kept = 0;
19344
- for (let start = covered.indexOf(1);start !== -1; start = covered.indexOf(1, kept)) {
19345
- redacted += `${scanned.slice(kept, start)}${REDACTED}`;
19346
- const end = covered.indexOf(0, start);
19347
- kept = end === -1 ? scanned.length : end;
19348
- }
19349
- return `${redacted}${scanned.slice(kept, EXCERPT_SCAN_LIMIT)}`.slice(0, EXCERPT_SCAN_LIMIT);
19350
- }
19351
- function excerpt(text, token) {
19352
- const plain = redactBearer(text, token.trim()).replace(/<(script|style)\b[^<>]*>(?:[\s\S]*?<\/\1\s*>|[\s\S]*$)/gi, " ").replace(/<[^<>]*>/g, " ");
19353
- return textHead(plain.replace(/(\bauthorization["']?\s*[:=]\s*["']?(?:(?:bearer|basic|digest|token)\s+)?)[^\s"'<>,;]+/gi, `$1${REDACTED}`).replace(/(\bbearer\s+)[^\s"'<>,;]+/gi, `$1${REDACTED}`));
19354
- }
19355
-
19356
- class DispatchClient {
19357
- fetchImpl;
19358
- writeRetry;
19359
- #baseUrl;
19360
- #resolvedIssues = new Map;
19361
- #signal;
19362
- #credential;
19363
- #madeAt;
19364
- constructor(baseUrl, credential, fetchImpl = fetch, signal, writeRetry = DISPATCH_WRITE_RETRY) {
19365
- this.fetchImpl = fetchImpl;
19366
- this.writeRetry = writeRetry;
19367
- this.#credential = credential;
19368
- this.#baseUrl = withoutTrailingSlashes(baseUrl);
19369
- this.#signal = requestSignal(signal);
19370
- this.#madeAt = this.#now();
19371
- }
19372
- get token() {
19373
- return this.#credential.secret();
19374
- }
19375
- async issue(input) {
19376
- const answer = await this.#jsonAnswer("POST", ["api", "v1", "issues"], input);
19377
- return { ...answer.payload, created: answer.status === 201 };
19378
- }
19379
- async resolveIssue(issueReference) {
19380
- return this.#resolveIssue(issueReference);
19381
- }
19382
- async listIssuePage(options, page) {
19383
- const path = ["api", "v1", "issues"];
19384
- const query = { ...options, limit: page.limit, offset: page.offset };
19385
- const answer = await this.#json("GET", path, undefined, query);
19386
- const refusal = whyNotAPage(answer);
19387
- if (refusal === undefined)
19388
- return answer;
19389
- throw new Error(`GET ${this.#url(path, query)} asked for a page ({issues, total, limit, offset}) and got ` + refusal);
19390
- }
19391
- async listAllIssues(options) {
19392
- const path = ["api", "v1", "issues"];
19393
- const query = { ...options };
19394
- const answer = await this.#json("GET", path, undefined, query);
19395
- if (Array.isArray(answer))
19396
- return answer;
19397
- throw new Error(`GET ${this.#url(path, query)} asked for the unpaged listing and got ${whyNotAnArray(answer)}.`);
19398
- }
19399
- async listIssueArtifacts(issue) {
19400
- return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "artifacts"]);
19401
- }
19402
- async markdownRoundTrip(markdown) {
19403
- const answer = await this.#json("POST", ["api", "v1", "markdown", "round-trip"], { markdown });
19404
- return answer.markdown;
19405
- }
19406
- async listProjectArtifacts(project, unlinked = false) {
19407
- return this.#json("GET", ["api", "v1", "projects", project, "artifacts"], undefined, unlinked ? { unlinked: "true" } : undefined);
19408
- }
19409
- async projectArtifact(project, input, key) {
19410
- return this.#upload(["api", "v1", "projects", project, "artifacts"], input, key);
19411
- }
19412
- async getProjectArtifact(project, slug) {
19413
- return this.#json("GET", ["api", "v1", "projects", project, "artifacts", slug]);
19414
- }
19415
- async agentArtifact(sessionId, input) {
19416
- return this.#upload(["api", "v1", "agents", sessionId, "artifacts"], input);
19417
- }
19418
- async getAgentArtifact(sessionId, slug) {
19419
- return this.#json("GET", ["api", "v1", "agents", sessionId, "artifacts", slug]);
19420
- }
19421
- async getIssueArtifact(issue, slug) {
19422
- return this.#json("GET", [
19423
- "api",
19424
- "v1",
19425
- "issues",
19426
- await this.#resolveIssue(issue),
19427
- "artifacts",
19428
- slug
19429
- ]);
19430
- }
19431
- async search(query, options = {}) {
19432
- const request = { q: query, ...options };
19433
- const path = everyBuildReadsSearch(request) ? ["api", "v1", "search"] : ["api", "v1", "search", "results"];
19434
- return this.#json("GET", path, undefined, request);
19435
- }
19436
- async related(project, input) {
19437
- return this.#json("POST", ["api", "v1", "projects", project, "related"], input);
19438
- }
19439
- async getIssue(issue) {
19440
- return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue)]);
19441
- }
19442
- async updateIssue(issue, input) {
19443
- return this.#json("PATCH", ["api", "v1", "issues", await this.#resolveIssue(issue)], input);
19444
- }
19445
- async claimIssue(issue, input = {}) {
19446
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "claim"], input);
19447
- }
19448
- async releaseIssueClaim(issue, input = {}) {
19449
- return this.#json("DELETE", ["api", "v1", "issues", await this.#resolveIssue(issue), "claim"], input);
19450
- }
19451
- async getIssueEvents(issue, after = 0, limit = ISSUE_EVENTS_PAGE_MAX) {
19452
- return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "events"], undefined, { after, limit });
19453
- }
19454
- async read(issueReference, options = {}) {
19455
- const issueKey = await this.#resolveIssue(issueReference);
19456
- const issue = await this.getIssue(issueKey);
19457
- const requested = options.events;
19458
- const count = requested === undefined ? DEFAULT_ISSUE_READ_EVENTS : requested === "all" ? issue.last_seq : Math.min(requested, issue.last_seq);
19459
- const events = [];
19460
- let after = Math.max(0, issue.last_seq - count);
19461
- while (events.length < count) {
19462
- const limit = Math.min(ISSUE_EVENTS_PAGE_MAX, count - events.length);
19463
- const page = await this.getIssueEvents(issueKey, after, limit);
19464
- events.push(...page);
19465
- const last = page.at(-1);
19466
- if (page.length < limit || last === undefined || events.length >= count)
19467
- break;
19468
- if (last.seq <= after) {
19469
- throw new Error(`GET /api/v1/issues/${issueKey}/events?after=${after} answered no event after seq ${after}`);
19470
- }
19471
- after = last.seq;
19472
- }
19473
- return { issue, events };
19474
- }
19475
- async ask(issue, input) {
19476
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "asks"], input);
18727
+ async ask(issue, input) {
18728
+ return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "asks"], input);
19477
18729
  }
19478
18730
  async openAsks(sessionID, since) {
19479
18731
  return this.#json("GET", ["api", "v1", "asks", "open"], undefined, {
@@ -19809,214 +19061,1056 @@ class DispatchClient {
19809
19061
  const response = await this.#send(method, url, { content, type }, undefined, undefined, key);
19810
19062
  return this.#response(method, url, response);
19811
19063
  }
19812
- async#send(method, url, body, accept = "application/json", signal, callerKey) {
19813
- const headers = { Accept: accept };
19814
- let presented = await this.#credential.headers(method, url);
19815
- if (body !== undefined)
19816
- headers["Content-Type"] = body.type;
19817
- if (method !== "POST" && method !== "PATCH") {
19818
- return this.fetchImpl(url, {
19819
- method,
19820
- headers: { ...headers, ...presented },
19821
- signal: signal === undefined ? this.#signal : AbortSignal.any([this.#signal, signal]),
19822
- ...body === undefined ? {} : { body: body.content }
19823
- });
19064
+ async#send(method, url, body, accept = "application/json", signal, callerKey) {
19065
+ const headers = { Accept: accept };
19066
+ let presented = await this.#credential.headers(method, url);
19067
+ if (body !== undefined)
19068
+ headers["Content-Type"] = body.type;
19069
+ if (method !== "POST" && method !== "PATCH") {
19070
+ return this.fetchImpl(url, {
19071
+ method,
19072
+ headers: { ...headers, ...presented },
19073
+ signal: signal === undefined ? this.#signal : AbortSignal.any([this.#signal, signal]),
19074
+ ...body === undefined ? {} : { body: body.content }
19075
+ });
19076
+ }
19077
+ const key = callerKey ?? crypto.randomUUID();
19078
+ headers[IDEMPOTENCY_KEY_HEADER] = key;
19079
+ const { pausesMs, withinMs, silenceMs, inFlightPauseMs, inFlightWithinMs } = this.writeRetry;
19080
+ const pause = this.writeRetry.pause ?? pauseFor;
19081
+ const request = `${method} ${url}`;
19082
+ const started = this.#now();
19083
+ const bodyBytes = body === undefined ? 0 : typeof body.content === "string" ? Buffer.byteLength(body.content) : body.content.byteLength;
19084
+ const upload = bodyBytes >= STREAMED_BODY_MIN;
19085
+ const lastAsk = this.#madeAt + inFlightWithinMs;
19086
+ let reached = false;
19087
+ let running = false;
19088
+ let sawKeyedLayer = false;
19089
+ for (let attempt = 1;; attempt++) {
19090
+ let answer;
19091
+ let thrown;
19092
+ try {
19093
+ if (attempt > 1)
19094
+ presented = await this.#credential.headers(method, url);
19095
+ const sent = { ...headers, ...presented };
19096
+ answer = await writeAnswer(await this.#attempt(url, method, sent, body, silenceMs), key);
19097
+ if (answer.echoed)
19098
+ KEYED_LAYER_SEEN.set(this.#baseUrl, this.#now());
19099
+ if (!answer.again)
19100
+ return answer.response;
19101
+ reached ||= answer.reached;
19102
+ running ||= answer.running && !upload;
19103
+ sawKeyedLayer ||= answer.echoed;
19104
+ } catch (error) {
19105
+ const name = error instanceof Error || error instanceof DOMException ? error.name : "";
19106
+ if (!(error instanceof WriteAttemptSilent) && (this.#signal.aborted || name === "AbortError" || name === "TimeoutError")) {
19107
+ throw this.#ended(error, request, attempt, true, sawKeyedLayer);
19108
+ }
19109
+ thrown = error;
19110
+ reached = true;
19111
+ running ||= error instanceof WriteAttemptSilent && !upload;
19112
+ }
19113
+ const scheduled = running ? Math.min(pausesMs[attempt - 1] ?? inFlightPauseMs, inFlightPauseMs) : pausesMs[attempt - 1];
19114
+ const wait = Math.max(scheduled ?? 0, answer === undefined ? 0 : retryAfterMs(answer.response));
19115
+ const latest = Math.min(started + (running ? inFlightWithinMs : withinMs), lastAsk);
19116
+ let again = scheduled !== undefined && this.#now() + wait <= latest;
19117
+ if (again) {
19118
+ again = answer?.echoed || await this.#runsKeyedLayer(answer?.unjudged ?? false);
19119
+ sawKeyedLayer ||= again;
19120
+ again &&= this.#now() + wait <= latest;
19121
+ }
19122
+ if (again) {
19123
+ try {
19124
+ await pause(wait, this.#signal);
19125
+ } catch (error) {
19126
+ throw this.#ended(error, request, attempt, reached, sawKeyedLayer);
19127
+ }
19128
+ again = this.#now() <= latest;
19129
+ }
19130
+ if (!again) {
19131
+ if (answer !== undefined) {
19132
+ return this.#unsettled(method, url, answer.response, reached, attempt, sawKeyedLayer);
19133
+ }
19134
+ if (thrown instanceof WriteAttemptSilent) {
19135
+ throw new DispatchWriteUnsettledError(thrown, attempt, `${request} ${thrown.message}`, sawKeyedLayer);
19136
+ }
19137
+ throw thrown;
19138
+ }
19139
+ }
19140
+ }
19141
+ #now() {
19142
+ return this.writeRetry.now?.() ?? performance.now();
19143
+ }
19144
+ async#attempt(url, method, headers, body, silenceMs) {
19145
+ const cut = new AbortController;
19146
+ const silent = () => cut.abort(new WriteAttemptSilent(silenceMs));
19147
+ let timer = setTimeout(silent, silenceMs);
19148
+ let answered = false;
19149
+ const progress = () => {
19150
+ if (answered)
19151
+ return;
19152
+ clearTimeout(timer);
19153
+ timer = setTimeout(silent, silenceMs);
19154
+ };
19155
+ try {
19156
+ return await this.fetchImpl(url, {
19157
+ method,
19158
+ signal: AbortSignal.any([this.#signal, cut.signal]),
19159
+ ...body === undefined ? { headers } : attemptBody(body, headers, progress)
19160
+ });
19161
+ } catch (error) {
19162
+ if (cut.signal.aborted && !this.#signal.aborted)
19163
+ throw cut.signal.reason;
19164
+ throw error;
19165
+ } finally {
19166
+ answered = true;
19167
+ clearTimeout(timer);
19168
+ }
19169
+ }
19170
+ #ended(error, request, attempts, mayHaveReached, keyed) {
19171
+ const reason = this.#signal.aborted ? this.#signal.reason : error;
19172
+ const timedOut = (reason instanceof Error || reason instanceof DOMException) && reason.name === "TimeoutError";
19173
+ if (!timedOut || !mayHaveReached || !(error instanceof Error))
19174
+ return error;
19175
+ return new DispatchWriteUnsettledError(error, attempts, `${request} had no definitive answer when its deadline ended it`, keyed);
19176
+ }
19177
+ async#runsKeyedLayer(unjudged) {
19178
+ const origin = this.#baseUrl;
19179
+ if (unjudged)
19180
+ KEYED_LAYER_SEEN.delete(origin);
19181
+ const seen = KEYED_LAYER_SEEN.get(origin);
19182
+ if (seen !== undefined && this.#now() - seen < KEYED_LAYER_MEMORY_MS)
19183
+ return true;
19184
+ let probe = KEYED_LAYER_PROBES.get(origin);
19185
+ if (probe === undefined) {
19186
+ probe = this.#probeKeyedLayer().finally(() => KEYED_LAYER_PROBES.delete(origin));
19187
+ KEYED_LAYER_PROBES.set(origin, probe);
19188
+ }
19189
+ const runs = await probe;
19190
+ if (runs)
19191
+ KEYED_LAYER_SEEN.set(origin, this.#now());
19192
+ return runs;
19193
+ }
19194
+ async#probeKeyedLayer() {
19195
+ try {
19196
+ const probe = `${this.#baseUrl}/healthz`;
19197
+ const response = await this.fetchImpl(probe, {
19198
+ method: "GET",
19199
+ headers: { Accept: "application/json", ...await this.#credential.headers("GET", probe) },
19200
+ signal: AbortSignal.any([this.#signal, AbortSignal.timeout(KEY_LAYER_PROBE_MS)])
19201
+ });
19202
+ if (!isJson(response))
19203
+ return false;
19204
+ const health = await response.json();
19205
+ return typeof health === "object" && health !== null && Reflect.get(health, "idempotency_keys") === true;
19206
+ } catch {
19207
+ return false;
19208
+ }
19209
+ }
19210
+ async#unsettled(method, url, response, reached, attempts, keyed) {
19211
+ const refusal = await this.#response(method, url, response).catch((error) => error);
19212
+ if (reached && refusal instanceof DispatchServiceError) {
19213
+ const landedAlone = refusal instanceof DispatchGatewayError ? refusal.mayHaveReachedDispatch : refusal.status >= 500;
19214
+ if (!landedAlone)
19215
+ throw new DispatchWriteUnsettledError(refusal, attempts, undefined, keyed);
19216
+ }
19217
+ throw refusal;
19218
+ }
19219
+ #url(path, query) {
19220
+ const url = new URL(`${path.map((segment) => encodeURIComponent(segment)).join("/")}`, `${this.#baseUrl}/`);
19221
+ if (query) {
19222
+ for (const [name, value] of Object.entries(query)) {
19223
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
19224
+ url.searchParams.set(name, String(value));
19225
+ } else if (Array.isArray(value)) {
19226
+ for (const item of value)
19227
+ url.searchParams.append(name, String(item));
19228
+ }
19229
+ }
19230
+ }
19231
+ return url.toString();
19232
+ }
19233
+ async#response(method, url, response) {
19234
+ const text = await response.text();
19235
+ let payload = text;
19236
+ if (text && isJson(response)) {
19237
+ try {
19238
+ payload = JSON.parse(text);
19239
+ } catch {
19240
+ payload = text;
19241
+ }
19242
+ }
19243
+ if (!response.ok) {
19244
+ const error = asErrorShape(payload);
19245
+ if (typeof error.error === "string") {
19246
+ if (response.status === 409 && error.code === IDEMPOTENCY_KEY_COMMITTED) {
19247
+ throw new DispatchWriteLandedError(IDEMPOTENCY_KEY_COMMITTED, response.status, method, url);
19248
+ }
19249
+ throw new DispatchServiceError(error.code ?? `HTTP_${response.status}`, response.status, error.error, error.candidates, error.current, error.mismatches);
19250
+ }
19251
+ const quoted = excerpt(text, this.token);
19252
+ let body;
19253
+ if (quoted !== "") {
19254
+ body = `a body that is not Dispatch's error JSON (${JSON.stringify(quoted)})`;
19255
+ } else if (text === "") {
19256
+ body = "an empty body";
19257
+ } else {
19258
+ const within = text.length > EXCERPT_SCAN_LIMIT ? ` in its first ${EXCERPT_SCAN_LIMIT / 1024} KiB` : "";
19259
+ const size = Buffer.byteLength(text).toLocaleString("en-US");
19260
+ body = `a body of ${size} bytes and no readable text${within}`;
19261
+ }
19262
+ const reasonPhrase = excerpt(response.statusText, this.token);
19263
+ const reason = reasonPhrase === "" ? "" : ` ${reasonPhrase}`;
19264
+ throw new DispatchGatewayError(response.status, `${method} ${url} answered ${response.status}${reason} with ${body}, ${GATEWAY_PAGE}`, gatewayAdvice(method, response.status));
19265
+ }
19266
+ const replayed = response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1";
19267
+ if (answerNotKept(response.status, replayed, payload)) {
19268
+ throw new DispatchWriteLandedError(IDEMPOTENCY_ANSWER_NOT_KEPT, response.status, method, url);
19269
+ }
19270
+ return payload;
19271
+ }
19272
+ }
19273
+
19274
+ // ../envoy-client/src/dispatch-commands/context.ts
19275
+ function stringArg(args, name) {
19276
+ const value = args[name];
19277
+ if (typeof value !== "string")
19278
+ throw new Error(`${name} is required`);
19279
+ return value;
19280
+ }
19281
+ function numberArg(args, name) {
19282
+ const value = args[name];
19283
+ if (typeof value !== "number")
19284
+ throw new Error(`${name} is required`);
19285
+ return value;
19286
+ }
19287
+ function optionalString(args, name) {
19288
+ const value = args[name];
19289
+ return typeof value === "string" ? value : undefined;
19290
+ }
19291
+ function optionalNullableString(args, name) {
19292
+ const value = args[name];
19293
+ if (value === null)
19294
+ return null;
19295
+ return typeof value === "string" ? value : undefined;
19296
+ }
19297
+ function optionalBoolean(args, name) {
19298
+ const value = args[name];
19299
+ return typeof value === "boolean" ? value : undefined;
19300
+ }
19301
+ function optionalNumber(args, name) {
19302
+ const value = args[name];
19303
+ return typeof value === "number" ? value : undefined;
19304
+ }
19305
+ function defined(name, value) {
19306
+ return value === undefined ? {} : { [name]: value };
19307
+ }
19308
+ function optionalStringArray(args, name) {
19309
+ const value = args[name];
19310
+ return Array.isArray(value) ? value : undefined;
19311
+ }
19312
+ function optionalPriority(args, name) {
19313
+ const value = args[name];
19314
+ if (value === null)
19315
+ return null;
19316
+ return typeof value === "number" ? value : undefined;
19317
+ }
19318
+ function optionalPriorityFilter(args, name) {
19319
+ const value = args[name];
19320
+ return Array.isArray(value) ? value.map((item) => item ?? "none") : undefined;
19321
+ }
19322
+ function optionalComponents(args, name) {
19323
+ const value = args[name];
19324
+ if (typeof value !== "object" || value === null)
19325
+ return;
19326
+ const input = value;
19327
+ return {
19328
+ mode: input.mode,
19329
+ ...input.ids === undefined ? {} : { ids: input.ids },
19330
+ ...input.reason === undefined ? {} : { reason: input.reason }
19331
+ };
19332
+ }
19333
+ function asObject(value) {
19334
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
19335
+ }
19336
+ function sessionContext(input, checked) {
19337
+ const { url: configUrl, credential } = input.config;
19338
+ const baseFetch = input.fetchImpl ?? fetch;
19339
+ const fetchImpl = Object.assign(async (...args) => {
19340
+ try {
19341
+ return await baseFetch(...args);
19342
+ } catch (error) {
19343
+ if (error instanceof TypeError) {
19344
+ throw new Error(`Dispatch at ${configUrl} is unreachable: ${error.message}. If the Dispatch URL changed, restart this agent process so it picks up the new configuration.`);
19345
+ }
19346
+ throw error;
19347
+ }
19348
+ }, { preconnect: baseFetch.preconnect });
19349
+ return {
19350
+ input,
19351
+ args: checked.args,
19352
+ ownerArguments: checked.owner,
19353
+ pictures: checked.pictures,
19354
+ configUrl,
19355
+ linkBase: input.config.publicUrl ?? configUrl,
19356
+ hostSession: input.sessionId?.trim(),
19357
+ newClient: () => new DispatchClient(configUrl, credential, fetchImpl, input.signal, input.writeRetry)
19358
+ };
19359
+ }
19360
+
19361
+ // ../envoy-client/src/dispatch-cwd.ts
19362
+ import { execFile } from "child_process";
19363
+ import { promisify } from "util";
19364
+
19365
+ // ../envoy-client/src/machine.ts
19366
+ import { hostname as hostname3 } from "os";
19367
+ function machineID() {
19368
+ return process.env["ENVOY_MACHINE_ID"] || process.env["AGENTBOX_HOST"] || hostname3();
19369
+ }
19370
+
19371
+ // ../envoy-client/src/dispatch-cwd.ts
19372
+ var execFileAsync = promisify(execFile);
19373
+ var defaultExec = (file, args, { cwd, signal }) => {
19374
+ const call = execFileAsync(file, args, { cwd, signal });
19375
+ const kill = () => call.child.kill("SIGKILL");
19376
+ if (signal.aborted)
19377
+ kill();
19378
+ else
19379
+ signal.addEventListener("abort", kill, { once: true });
19380
+ return call;
19381
+ };
19382
+ var REMOTE_LOOKUP_MS = 5000;
19383
+ var TMUX_PANE_LOOKUP_MS = 1000;
19384
+ async function tryExec(exec, file, args, cwd, limitMs) {
19385
+ const controller = new AbortController;
19386
+ const expired = Promise.withResolvers();
19387
+ const timer = setTimeout(() => {
19388
+ controller.abort();
19389
+ expired.resolve(null);
19390
+ }, limitMs);
19391
+ try {
19392
+ const answer = await Promise.race([
19393
+ exec(file, args, { cwd, signal: controller.signal }),
19394
+ expired.promise
19395
+ ]);
19396
+ if (answer === null) {
19397
+ return { failure: "timedOut", ok: false };
19398
+ }
19399
+ return { ok: true, stdout: answer.stdout };
19400
+ } catch {
19401
+ return { failure: "refused", ok: false };
19402
+ } finally {
19403
+ clearTimeout(timer);
19404
+ }
19405
+ }
19406
+ function parseRemoteList(stdout) {
19407
+ const remotes = new Map;
19408
+ for (const line of stdout.split(`
19409
+ `)) {
19410
+ const trimmed = line.trim();
19411
+ if (!trimmed)
19412
+ continue;
19413
+ const match = trimmed.match(/^(\S+)\s+(\S+)/);
19414
+ const [, name, url] = match ?? [];
19415
+ if (name && url)
19416
+ remotes.set(name, url);
19417
+ }
19418
+ return remotes;
19419
+ }
19420
+ function selectRemoteUrl(remotes) {
19421
+ const origin = remotes.get("origin");
19422
+ if (origin)
19423
+ return origin;
19424
+ const candidates = [...remotes.entries()].filter(([name]) => name !== "upstream");
19425
+ return candidates.length === 1 ? candidates[0]?.[1] ?? null : null;
19426
+ }
19427
+ var GITHUB_REMOTE_PATTERNS = [
19428
+ /^https:\/\/(?:[^@/\s]+@)?github\.com\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/i,
19429
+ /^git@github\.com:([^/]+)\/([^/]+?)(?:\.git)?\/?$/i,
19430
+ /^ssh:\/\/git@github\.com\/([^/]+)\/([^/]+?)(?:\.git)?\/?$/i
19431
+ ];
19432
+ function parseGitHubRemoteUrl(url) {
19433
+ const trimmed = url.trim();
19434
+ for (const pattern of GITHUB_REMOTE_PATTERNS) {
19435
+ const match = trimmed.match(pattern);
19436
+ if (match)
19437
+ return canonicalRepo(match[1] ?? "", match[2] ?? "");
19438
+ }
19439
+ return null;
19440
+ }
19441
+ async function resolveCwdRepo(cwd, exec) {
19442
+ const remoteList = await tryExec(exec, "jj", ["git", "remote", "list"], cwd, REMOTE_LOOKUP_MS);
19443
+ if (remoteList.ok) {
19444
+ const url = selectRemoteUrl(parseRemoteList(remoteList.stdout));
19445
+ return url ? parseGitHubRemoteUrl(url) : null;
19446
+ }
19447
+ const originRemote = await tryExec(exec, "git", ["remote", "get-url", "origin"], cwd, REMOTE_LOOKUP_MS);
19448
+ return originRemote.ok ? parseGitHubRemoteUrl(originRemote.stdout) : null;
19449
+ }
19450
+ async function resolveOrigin(env, exec, cwd) {
19451
+ const origin = {
19452
+ cwd,
19453
+ machine: machineID()
19454
+ };
19455
+ const pane = env.TMUX_PANE;
19456
+ if (pane) {
19457
+ const answer = await tryExec(exec, "tmux", ["display-message", "-p", "-t", pane, "#S:#I.#P #{pane_id}"], cwd, TMUX_PANE_LOOKUP_MS);
19458
+ const [target, paneId] = answer.ok ? answer.stdout.trim().split(" ") : [];
19459
+ if (target)
19460
+ origin.tmux = target;
19461
+ if (paneId)
19462
+ origin.pane = paneId;
19463
+ }
19464
+ return origin;
19465
+ }
19466
+
19467
+ // ../envoy-client/src/dispatch-owner.ts
19468
+ function documentLabel(project, slug) {
19469
+ return `${project}/${slug}`;
19470
+ }
19471
+ function ownerTitle(owner) {
19472
+ const { issue, document } = owner;
19473
+ if (issue !== undefined)
19474
+ return `${issue.key}: ${issue.title}`;
19475
+ if (document !== undefined)
19476
+ return `${document.project} / ${document.name}`;
19477
+ return "";
19478
+ }
19479
+ function issueTopic(key) {
19480
+ return { label: key, topic: dispatchIssueSubject(key, ">") };
19481
+ }
19482
+ function documentTopicOf(project, slug) {
19483
+ return {
19484
+ label: documentLabel(project, slug),
19485
+ topic: dispatchDocumentSubject(project, slug, ">")
19486
+ };
19487
+ }
19488
+ function dispatchIssueRef(key) {
19489
+ return `dispatch://${key}`;
19490
+ }
19491
+ function dispatchDocumentRef(owner, slug) {
19492
+ return `dispatch://${owner}/artifact/${slug}`;
19493
+ }
19494
+ var ITEM_KINDS = ["ask", "comment", "message"];
19495
+ function dispatchChildRef(ownerRef, kind, id) {
19496
+ return `${ownerRef}/${kind}/${id}`;
19497
+ }
19498
+ function parseBlockRef(holder, fragment) {
19499
+ const target = holder.includes("@") ? undefined : parseBlockFragment(fragment);
19500
+ const parsed = parseDispatchRef(holder);
19501
+ if (target === undefined || parsed === null) {
19502
+ return null;
19503
+ }
19504
+ const pin = target.pin === undefined ? {} : { pin: target.pin };
19505
+ const artifact = parsed.artifact === undefined ? {} : { artifact: parsed.artifact };
19506
+ if (parsed.kind === "ask" || parsed.kind === "comment" || parsed.kind === "message" && target.pin === undefined) {
19507
+ return {
19508
+ owner: parsed.owner,
19509
+ kind: "block",
19510
+ id: parsed.id,
19511
+ block: target.block,
19512
+ item: { kind: parsed.kind, id: parsed.id },
19513
+ ...artifact,
19514
+ ...pin
19515
+ };
19516
+ }
19517
+ if (parsed.kind !== "spec" && parsed.kind !== "artifact") {
19518
+ return null;
19519
+ }
19520
+ return {
19521
+ owner: parsed.owner,
19522
+ kind: "block",
19523
+ id: parsed.id,
19524
+ block: target.block,
19525
+ document: holder,
19526
+ ...parsed.owner.kind === "project" ? { artifact: parsed.id } : {},
19527
+ ...pin
19528
+ };
19529
+ }
19530
+ function parseDispatchRef(ref) {
19531
+ const hash = ref.indexOf("#");
19532
+ if (hash !== -1 && ref.startsWith("b-", hash + 1)) {
19533
+ return parseBlockRef(ref.slice(0, hash), ref.slice(hash + 3));
19534
+ }
19535
+ const projectDocument = ref.match(/^dispatch:\/\/([A-Z][A-Z0-9]{1,9})\/artifact\/([^/@]+)(?:@v(\d+))?(?:\/(ask|comment)\/([^/]+))?$/);
19536
+ if (projectDocument) {
19537
+ const [, project, artifact, version, targetKind, targetID] = projectDocument;
19538
+ if (project === undefined || artifact === undefined || version !== undefined && Number(version) < 1) {
19539
+ return null;
19540
+ }
19541
+ if (targetKind === undefined) {
19542
+ return {
19543
+ owner: { kind: "project", project },
19544
+ kind: "artifact",
19545
+ id: artifact,
19546
+ ...version === undefined ? {} : { version: Number(version) }
19547
+ };
19548
+ }
19549
+ if (version !== undefined)
19550
+ return null;
19551
+ if (targetID === undefined || targetKind !== "ask" && targetKind !== "comment")
19552
+ return null;
19553
+ return {
19554
+ owner: { kind: "project", project },
19555
+ kind: targetKind,
19556
+ id: targetID,
19557
+ artifact
19558
+ };
19559
+ }
19560
+ const issueReference = ref.match(/^dispatch:\/\/([A-Z][A-Z0-9]{1,9}-[1-9][0-9]*)(?:\/(spec)|\/(log|activity)|\/(children)|\/artifact\/([^/@]+)(?:@v(\d+))?|\/ask\/([^/]+)|\/comment\/([^/]+)|\/message\/([^/]+))?$/);
19561
+ if (!issueReference)
19562
+ return null;
19563
+ const [, issue, spec, log, children, artifact, version, ask, comment, message] = issueReference;
19564
+ if (!issue || version !== undefined && Number(version) < 1)
19565
+ return null;
19566
+ const owner = { kind: "issue", issue };
19567
+ if (spec)
19568
+ return { owner, kind: "spec", id: spec };
19569
+ if (log)
19570
+ return { owner, kind: "log", id: log };
19571
+ if (children)
19572
+ return { owner, kind: "children", id: children };
19573
+ if (artifact) {
19574
+ return {
19575
+ owner,
19576
+ kind: "artifact",
19577
+ id: artifact,
19578
+ ...version === undefined ? {} : { version: Number(version) }
19579
+ };
19580
+ }
19581
+ if (ask)
19582
+ return { owner, kind: "ask", id: ask };
19583
+ if (comment)
19584
+ return { owner, kind: "comment", id: comment };
19585
+ if (message)
19586
+ return { owner, kind: "message", id: message };
19587
+ return { owner, kind: "issue", id: issue };
19588
+ }
19589
+
19590
+ // ../envoy-client/src/dispatch-picture-tools.ts
19591
+ import { basename, resolve as resolvePath } from "path";
19592
+
19593
+ // ../../node_modules/.bun/@toon-format+toon@4.1.1/node_modules/@toon-format/toon/dist/index.mjs
19594
+ var NULL_LITERAL = "null";
19595
+ var DELIMITERS = {
19596
+ comma: ",",
19597
+ tab: "\t",
19598
+ pipe: "|"
19599
+ };
19600
+ var DEFAULT_DELIMITER = DELIMITERS.comma;
19601
+ function escapeString(value) {
19602
+ return value.replace(/\\/g, `\\\\`).replace(/"/g, `\\"`).replace(/\n/g, `\\n`).replace(/\r/g, `\\r`).replace(/\t/g, `\\t`).replace(/[\u0000-\u001F]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
19603
+ }
19604
+ var FETCH_LINE = Symbol("fetch-line");
19605
+ function isBooleanOrNullLiteral(token) {
19606
+ return token === "true" || token === "false" || token === "null";
19607
+ }
19608
+ function setOwnProperty(target, key, value) {
19609
+ if (key === "__proto__") {
19610
+ Object.defineProperty(target, key, {
19611
+ value,
19612
+ enumerable: true,
19613
+ writable: true,
19614
+ configurable: true
19615
+ });
19616
+ return;
19617
+ }
19618
+ target[key] = value;
19619
+ }
19620
+ var COMMENT_LINE_PATTERN = new RegExp(`(?:^\uFEFF?|\\n) *#`);
19621
+ var RawString = class {
19622
+ constructor(value) {
19623
+ if (COMMENT_LINE_PATTERN.test(value))
19624
+ throw new TypeError(`Raw string must not contain a line starting with "#": ${JSON.stringify(value)}`);
19625
+ this.value = value;
19626
+ }
19627
+ };
19628
+ function isRawString(value) {
19629
+ return value instanceof RawString;
19630
+ }
19631
+ var SURROGATE_PATTERN = /[\uD800-\uDFFF]/;
19632
+ function normalizeValue(value) {
19633
+ if (value === null)
19634
+ return null;
19635
+ if (isRawString(value))
19636
+ return value;
19637
+ if (typeof value === "object" && value !== null && "toJSON" in value && typeof value.toJSON === "function") {
19638
+ const next = value.toJSON();
19639
+ if (next !== value)
19640
+ return normalizeValue(next);
19641
+ }
19642
+ if (typeof value === "string") {
19643
+ assertNoLoneSurrogate(value, "string value");
19644
+ return value;
19645
+ }
19646
+ if (typeof value === "boolean")
19647
+ return value;
19648
+ if (typeof value === "number") {
19649
+ if (Object.is(value, -0))
19650
+ return 0;
19651
+ if (!Number.isFinite(value))
19652
+ return null;
19653
+ return value;
19654
+ }
19655
+ if (typeof value === "bigint") {
19656
+ if (value >= Number.MIN_SAFE_INTEGER && value <= Number.MAX_SAFE_INTEGER)
19657
+ return Number(value);
19658
+ return value.toString();
19659
+ }
19660
+ if (value instanceof Date)
19661
+ return value.toISOString();
19662
+ if (Array.isArray(value))
19663
+ return value.map(normalizeValue);
19664
+ if (value instanceof Set)
19665
+ return Array.from(value).map(normalizeValue);
19666
+ if (value instanceof Map)
19667
+ return Object.fromEntries(Array.from(value, ([k, v]) => [String(k), normalizeValue(v)]));
19668
+ if (isPlainObject2(value)) {
19669
+ const encodedValues = {};
19670
+ for (const key in value)
19671
+ if (Object.hasOwn(value, key)) {
19672
+ assertNoLoneSurrogate(key, "object key");
19673
+ setOwnProperty(encodedValues, key, normalizeValue(value[key]));
19674
+ }
19675
+ return encodedValues;
19676
+ }
19677
+ return null;
19678
+ }
19679
+ function assertNoLoneSurrogate(value, context) {
19680
+ if (!SURROGATE_PATTERN.test(value))
19681
+ return;
19682
+ for (let index = 0;index < value.length; index++) {
19683
+ const code = value.charCodeAt(index);
19684
+ if (code < 55296 || code > 57343)
19685
+ continue;
19686
+ const isHighSurrogate = code <= 56319;
19687
+ const next = value.charCodeAt(index + 1);
19688
+ if (isHighSurrogate && next >= 56320 && next <= 57343) {
19689
+ index++;
19690
+ continue;
19691
+ }
19692
+ throw new TypeError(`Cannot encode ${context} containing an unpaired surrogate U+${code.toString(16).toUpperCase()} at index ${index}`);
19693
+ }
19694
+ }
19695
+ function isJsonPrimitive(value) {
19696
+ return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
19697
+ }
19698
+ function isEncodablePrimitive(value) {
19699
+ return isJsonPrimitive(value) || isRawString(value);
19700
+ }
19701
+ function isJsonArray(value) {
19702
+ return Array.isArray(value);
19703
+ }
19704
+ function isJsonObject(value) {
19705
+ return value !== null && typeof value === "object" && !Array.isArray(value) && !isRawString(value);
19706
+ }
19707
+ function isEmptyObject(value) {
19708
+ return Object.keys(value).length === 0;
19709
+ }
19710
+ function isPlainObject2(value) {
19711
+ if (value === null || typeof value !== "object")
19712
+ return false;
19713
+ const prototype = Object.getPrototypeOf(value);
19714
+ return prototype === null || prototype === Object.prototype;
19715
+ }
19716
+ function isArrayOfPrimitives(value) {
19717
+ return value.length === 0 || value.every((item) => isEncodablePrimitive(item));
19718
+ }
19719
+ function isArrayOfArrays(value) {
19720
+ return value.length === 0 || value.every((item) => isJsonArray(item));
19721
+ }
19722
+ function isArrayOfObjects(value) {
19723
+ return value.length === 0 || value.every((item) => isJsonObject(item));
19724
+ }
19725
+ var NUMERIC_LIKE_PATTERN = /^[+-]?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i;
19726
+ function assertValidDelimiter(delimiter) {
19727
+ if (!Object.values(DELIMITERS).includes(delimiter))
19728
+ throw new TypeError(`Invalid delimiter ${JSON.stringify(delimiter)}. Valid delimiters are: comma (,), tab (\\t), pipe (|)`);
19729
+ }
19730
+ function isValidUnquotedKey(key) {
19731
+ return /^[A-Z_][\w.]*$/i.test(key);
19732
+ }
19733
+ function isSafeUnquoted(value, delimiter = DEFAULT_DELIMITER) {
19734
+ if (!value)
19735
+ return false;
19736
+ if (/^[ \t]|[ \t]$/.test(value))
19737
+ return false;
19738
+ if (isBooleanOrNullLiteral(value) || isNumericLike(value))
19739
+ return false;
19740
+ if (value.includes(":"))
19741
+ return false;
19742
+ if (value.includes('"') || value.includes("\\"))
19743
+ return false;
19744
+ if (/[[\]{}]/.test(value))
19745
+ return false;
19746
+ if (/[\u0000-\u001F]/.test(value))
19747
+ return false;
19748
+ if (value.includes(delimiter))
19749
+ return false;
19750
+ if (value.startsWith("-"))
19751
+ return false;
19752
+ if (value.startsWith("#"))
19753
+ return false;
19754
+ return true;
19755
+ }
19756
+ function isNumericLike(value) {
19757
+ return NUMERIC_LIKE_PATTERN.test(value);
19758
+ }
19759
+ function encodePrimitive(value, delimiter) {
19760
+ if (isRawString(value))
19761
+ return value.value;
19762
+ if (value === null)
19763
+ return NULL_LITERAL;
19764
+ if (typeof value === "boolean")
19765
+ return String(value);
19766
+ if (typeof value === "number")
19767
+ return String(value);
19768
+ return encodeStringLiteral(value, delimiter);
19769
+ }
19770
+ function encodeStringLiteral(value, delimiter = DEFAULT_DELIMITER) {
19771
+ if (isSafeUnquoted(value, delimiter))
19772
+ return value;
19773
+ return `"${escapeString(value)}"`;
19774
+ }
19775
+ function encodeKey(key) {
19776
+ if (isValidUnquotedKey(key))
19777
+ return key;
19778
+ return `"${escapeString(key)}"`;
19779
+ }
19780
+ function encodeAndJoinPrimitives(values, delimiter = DEFAULT_DELIMITER) {
19781
+ return values.map((v) => encodePrimitive(v, delimiter)).join(delimiter);
19782
+ }
19783
+ function formatHeader(length, options) {
19784
+ const key = options?.key;
19785
+ const fields = options?.fields;
19786
+ const delimiter = options?.delimiter ?? ",";
19787
+ let header = "";
19788
+ if (key != null)
19789
+ header += encodeKey(key);
19790
+ header += `[${length}${options?.keyed ? ":" : ""}${delimiter !== DEFAULT_DELIMITER ? delimiter : ""}]`;
19791
+ if (fields)
19792
+ header += `{${formatFieldSegment(fields, delimiter)}}`;
19793
+ header += ":";
19794
+ return header;
19795
+ }
19796
+ function formatFieldSegment(fields, delimiter) {
19797
+ return fields.map((field) => encodeKey(field.name) + (field.children ? `{${formatFieldSegment(field.children, delimiter)}}` : "")).join(delimiter);
19798
+ }
19799
+ function extractTabularFields(rows) {
19800
+ if (rows.length === 0)
19801
+ return;
19802
+ const firstKeys = Object.keys(rows[0]);
19803
+ if (firstKeys.length === 0)
19804
+ return;
19805
+ for (const row of rows) {
19806
+ if (Object.keys(row).length !== firstKeys.length)
19807
+ return;
19808
+ for (const key of firstKeys)
19809
+ if (!Object.hasOwn(row, key))
19810
+ return;
19811
+ }
19812
+ const fieldNodes = [];
19813
+ for (const key of firstKeys) {
19814
+ const fieldNode = classifyColumn(key, rows.map((row) => row[key]));
19815
+ if (!fieldNode)
19816
+ return;
19817
+ fieldNodes.push(fieldNode);
19818
+ }
19819
+ return fieldNodes;
19820
+ }
19821
+ function extractKeyedTabularFields(value) {
19822
+ const entryValues = Object.values(value);
19823
+ if (entryValues.length < 2)
19824
+ return;
19825
+ if (!entryValues.every((entryValue) => isJsonObject(entryValue) && !isEmptyObject(entryValue)))
19826
+ return;
19827
+ return extractTabularFields(entryValues);
19828
+ }
19829
+ function collectRowLeaves(row, fields) {
19830
+ const leaves = [];
19831
+ collectLeafValues(row, fields, leaves);
19832
+ return leaves;
19833
+ }
19834
+ function classifyColumn(name, values) {
19835
+ if (values.every((value) => isEncodablePrimitive(value)))
19836
+ return { name };
19837
+ if (!values.every((value) => isJsonObject(value) && !isEmptyObject(value)))
19838
+ return;
19839
+ const children = extractTabularFields(values);
19840
+ if (!children)
19841
+ return;
19842
+ return {
19843
+ name,
19844
+ children
19845
+ };
19846
+ }
19847
+ function collectLeafValues(row, fields, leaves) {
19848
+ for (const field of fields) {
19849
+ const value = row[field.name];
19850
+ if (field.children)
19851
+ collectLeafValues(value, field.children, leaves);
19852
+ else
19853
+ leaves.push(value);
19854
+ }
19855
+ }
19856
+ function* encodeJsonValue(value, options, depth) {
19857
+ if (isEncodablePrimitive(value)) {
19858
+ const encodedPrimitive = encodePrimitive(value, options.delimiter);
19859
+ if (encodedPrimitive !== "")
19860
+ yield encodedPrimitive;
19861
+ return;
19862
+ }
19863
+ if (isJsonArray(value))
19864
+ yield* encodeArrayLines(undefined, value, depth, options);
19865
+ else if (isJsonObject(value)) {
19866
+ const keyedFields = extractKeyedTabularFields(value);
19867
+ if (keyedFields) {
19868
+ yield* encodeKeyedObjectLines(undefined, value, keyedFields, depth, options);
19869
+ return;
19824
19870
  }
19825
- const key = callerKey ?? crypto.randomUUID();
19826
- headers[IDEMPOTENCY_KEY_HEADER] = key;
19827
- const { pausesMs, withinMs, silenceMs, inFlightPauseMs, inFlightWithinMs } = this.writeRetry;
19828
- const pause = this.writeRetry.pause ?? pauseFor;
19829
- const request = `${method} ${url}`;
19830
- const started = this.#now();
19831
- const bodyBytes = body === undefined ? 0 : typeof body.content === "string" ? Buffer.byteLength(body.content) : body.content.byteLength;
19832
- const upload = bodyBytes >= STREAMED_BODY_MIN;
19833
- const lastAsk = this.#madeAt + inFlightWithinMs;
19834
- let reached = false;
19835
- let running = false;
19836
- let sawKeyedLayer = false;
19837
- for (let attempt = 1;; attempt++) {
19838
- let answer;
19839
- let thrown;
19840
- try {
19841
- if (attempt > 1)
19842
- presented = await this.#credential.headers(method, url);
19843
- const sent = { ...headers, ...presented };
19844
- answer = await writeAnswer(await this.#attempt(url, method, sent, body, silenceMs), key);
19845
- if (answer.echoed)
19846
- KEYED_LAYER_SEEN.set(this.#baseUrl, this.#now());
19847
- if (!answer.again)
19848
- return answer.response;
19849
- reached ||= answer.reached;
19850
- running ||= answer.running && !upload;
19851
- sawKeyedLayer ||= answer.echoed;
19852
- } catch (error) {
19853
- const name = error instanceof Error || error instanceof DOMException ? error.name : "";
19854
- if (!(error instanceof WriteAttemptSilent) && (this.#signal.aborted || name === "AbortError" || name === "TimeoutError")) {
19855
- throw this.#ended(error, request, attempt, true, sawKeyedLayer);
19856
- }
19857
- thrown = error;
19858
- reached = true;
19859
- running ||= error instanceof WriteAttemptSilent && !upload;
19860
- }
19861
- const scheduled = running ? Math.min(pausesMs[attempt - 1] ?? inFlightPauseMs, inFlightPauseMs) : pausesMs[attempt - 1];
19862
- const wait = Math.max(scheduled ?? 0, answer === undefined ? 0 : retryAfterMs(answer.response));
19863
- const latest = Math.min(started + (running ? inFlightWithinMs : withinMs), lastAsk);
19864
- let again = scheduled !== undefined && this.#now() + wait <= latest;
19865
- if (again) {
19866
- again = answer?.echoed || await this.#runsKeyedLayer(answer?.unjudged ?? false);
19867
- sawKeyedLayer ||= again;
19868
- again &&= this.#now() + wait <= latest;
19869
- }
19870
- if (again) {
19871
- try {
19872
- await pause(wait, this.#signal);
19873
- } catch (error) {
19874
- throw this.#ended(error, request, attempt, reached, sawKeyedLayer);
19875
- }
19876
- again = this.#now() <= latest;
19877
- }
19878
- if (!again) {
19879
- if (answer !== undefined) {
19880
- return this.#unsettled(method, url, answer.response, reached, attempt, sawKeyedLayer);
19881
- }
19882
- if (thrown instanceof WriteAttemptSilent) {
19883
- throw new DispatchWriteUnsettledError(thrown, attempt, `${request} ${thrown.message}`, sawKeyedLayer);
19884
- }
19885
- throw thrown;
19886
- }
19871
+ yield* encodeObjectLines(value, depth, options);
19872
+ }
19873
+ }
19874
+ function* encodeObjectLines(value, depth, options) {
19875
+ for (const [key, val] of Object.entries(value))
19876
+ yield* encodeKeyValuePairLines(key, val, depth, options);
19877
+ }
19878
+ function* encodeKeyValuePairLines(key, value, depth, options) {
19879
+ const encodedKey = encodeKey(key);
19880
+ if (isEncodablePrimitive(value))
19881
+ yield indentedLine(depth, `${encodedKey}: ${encodePrimitive(value, options.delimiter)}`, options.indentSize);
19882
+ else if (isJsonArray(value))
19883
+ yield* encodeArrayLines(key, value, depth, options);
19884
+ else if (isJsonObject(value)) {
19885
+ const keyedFields = extractKeyedTabularFields(value);
19886
+ if (keyedFields) {
19887
+ yield* encodeKeyedObjectLines(key, value, keyedFields, depth, options);
19888
+ return;
19887
19889
  }
19890
+ yield indentedLine(depth, `${encodedKey}:`, options.indentSize);
19891
+ if (!isEmptyObject(value))
19892
+ yield* encodeObjectLines(value, depth + 1, options);
19888
19893
  }
19889
- #now() {
19890
- return this.writeRetry.now?.() ?? performance.now();
19894
+ }
19895
+ function* encodeKeyedObjectLines(key, value, fields, depth, options) {
19896
+ const entries = Object.entries(value);
19897
+ yield indentedLine(depth, formatHeader(entries.length, {
19898
+ key,
19899
+ fields,
19900
+ delimiter: options.delimiter,
19901
+ keyed: true
19902
+ }), options.indentSize);
19903
+ yield* encodeKeyedEntryRowsLines(entries, fields, depth + 1, options);
19904
+ }
19905
+ function* encodeKeyedEntryRowsLines(entries, fields, depth, options) {
19906
+ for (const [entryKey, entryValue] of entries) {
19907
+ const leaves = collectRowLeaves(entryValue, fields);
19908
+ yield indentedLine(depth, `${encodeKey(entryKey)}: ${encodeAndJoinPrimitives(leaves, options.delimiter)}`, options.indentSize);
19891
19909
  }
19892
- async#attempt(url, method, headers, body, silenceMs) {
19893
- const cut = new AbortController;
19894
- const silent = () => cut.abort(new WriteAttemptSilent(silenceMs));
19895
- let timer = setTimeout(silent, silenceMs);
19896
- let answered = false;
19897
- const progress = () => {
19898
- if (answered)
19899
- return;
19900
- clearTimeout(timer);
19901
- timer = setTimeout(silent, silenceMs);
19902
- };
19903
- try {
19904
- return await this.fetchImpl(url, {
19905
- method,
19906
- signal: AbortSignal.any([this.#signal, cut.signal]),
19907
- ...body === undefined ? { headers } : attemptBody(body, headers, progress)
19908
- });
19909
- } catch (error) {
19910
- if (cut.signal.aborted && !this.#signal.aborted)
19911
- throw cut.signal.reason;
19912
- throw error;
19913
- } finally {
19914
- answered = true;
19915
- clearTimeout(timer);
19910
+ }
19911
+ function* encodeArrayLines(key, value, depth, options) {
19912
+ if (value.length === 0) {
19913
+ yield indentedLine(depth, key != null ? `${encodeKey(key)}: []` : "[]", options.indentSize);
19914
+ return;
19915
+ }
19916
+ if (isArrayOfPrimitives(value)) {
19917
+ yield indentedLine(depth, encodeInlineArrayLine(value, options.delimiter, key), options.indentSize);
19918
+ return;
19919
+ }
19920
+ if (isArrayOfArrays(value)) {
19921
+ if (value.every((arr) => isArrayOfPrimitives(arr))) {
19922
+ yield* encodeArrayOfArraysAsListItemsLines(key, value, depth, options);
19923
+ return;
19916
19924
  }
19917
19925
  }
19918
- #ended(error, request, attempts, mayHaveReached, keyed) {
19919
- const reason = this.#signal.aborted ? this.#signal.reason : error;
19920
- const timedOut = (reason instanceof Error || reason instanceof DOMException) && reason.name === "TimeoutError";
19921
- if (!timedOut || !mayHaveReached || !(error instanceof Error))
19922
- return error;
19923
- return new DispatchWriteUnsettledError(error, attempts, `${request} had no definitive answer when its deadline ended it`, keyed);
19926
+ if (isArrayOfObjects(value)) {
19927
+ const fields = extractTabularFields(value);
19928
+ if (fields)
19929
+ yield* encodeArrayOfObjectsAsTabularLines(key, value, fields, depth, options);
19930
+ else
19931
+ yield* encodeMixedArrayAsListItemsLines(key, value, depth, options);
19932
+ return;
19924
19933
  }
19925
- async#runsKeyedLayer(unjudged) {
19926
- const origin = this.#baseUrl;
19927
- if (unjudged)
19928
- KEYED_LAYER_SEEN.delete(origin);
19929
- const seen = KEYED_LAYER_SEEN.get(origin);
19930
- if (seen !== undefined && this.#now() - seen < KEYED_LAYER_MEMORY_MS)
19931
- return true;
19932
- let probe = KEYED_LAYER_PROBES.get(origin);
19933
- if (probe === undefined) {
19934
- probe = this.#probeKeyedLayer().finally(() => KEYED_LAYER_PROBES.delete(origin));
19935
- KEYED_LAYER_PROBES.set(origin, probe);
19934
+ yield* encodeMixedArrayAsListItemsLines(key, value, depth, options);
19935
+ }
19936
+ function* encodeArrayOfArraysAsListItemsLines(prefix, values, depth, options) {
19937
+ yield indentedLine(depth, formatHeader(values.length, {
19938
+ key: prefix,
19939
+ delimiter: options.delimiter
19940
+ }), options.indentSize);
19941
+ for (const arr of values)
19942
+ if (isArrayOfPrimitives(arr)) {
19943
+ const arrayLine = encodeInlineArrayLine(arr, options.delimiter);
19944
+ yield indentedListItem(depth + 1, arrayLine, options.indentSize);
19936
19945
  }
19937
- const runs = await probe;
19938
- if (runs)
19939
- KEYED_LAYER_SEEN.set(origin, this.#now());
19940
- return runs;
19946
+ }
19947
+ function encodeInlineArrayLine(values, delimiter, prefix) {
19948
+ const header = formatHeader(values.length, {
19949
+ key: prefix,
19950
+ delimiter
19951
+ });
19952
+ const joinedValue = encodeAndJoinPrimitives(values, delimiter);
19953
+ if (values.length === 0)
19954
+ return header;
19955
+ return `${header} ${joinedValue}`;
19956
+ }
19957
+ function* encodeArrayOfObjectsAsTabularLines(prefix, rows, fields, depth, options) {
19958
+ yield indentedLine(depth, formatHeader(rows.length, {
19959
+ key: prefix,
19960
+ fields,
19961
+ delimiter: options.delimiter
19962
+ }), options.indentSize);
19963
+ yield* writeTabularRowsLines(rows, fields, depth + 1, options);
19964
+ }
19965
+ function* writeTabularRowsLines(rows, fields, depth, options) {
19966
+ for (const row of rows)
19967
+ yield indentedLine(depth, encodeAndJoinPrimitives(collectRowLeaves(row, fields), options.delimiter), options.indentSize);
19968
+ }
19969
+ function* encodeMixedArrayAsListItemsLines(prefix, items, depth, options) {
19970
+ yield indentedLine(depth, formatHeader(items.length, {
19971
+ key: prefix,
19972
+ delimiter: options.delimiter
19973
+ }), options.indentSize);
19974
+ for (const item of items)
19975
+ yield* encodeListItemValueLines(item, depth + 1, options);
19976
+ }
19977
+ function* encodeObjectAsListItemLines(obj, depth, options) {
19978
+ if (isEmptyObject(obj)) {
19979
+ yield indentedLine(depth, "-", options.indentSize);
19980
+ return;
19941
19981
  }
19942
- async#probeKeyedLayer() {
19943
- try {
19944
- const probe = `${this.#baseUrl}/healthz`;
19945
- const response = await this.fetchImpl(probe, {
19946
- method: "GET",
19947
- headers: { Accept: "application/json", ...await this.#credential.headers("GET", probe) },
19948
- signal: AbortSignal.any([this.#signal, AbortSignal.timeout(KEY_LAYER_PROBE_MS)])
19949
- });
19950
- if (!isJson(response))
19951
- return false;
19952
- const health = await response.json();
19953
- return typeof health === "object" && health !== null && Reflect.get(health, "idempotency_keys") === true;
19954
- } catch {
19955
- return false;
19982
+ const entries = Object.entries(obj);
19983
+ const [firstKey, firstValue] = entries[0];
19984
+ const restEntries = entries.slice(1);
19985
+ if (isJsonArray(firstValue) && isArrayOfObjects(firstValue)) {
19986
+ const fields = extractTabularFields(firstValue);
19987
+ if (fields) {
19988
+ yield indentedListItem(depth, formatHeader(firstValue.length, {
19989
+ key: firstKey,
19990
+ fields,
19991
+ delimiter: options.delimiter
19992
+ }), options.indentSize);
19993
+ yield* writeTabularRowsLines(firstValue, fields, depth + 2, options);
19994
+ if (restEntries.length > 0)
19995
+ yield* encodeObjectLines(Object.fromEntries(restEntries), depth + 1, options);
19996
+ return;
19956
19997
  }
19957
19998
  }
19958
- async#unsettled(method, url, response, reached, attempts, keyed) {
19959
- const refusal = await this.#response(method, url, response).catch((error) => error);
19960
- if (reached && refusal instanceof DispatchServiceError) {
19961
- const landedAlone = refusal instanceof DispatchGatewayError ? refusal.mayHaveReachedDispatch : refusal.status >= 500;
19962
- if (!landedAlone)
19963
- throw new DispatchWriteUnsettledError(refusal, attempts, undefined, keyed);
19999
+ if (isJsonObject(firstValue)) {
20000
+ const keyedFields = extractKeyedTabularFields(firstValue);
20001
+ if (keyedFields) {
20002
+ const keyedEntries = Object.entries(firstValue);
20003
+ yield indentedListItem(depth, formatHeader(keyedEntries.length, {
20004
+ key: firstKey,
20005
+ fields: keyedFields,
20006
+ delimiter: options.delimiter,
20007
+ keyed: true
20008
+ }), options.indentSize);
20009
+ yield* encodeKeyedEntryRowsLines(keyedEntries, keyedFields, depth + 2, options);
20010
+ if (restEntries.length > 0)
20011
+ yield* encodeObjectLines(Object.fromEntries(restEntries), depth + 1, options);
20012
+ return;
19964
20013
  }
19965
- throw refusal;
19966
20014
  }
19967
- #url(path, query) {
19968
- const url = new URL(`${path.map((segment) => encodeURIComponent(segment)).join("/")}`, `${this.#baseUrl}/`);
19969
- if (query) {
19970
- for (const [name, value] of Object.entries(query)) {
19971
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
19972
- url.searchParams.set(name, String(value));
19973
- } else if (Array.isArray(value)) {
19974
- for (const item of value)
19975
- url.searchParams.append(name, String(item));
19976
- }
19977
- }
20015
+ const encodedKey = encodeKey(firstKey);
20016
+ if (isEncodablePrimitive(firstValue))
20017
+ yield indentedListItem(depth, `${encodedKey}: ${encodePrimitive(firstValue, options.delimiter)}`, options.indentSize);
20018
+ else if (isJsonArray(firstValue))
20019
+ if (firstValue.length === 0)
20020
+ yield indentedListItem(depth, `${encodedKey}: []`, options.indentSize);
20021
+ else if (isArrayOfPrimitives(firstValue))
20022
+ yield indentedListItem(depth, `${encodedKey}${encodeInlineArrayLine(firstValue, options.delimiter)}`, options.indentSize);
20023
+ else {
20024
+ yield indentedListItem(depth, `${encodedKey}${formatHeader(firstValue.length, { delimiter: options.delimiter })}`, options.indentSize);
20025
+ for (const item of firstValue)
20026
+ yield* encodeListItemValueLines(item, depth + 2, options);
19978
20027
  }
19979
- return url.toString();
20028
+ else if (isJsonObject(firstValue)) {
20029
+ yield indentedListItem(depth, `${encodedKey}:`, options.indentSize);
20030
+ if (!isEmptyObject(firstValue))
20031
+ yield* encodeObjectLines(firstValue, depth + 2, options);
19980
20032
  }
19981
- async#response(method, url, response) {
19982
- const text = await response.text();
19983
- let payload = text;
19984
- if (text && isJson(response)) {
19985
- try {
19986
- payload = JSON.parse(text);
19987
- } catch {
19988
- payload = text;
19989
- }
19990
- }
19991
- if (!response.ok) {
19992
- const error = asErrorShape(payload);
19993
- if (typeof error.error === "string") {
19994
- if (response.status === 409 && error.code === IDEMPOTENCY_KEY_COMMITTED) {
19995
- throw new DispatchWriteLandedError(IDEMPOTENCY_KEY_COMMITTED, response.status, method, url);
19996
- }
19997
- throw new DispatchServiceError(error.code ?? `HTTP_${response.status}`, response.status, error.error, error.candidates, error.current, error.mismatches);
19998
- }
19999
- const quoted = excerpt(text, this.token);
20000
- let body;
20001
- if (quoted !== "") {
20002
- body = `a body that is not Dispatch's error JSON (${JSON.stringify(quoted)})`;
20003
- } else if (text === "") {
20004
- body = "an empty body";
20005
- } else {
20006
- const within = text.length > EXCERPT_SCAN_LIMIT ? ` in its first ${EXCERPT_SCAN_LIMIT / 1024} KiB` : "";
20007
- const size = Buffer.byteLength(text).toLocaleString("en-US");
20008
- body = `a body of ${size} bytes and no readable text${within}`;
20009
- }
20010
- const reasonPhrase = excerpt(response.statusText, this.token);
20011
- const reason = reasonPhrase === "" ? "" : ` ${reasonPhrase}`;
20012
- throw new DispatchGatewayError(response.status, `${method} ${url} answered ${response.status}${reason} with ${body}, ${GATEWAY_PAGE}`, gatewayAdvice(method, response.status));
20013
- }
20014
- const replayed = response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1";
20015
- if (answerNotKept(response.status, replayed, payload)) {
20016
- throw new DispatchWriteLandedError(IDEMPOTENCY_ANSWER_NOT_KEPT, response.status, method, url);
20033
+ if (restEntries.length > 0)
20034
+ yield* encodeObjectLines(Object.fromEntries(restEntries), depth + 1, options);
20035
+ }
20036
+ function* encodeListItemValueLines(value, depth, options) {
20037
+ if (isEncodablePrimitive(value))
20038
+ yield indentedListItem(depth, encodePrimitive(value, options.delimiter), options.indentSize);
20039
+ else if (isJsonArray(value))
20040
+ if (isArrayOfPrimitives(value))
20041
+ yield indentedListItem(depth, encodeInlineArrayLine(value, options.delimiter), options.indentSize);
20042
+ else {
20043
+ yield indentedListItem(depth, formatHeader(value.length, { delimiter: options.delimiter }), options.indentSize);
20044
+ for (const item of value)
20045
+ yield* encodeListItemValueLines(item, depth + 1, options);
20017
20046
  }
20018
- return payload;
20047
+ else if (isJsonObject(value))
20048
+ yield* encodeObjectAsListItemLines(value, depth, options);
20049
+ }
20050
+ function indentedLine(depth, content, indentSize) {
20051
+ return " ".repeat(indentSize * depth) + content;
20052
+ }
20053
+ function indentedListItem(depth, content, indentSize) {
20054
+ return indentedLine(depth, "- " + content, indentSize);
20055
+ }
20056
+ function applyReplacer(root, replacer) {
20057
+ const replacedRoot = replacer("", root, []);
20058
+ if (replacedRoot === undefined)
20059
+ return transformChildren(root, replacer, []);
20060
+ return transformReplaced(root, replacedRoot, replacer, []);
20061
+ }
20062
+ function transformReplaced(original, replaced, replacer, path) {
20063
+ if (isRawString(replaced) && !isEncodablePrimitive(original))
20064
+ return transformChildren(original, replacer, path);
20065
+ return transformChildren(normalizeValue(replaced), replacer, path);
20066
+ }
20067
+ function transformChildren(value, replacer, path) {
20068
+ if (isJsonObject(value))
20069
+ return transformObject(value, replacer, path);
20070
+ if (isJsonArray(value))
20071
+ return transformArray(value, replacer, path);
20072
+ return value;
20073
+ }
20074
+ function transformObject(obj, replacer, path) {
20075
+ const result = {};
20076
+ for (const [key, value] of Object.entries(obj)) {
20077
+ const childPath = [...path, key];
20078
+ const replacedValue = replacer(key, value, childPath);
20079
+ if (replacedValue === undefined)
20080
+ continue;
20081
+ setOwnProperty(result, key, transformReplaced(value, replacedValue, replacer, childPath));
20082
+ }
20083
+ return result;
20084
+ }
20085
+ function transformArray(arr, replacer, path) {
20086
+ const result = [];
20087
+ for (let i = 0;i < arr.length; i++) {
20088
+ const value = arr[i];
20089
+ const childPath = [...path, i];
20090
+ const replacedValue = replacer(String(i), value, childPath);
20091
+ if (replacedValue === undefined)
20092
+ continue;
20093
+ result.push(transformReplaced(value, replacedValue, replacer, childPath));
20019
20094
  }
20095
+ return result;
20096
+ }
20097
+ function encode3(input, options) {
20098
+ return Array.from(encodeLines(input, options)).join(`
20099
+ `);
20100
+ }
20101
+ function encodeLines(input, options) {
20102
+ const normalizedValue = normalizeValue(input);
20103
+ const resolvedOptions = resolveOptions(options);
20104
+ return encodeJsonValue(resolvedOptions.replacer ? applyReplacer(normalizedValue, resolvedOptions.replacer) : normalizedValue, resolvedOptions, 0);
20105
+ }
20106
+ function resolveOptions(options) {
20107
+ const delimiter = options?.delimiter ?? DEFAULT_DELIMITER;
20108
+ assertValidDelimiter(delimiter);
20109
+ return {
20110
+ indentSize: options?.indentSize ?? options?.indent ?? 2,
20111
+ delimiter,
20112
+ replacer: options?.replacer
20113
+ };
20020
20114
  }
20021
20115
 
20022
20116
  // ../envoy-client/src/dispatch-pictures.ts
@@ -21253,93 +21347,6 @@ function formatZodIssues(issues, schema, tool) {
21253
21347
  });
21254
21348
  }
21255
21349
 
21256
- // ../envoy-client/src/dispatch-commands/context.ts
21257
- function stringArg(args, name) {
21258
- const value = args[name];
21259
- if (typeof value !== "string")
21260
- throw new Error(`${name} is required`);
21261
- return value;
21262
- }
21263
- function numberArg(args, name) {
21264
- const value = args[name];
21265
- if (typeof value !== "number")
21266
- throw new Error(`${name} is required`);
21267
- return value;
21268
- }
21269
- function optionalString(args, name) {
21270
- const value = args[name];
21271
- return typeof value === "string" ? value : undefined;
21272
- }
21273
- function optionalNullableString(args, name) {
21274
- const value = args[name];
21275
- if (value === null)
21276
- return null;
21277
- return typeof value === "string" ? value : undefined;
21278
- }
21279
- function optionalBoolean(args, name) {
21280
- const value = args[name];
21281
- return typeof value === "boolean" ? value : undefined;
21282
- }
21283
- function optionalNumber(args, name) {
21284
- const value = args[name];
21285
- return typeof value === "number" ? value : undefined;
21286
- }
21287
- function defined(name, value) {
21288
- return value === undefined ? {} : { [name]: value };
21289
- }
21290
- function optionalStringArray(args, name) {
21291
- const value = args[name];
21292
- return Array.isArray(value) ? value : undefined;
21293
- }
21294
- function optionalPriority(args, name) {
21295
- const value = args[name];
21296
- if (value === null)
21297
- return null;
21298
- return typeof value === "number" ? value : undefined;
21299
- }
21300
- function optionalPriorityFilter(args, name) {
21301
- const value = args[name];
21302
- return Array.isArray(value) ? value.map((item) => item ?? "none") : undefined;
21303
- }
21304
- function optionalComponents(args, name) {
21305
- const value = args[name];
21306
- if (typeof value !== "object" || value === null)
21307
- return;
21308
- const input = value;
21309
- return {
21310
- mode: input.mode,
21311
- ...input.ids === undefined ? {} : { ids: input.ids },
21312
- ...input.reason === undefined ? {} : { reason: input.reason }
21313
- };
21314
- }
21315
- function asObject(value) {
21316
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
21317
- }
21318
- function sessionContext(input, checked) {
21319
- const { url: configUrl, credential } = input.config;
21320
- const baseFetch = input.fetchImpl ?? fetch;
21321
- const fetchImpl = Object.assign(async (...args) => {
21322
- try {
21323
- return await baseFetch(...args);
21324
- } catch (error) {
21325
- if (error instanceof TypeError) {
21326
- throw new Error(`Dispatch at ${configUrl} is unreachable: ${error.message}. If the Dispatch URL changed, restart this agent process so it picks up the new configuration.`);
21327
- }
21328
- throw error;
21329
- }
21330
- }, { preconnect: baseFetch.preconnect });
21331
- return {
21332
- input,
21333
- args: checked.args,
21334
- ownerArguments: checked.owner,
21335
- pictures: checked.pictures,
21336
- configUrl,
21337
- linkBase: input.config.publicUrl ?? configUrl,
21338
- hostSession: input.sessionId?.trim(),
21339
- newClient: () => new DispatchClient(configUrl, credential, fetchImpl, input.signal, input.writeRetry)
21340
- };
21341
- }
21342
-
21343
21350
  // ../envoy-client/src/dispatch-commands/refs.ts
21344
21351
  var canonicalUUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
21345
21352
  var compactUUIDPattern = /^[0-9a-f]{32}$/i;
@@ -29850,7 +29857,7 @@ async function runDispatchCli(argv, rawEnv, io) {
29850
29857
  if (parsed.kind === "refused") {
29851
29858
  return parsed.tool === undefined ? refuse([`dispatch: ${parsed.problems.join(`
29852
29859
  `)}`, "Run dispatch --help."].join(`
29853
- `), USAGE) : refuse(new ToolInputError(parsed.tool, parsed.problems).message, USAGE, parsed.tool);
29860
+ `), USAGE) : refuse(new ToolInputError(parsed.tool, parsed.problems, defined("aboutAFlag", parsed.aboutAFlag)).message, USAGE, parsed.tool);
29854
29861
  }
29855
29862
  const hostName = env.DISPATCH_HOST ?? (env.CLAUDE_CODE_CHILD_SESSION === "1" ? "claude" : undefined);
29856
29863
  const host = HOSTS.find((name) => name === hostName);