@sjawhar/pi-envoy 11.9.0 → 13.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/dispatch.js +323 -29
  2. package/dist/envoy.js +2185 -1908
  3. package/package.json +1 -1
package/dist/envoy.js CHANGED
@@ -29669,6 +29669,21 @@ var MAX_ISSUE_PAGE_LIMIT = 250;
29669
29669
  var DEFAULT_ISSUE_PAGE_LIMIT = 50;
29670
29670
  var ASK_TURNS = ["human", "agent"];
29671
29671
  var DELIVERY_CAPABILITIES = ["aside", "btw", "steer"];
29672
+ var IDEMPOTENCY_KEY_HEADER = "Idempotency-Key";
29673
+ var IDEMPOTENCY_REPLAYED_HEADER = "Idempotency-Replayed";
29674
+ var IDEMPOTENCY_KEY_MAX = 128;
29675
+ var IDEMPOTENCY_KEY_PATTERN = new RegExp(`^[A-Za-z0-9._:-]{1,${IDEMPOTENCY_KEY_MAX}}$`);
29676
+ var IDEMPOTENCY_KEY_IN_FLIGHT = "KEY_IN_FLIGHT";
29677
+ var IDEMPOTENCY_KEY_COMMITTED = "KEY_COMMITTED";
29678
+ var IDEMPOTENCY_ANSWER_NOT_KEPT = "ANSWER_NOT_KEPT";
29679
+ function retriesUnderKey(status, code) {
29680
+ return status >= 500 || status === 408 || status === 429 || status === 409 && code === IDEMPOTENCY_KEY_IN_FLIGHT;
29681
+ }
29682
+ function answerNotKept(status, replayed, body) {
29683
+ return replayed && status >= 200 && status < 300 && typeof body === "object" && body !== null && Reflect.get(body, "code") === IDEMPOTENCY_ANSWER_NOT_KEPT;
29684
+ }
29685
+ var IDEMPOTENCY_KEY_TTL_MS = 24 * 60 * 60 * 1000;
29686
+ var IDEMPOTENCY_LEASE_MS = 60 * 1000;
29672
29687
  var DELIVERY_DUPLICATE_WINDOW_MS = 72 * 60 * 60 * 1000;
29673
29688
  var IssueDeployedEventPayloadSchema = strictObject({
29674
29689
  repo: string2(),
@@ -31616,2078 +31631,2336 @@ function commandLine(tool, args) {
31616
31631
  return words.join(" ");
31617
31632
  }
31618
31633
 
31619
- // ../envoy-client/src/dispatch-owner.ts
31620
- function dispatchIssueRef(key) {
31621
- return `dispatch://${key}`;
31622
- }
31623
- function dispatchDocumentRef(owner, slug) {
31624
- return `dispatch://${owner}/artifact/${slug}`;
31625
- }
31626
- function dispatchChildRef(ownerRef, kind, id) {
31627
- return `${ownerRef}/${kind}/${id}`;
31628
- }
31629
- function parseBlockRef(document, fragment) {
31630
- const target = parseBlockFragment(fragment);
31631
- const parsed = parseDispatchRef(document);
31632
- if (target === undefined || parsed === null || parsed.version !== undefined || parsed.kind !== "spec" && parsed.kind !== "artifact") {
31633
- return null;
31634
+ // ../envoy-client/src/dispatch-http.ts
31635
+ class DispatchServiceError extends Error {
31636
+ code;
31637
+ status;
31638
+ candidates;
31639
+ current;
31640
+ mismatches;
31641
+ name = "DispatchServiceError";
31642
+ fromDispatch = true;
31643
+ constructor(code, status, message, candidates, current, mismatches) {
31644
+ super(message);
31645
+ this.code = code;
31646
+ this.status = status;
31647
+ this.candidates = candidates;
31648
+ this.current = current;
31649
+ this.mismatches = mismatches;
31634
31650
  }
31635
- return {
31636
- owner: parsed.owner,
31637
- kind: "block",
31638
- id: parsed.id,
31639
- block: target.block,
31640
- document,
31641
- ...parsed.owner.kind === "project" ? { artifact: parsed.id } : {},
31642
- ...target.pin === undefined ? {} : { pin: target.pin }
31643
- };
31644
31651
  }
31645
- function parseDispatchRef(ref) {
31646
- const hash = ref.indexOf("#");
31647
- if (hash !== -1 && ref.startsWith("b-", hash + 1)) {
31648
- return parseBlockRef(ref.slice(0, hash), ref.slice(hash + 3));
31652
+
31653
+ class DispatchGatewayError extends DispatchServiceError {
31654
+ answer;
31655
+ advice;
31656
+ fromDispatch = false;
31657
+ transient;
31658
+ mayHaveReachedDispatch;
31659
+ constructor(status, answer, advice, message = `${answer}, so ${advice}.`) {
31660
+ super(`HTTP_${status}`, status, message);
31661
+ this.answer = answer;
31662
+ this.advice = advice;
31663
+ this.transient = transientStatus(status);
31664
+ this.mayHaveReachedDispatch = reachesDispatch(status);
31649
31665
  }
31650
- const projectDocument = ref.match(/^dispatch:\/\/([A-Z][A-Z0-9]{1,9})\/artifact\/([^/@]+)(?:@v(\d+))?(?:\/(ask|comment)\/([^/]+))?$/);
31651
- if (projectDocument) {
31652
- const [, project, artifact, version, targetKind, targetID] = projectDocument;
31653
- if (project === undefined || artifact === undefined || version !== undefined && Number(version) < 1) {
31654
- return null;
31655
- }
31656
- if (targetKind === undefined) {
31657
- return {
31658
- owner: { kind: "project", project },
31659
- kind: "artifact",
31660
- id: artifact,
31661
- ...version === undefined ? {} : { version: Number(version) }
31662
- };
31666
+ }
31667
+
31668
+ class DispatchWriteUnsettledError extends Error {
31669
+ last;
31670
+ attempts;
31671
+ name = "DispatchWriteUnsettledError";
31672
+ constructor(last, attempts, unanswered) {
31673
+ let answer;
31674
+ let why = "an earlier attempt of the write may have reached Dispatch";
31675
+ if (last instanceof DispatchGatewayError) {
31676
+ answer = last.answer;
31677
+ } else if (last instanceof DispatchServiceError) {
31678
+ answer = `${last.code}: ${last.message}`;
31679
+ if (last.code === IDEMPOTENCY_KEY_IN_FLIGHT) {
31680
+ why = "Dispatch was still running an earlier attempt of the write";
31681
+ }
31682
+ } else {
31683
+ answer = unanswered ?? last.message;
31684
+ why = "an attempt of the write may have reached Dispatch";
31663
31685
  }
31664
- if (version !== undefined)
31665
- return null;
31666
- if (targetID === undefined || targetKind !== "ask" && targetKind !== "comment")
31667
- return null;
31668
- return {
31669
- owner: { kind: "project", project },
31670
- kind: targetKind,
31671
- id: targetID,
31672
- artifact
31673
- };
31674
- }
31675
- 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\/([^/]+))?$/);
31676
- if (!issueReference)
31677
- return null;
31678
- const [, issue, spec, log, children, artifact, version, ask, comment, message] = issueReference;
31679
- if (!issue || version !== undefined && Number(version) < 1)
31680
- return null;
31681
- const owner = { kind: "issue", issue };
31682
- if (spec)
31683
- return { owner, kind: "spec", id: spec };
31684
- if (log)
31685
- return { owner, kind: "log", id: log };
31686
- if (children)
31687
- return { owner, kind: "children", id: children };
31688
- if (artifact) {
31689
- return {
31690
- owner,
31691
- kind: "artifact",
31692
- id: artifact,
31693
- ...version === undefined ? {} : { version: Number(version) }
31694
- };
31686
+ const tried = attempts === 1 ? "its only attempt" : `the last of ${attempts} attempts`;
31687
+ super(`${answer} (${tried}), and ${why}, so it may or may not have taken effect: check whether ` + "it did before retrying it.", { cause: last });
31688
+ this.last = last;
31689
+ this.attempts = attempts;
31695
31690
  }
31696
- if (ask)
31697
- return { owner, kind: "ask", id: ask };
31698
- if (comment)
31699
- return { owner, kind: "comment", id: comment };
31700
- if (message)
31701
- return { owner, kind: "message", id: message };
31702
- return { owner, kind: "issue", id: issue };
31703
31691
  }
31704
31692
 
31705
- // ../envoy-client/src/dispatch-pictures.ts
31706
- var PICTURE_UPLOAD_MAX_BYTES = 25 * 1024 * 1024;
31707
- var PICTURE_SHOWN_MAX_BYTES = 3750000;
31708
- var pictureShownMaxText = `${PICTURE_SHOWN_MAX_BYTES.toLocaleString("en-US")} bytes (5 MB of base64)`;
31709
- function oversizePictureText(name, bytes) {
31710
- return `${name} is ${bytes.toLocaleString("en-US")} bytes, over the ${pictureShownMaxText} a model is shown`;
31711
- }
31712
- var PICTURES_SHOWN_MAX = 8;
31713
- var PICTURES_SHOWN_MAX_BYTES = 10 * 1024 * 1024;
31714
- function bytesAt(bytes, offset, expected) {
31715
- return expected.every((byte, index) => bytes[offset + index] === byte);
31716
- }
31717
- function sniffPictureType(bytes) {
31718
- if (bytesAt(bytes, 0, [137, 80, 78, 71, 13, 10, 26, 10]))
31719
- return "image/png";
31720
- if (bytesAt(bytes, 0, [255, 216, 255]))
31721
- return "image/jpeg";
31722
- if (bytesAt(bytes, 0, [71, 73, 70, 56]) && (bytes[4] === 55 || bytes[4] === 57) && bytes[5] === 97) {
31723
- return "image/gif";
31724
- }
31725
- if (bytesAt(bytes, 0, [82, 73, 70, 70]) && bytesAt(bytes, 8, [87, 69, 66, 80])) {
31726
- return "image/webp";
31693
+ class DispatchWriteLandedError extends Error {
31694
+ code;
31695
+ status;
31696
+ name = "DispatchWriteLandedError";
31697
+ constructor(code, status, method, url) {
31698
+ 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";
31699
+ 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.");
31700
+ this.code = code;
31701
+ this.status = status;
31727
31702
  }
31728
- return;
31729
31703
  }
31730
- function toolImage(bytes) {
31731
- const mimeType = sniffPictureType(bytes);
31732
- if (mimeType === undefined || bytes.length > PICTURE_SHOWN_MAX_BYTES)
31733
- return;
31734
- return { data: Buffer.from(bytes).toString("base64"), mimeType };
31704
+ function asErrorShape(value) {
31705
+ return typeof value === "object" && value !== null ? value : {};
31735
31706
  }
31736
- function imageBlocks(images) {
31737
- return images.map(({ data, mimeType }) => ({ type: "image", data, mimeType }));
31707
+ function isJson(response) {
31708
+ return response.headers.get("content-type")?.includes("application/json") ?? false;
31738
31709
  }
31739
- var PICTURE_SYNTAX = /!\[(?:\\.|[^\\\]])*\]\((dispatch:\/\/[^\s()]+@v[1-9][0-9]*)(?:\s+"(?:\\.|[^\\"])*")?\)/g;
31740
- function pictureAddresses(text) {
31741
- return [...text.matchAll(PICTURE_SYNTAX)].map((match) => match[1]);
31710
+ function isNoRoute(error) {
31711
+ return error instanceof DispatchServiceError && error.status === 404 && error.code === "NOT_FOUND" && error.message.startsWith("no route for ");
31742
31712
  }
31743
-
31744
- // ../envoy-client/src/human-edit.ts
31745
- function humanEditHead(edit) {
31746
- const editors = edit.editors ?? [];
31747
- const by = editors.length === 0 ? "" : `, edited by ${editors.join(", ")}`;
31748
- return `${edit.name ?? "document"} v${edit.from_version ?? "?"} to v${edit.to_version ?? "?"}${by}`;
31713
+ var ISSUE_EVENTS_PAGE_MAX = 200;
31714
+ var DISPATCH_TOOL_DEADLINE_MS = 60000;
31715
+ function requestSignal(signal) {
31716
+ const deadline = AbortSignal.timeout(DISPATCH_TOOL_DEADLINE_MS);
31717
+ return signal === undefined ? deadline : AbortSignal.any([signal, deadline]);
31749
31718
  }
31750
- var HUMAN_EDIT_DIFF_CUT_NOTE = "(diff cut at 4,096 bytes)";
31751
- var HUMAN_EDIT_DIFF_MAX = 4096;
31752
- function humanEditDiffBlock(diff, cut) {
31753
- if (diff === undefined || diff === "")
31754
- return cut === true ? HUMAN_EDIT_DIFF_CUT_NOTE : "";
31755
- const bytes = new TextEncoder;
31756
- let shown = diff;
31757
- let note = cut === true;
31758
- if (bytes.encode(shown).length > HUMAN_EDIT_DIFF_MAX) {
31759
- let kept = "";
31760
- let size = 0;
31761
- for (const line of shown.split(`
31762
- `).slice(0, -1)) {
31763
- size += bytes.encode(`${line}
31764
- `).length;
31765
- if (size > HUMAN_EDIT_DIFF_MAX)
31766
- break;
31767
- kept += `${line}
31768
- `;
31769
- }
31770
- shown = kept;
31771
- note = true;
31719
+ var DISPATCH_WRITE_RETRY = {
31720
+ pausesMs: [1000, 2000, 4000, 8000],
31721
+ withinMs: 30000,
31722
+ silenceMs: 20000
31723
+ };
31724
+ function pauseFor(ms, signal) {
31725
+ const { promise, resolve, reject } = Promise.withResolvers();
31726
+ if (signal.aborted) {
31727
+ reject(signal.reason);
31728
+ return promise;
31772
31729
  }
31773
- if (shown === "")
31774
- return HUMAN_EDIT_DIFF_CUT_NOTE;
31775
- const longestRun = Math.max(0, ...(shown.match(/`+/g) ?? []).map((run) => run.length));
31776
- const fence = "`".repeat(Math.max(3, longestRun + 1));
31777
- const body = shown.endsWith(`
31778
- `) ? shown : `${shown}
31779
- `;
31780
- return `${fence}diff
31781
- ${body}${fence}${note ? `
31782
- ${HUMAN_EDIT_DIFF_CUT_NOTE}` : ""}`;
31783
- }
31784
-
31785
- // ../envoy-client/src/delivery.ts
31786
- var KNOWN_SOURCES = EnvelopeSchema.shape.source.enum;
31787
- var FOREIGN_SESSION_ID = /\b01a0[0-9a-f]{4}-[0-9a-f]{4}-7[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}\b/g;
31788
- var AskAuthorPayloadSchema = object({
31789
- author: object({ kind: string2(), id: string2() }).passthrough()
31790
- });
31791
- var InboundSenderSchema = object({
31792
- session_id: string2().optional(),
31793
- machine: string2().optional(),
31794
- cwd: string2().optional(),
31795
- title: string2().optional(),
31796
- roles: array(string2()).optional()
31797
- });
31798
- var InboundEnvelopeSchema = object({
31799
- event_id: string2().optional(),
31800
- source: string2(),
31801
- source_event_id: string2().optional(),
31802
- source_session: string2().optional(),
31803
- topic: string2().optional(),
31804
- dedupe_key: string2().optional(),
31805
- issued_at: number2().int().optional(),
31806
- expires_at: number2().int().optional(),
31807
- payload_summary: string2().optional(),
31808
- payload: string2().optional(),
31809
- sender: InboundSenderSchema.optional(),
31810
- in_reply_to: string2().optional(),
31811
- supersedes: string2().optional(),
31812
- urgency: string2().optional(),
31813
- expects_reply: string2().optional()
31814
- }).passthrough();
31815
- function tolerantShape(shape) {
31816
- return Object.fromEntries(Object.entries(shape).map(([key, schema]) => [key, _catch2(schema, undefined)]));
31817
- }
31818
- var TolerantInboundEnvelopeSchema = object({
31819
- ...tolerantShape(InboundEnvelopeSchema.shape),
31820
- source: InboundEnvelopeSchema.shape.source.optional().catch(undefined),
31821
- sender: object(tolerantShape(InboundSenderSchema.shape)).optional().catch(undefined)
31822
- }).passthrough();
31823
- function dispatchReplyPath(resource, id) {
31824
- const collection = resource === "message" ? "messages" : "comments";
31825
- return `/api/v1/${collection}/${encodeURIComponent(id)}/reply`;
31730
+ const stop = () => {
31731
+ clearTimeout(timer);
31732
+ reject(signal.reason);
31733
+ };
31734
+ const timer = setTimeout(() => {
31735
+ signal.removeEventListener("abort", stop);
31736
+ resolve();
31737
+ }, ms);
31738
+ signal.addEventListener("abort", stop, { once: true });
31739
+ return promise;
31826
31740
  }
31827
- async function postDeliveryReply(config, sessionId, delivery, result) {
31828
- const response = await fetch(`${config.url}${dispatchReplyPath(delivery.resource, delivery.id)}`, {
31829
- method: "POST",
31830
- headers: { Authorization: `Bearer ${config.token}`, "Content-Type": "application/json" },
31831
- body: JSON.stringify({
31832
- actor: { kind: "session", id: sessionId },
31833
- attempt: delivery.attempt,
31834
- ...delivery.replyFields,
31835
- ...result
31836
- })
31741
+ function retryAfterMs(response) {
31742
+ const value = response.headers.get("Retry-After")?.trim() ?? "";
31743
+ if (/^\d+$/.test(value))
31744
+ return Number(value) * 1000;
31745
+ const at = Date.parse(value);
31746
+ return Number.isNaN(at) ? 0 : Math.max(0, at - Date.now());
31747
+ }
31748
+ var KEYED_LAYER_MEMORY_MS = 5 * 60000;
31749
+ var KEYED_LAYER_SEEN = new Map;
31750
+ var KEYED_LAYER_PROBES = new Map;
31751
+ var KEY_LAYER_PROBE_MS = 5000;
31752
+ function keyEchoed(response, key) {
31753
+ const echoed = response.headers.get(IDEMPOTENCY_KEY_HEADER)?.trim() ?? "";
31754
+ return echoed.replace(/^"(.*)"$/, "$1") === key;
31755
+ }
31756
+ var STREAMED_BODY_MIN = 1 << 20;
31757
+ var STREAMED_BODY_CHUNK = 64 << 10;
31758
+ function attemptBody(body, headers, progress) {
31759
+ const bytes = typeof body.content === "string" ? new TextEncoder().encode(body.content) : body.content;
31760
+ if (bytes.byteLength < STREAMED_BODY_MIN)
31761
+ return { body: body.content, headers };
31762
+ let sent = 0;
31763
+ const stream = new ReadableStream({
31764
+ pull(controller) {
31765
+ progress();
31766
+ if (sent >= bytes.byteLength) {
31767
+ controller.close();
31768
+ return;
31769
+ }
31770
+ const end = Math.min(sent + STREAMED_BODY_CHUNK, bytes.byteLength);
31771
+ controller.enqueue(bytes.subarray(sent, end));
31772
+ sent = end;
31773
+ }
31837
31774
  });
31838
- if (!response.ok) {
31839
- throw new Error(`Dispatch reply failed: ${response.status} ${await response.text()}`);
31775
+ return { body: stream, headers: { ...headers, "Content-Length": String(bytes.byteLength) } };
31776
+ }
31777
+
31778
+ class WriteAttemptSilent extends Error {
31779
+ name = "WriteAttemptSilent";
31780
+ constructor(silenceMs) {
31781
+ super(`made no progress for ${silenceMs / 1000} s, so it was cut off`);
31840
31782
  }
31841
31783
  }
31842
- function expectsLaneReceipt(frame) {
31843
- return frame.reply !== undefined && frame.reply !== "" && frame.subject === frame.directSubject && frame.envelopeTopic !== undefined && frame.envelopeTopic !== frame.directSubject;
31844
- }
31845
- async function* readArrivals(subscription, now = Date.now) {
31846
- const source = subscription[Symbol.asyncIterator]();
31847
- const arrived = [];
31848
- let stopped;
31849
- let left = false;
31850
- let wake;
31851
- const signal = () => {
31852
- wake?.();
31853
- wake = undefined;
31854
- };
31855
- (async () => {
31784
+ var NULL_BODY_STATUSES = new Set([101, 204, 205, 304]);
31785
+ async function writeAnswer(response, key) {
31786
+ const echoed = keyEchoed(response, key);
31787
+ if (response.ok || NULL_BODY_STATUSES.has(response.status)) {
31788
+ return { response, again: false, reached: false, echoed, unjudged: false };
31789
+ }
31790
+ const { status } = response;
31791
+ const text = await response.text();
31792
+ let shape = {};
31793
+ if (isJson(response)) {
31856
31794
  try {
31857
- for (;; ) {
31858
- const read = await source.next();
31859
- if (read.done === true || left)
31860
- break;
31861
- arrived.push({ message: read.value, receivedAt: now() });
31862
- signal();
31863
- }
31864
- stopped = { failed: false };
31865
- } catch (error) {
31866
- stopped = { error, failed: true };
31867
- }
31868
- signal();
31869
- })();
31870
- try {
31871
- for (;; ) {
31872
- const next = arrived.shift();
31873
- if (next !== undefined) {
31874
- yield next;
31875
- continue;
31876
- }
31877
- if (stopped?.failed === true)
31878
- throw stopped.error;
31879
- if (stopped !== undefined)
31880
- return;
31881
- const { promise, resolve } = Promise.withResolvers();
31882
- wake = resolve;
31883
- await promise;
31884
- }
31885
- } finally {
31886
- if (stopped === undefined) {
31887
- left = true;
31888
- Promise.resolve(source.return?.()).catch(() => {
31889
- return;
31890
- });
31795
+ shape = asErrorShape(JSON.parse(text));
31796
+ } catch {
31797
+ shape = {};
31891
31798
  }
31892
31799
  }
31893
- }
31894
- var DedupeIdentitySchema = object({
31895
- event_id: string2().min(1).optional(),
31896
- dedupe_key: string2().min(1).optional(),
31897
- source: string2().optional(),
31898
- source_event_id: string2().optional()
31899
- });
31900
- var DELIVERY_DEDUPE_KEY_LIMIT = 250000;
31901
- var DELIVERY_EVENT_ID_LIMIT = 1e4;
31902
- function createDeliveryDedupe(now = Date.now) {
31903
- const keys = new Map;
31904
- let events = new Map;
31905
- let olderEvents = new Map;
31906
- const pendingKeys = new Map;
31907
- const pendingEvents = new Map;
31908
- let claims = 0;
31800
+ const again = retriesUnderKey(status, shape.code);
31909
31801
  return {
31910
- claim(frame) {
31911
- const eventId = frame?.event_id;
31912
- if (eventId !== undefined && (events.has(eventId) || olderEvents.has(eventId))) {
31913
- return;
31914
- }
31915
- const key = frame?.dedupe_key;
31916
- const named = frame !== undefined && key !== undefined && dedupeKeyNamesItsEvent(frame);
31917
- const at = now();
31918
- if (named) {
31919
- const claimedAt = keys.get(key);
31920
- if (claimedAt !== undefined && at - claimedAt < DELIVERY_DUPLICATE_WINDOW_MS) {
31921
- return;
31922
- }
31923
- for (const [oldest, deliveredAt] of keys) {
31924
- if (at - deliveredAt < DELIVERY_DUPLICATE_WINDOW_MS)
31925
- break;
31926
- keys.delete(oldest);
31927
- }
31928
- keys.delete(key);
31929
- if (keys.size >= DELIVERY_DEDUPE_KEY_LIMIT) {
31930
- const oldest = keys.keys().next();
31931
- if (oldest.done !== true)
31932
- keys.delete(oldest.value);
31933
- }
31934
- keys.set(key, at);
31935
- }
31936
- const claim = ++claims;
31937
- if (eventId !== undefined) {
31938
- if (events.size >= DELIVERY_EVENT_ID_LIMIT / 2) {
31939
- olderEvents = events;
31940
- events = new Map;
31941
- }
31942
- events.set(eventId, claim);
31943
- pendingEvents.set(eventId, claim);
31944
- }
31945
- if (named)
31946
- pendingKeys.set(key, claim);
31947
- let open = true;
31948
- const close = () => {
31949
- if (!open)
31950
- return;
31951
- open = false;
31952
- if (eventId !== undefined && pendingEvents.get(eventId) === claim) {
31953
- pendingEvents.delete(eventId);
31954
- }
31955
- if (named && pendingKeys.get(key) === claim)
31956
- pendingKeys.delete(key);
31957
- };
31958
- let released = false;
31959
- return {
31960
- release() {
31961
- close();
31962
- if (released)
31963
- return;
31964
- released = true;
31965
- if (named && keys.get(key) === at)
31966
- keys.delete(key);
31967
- if (eventId === undefined)
31968
- return;
31969
- if (events.get(eventId) === claim)
31970
- events.delete(eventId);
31971
- if (olderEvents.get(eventId) === claim)
31972
- olderEvents.delete(eventId);
31973
- },
31974
- settle: close
31975
- };
31976
- },
31977
- pending(frame) {
31978
- const eventId = frame.event_id;
31979
- const key = frame.dedupe_key;
31980
- return eventId !== undefined && pendingEvents.has(eventId) || key !== undefined && dedupeKeyNamesItsEvent(frame) && pendingKeys.has(key);
31981
- }
31802
+ response: new Response(text, {
31803
+ status,
31804
+ statusText: response.statusText,
31805
+ headers: response.headers
31806
+ }),
31807
+ again,
31808
+ reached: status >= 500 || again && status === 409,
31809
+ echoed,
31810
+ unjudged: !echoed && typeof shape.error === "string"
31982
31811
  };
31983
31812
  }
31984
- function isCommentTargetedDelivery(delivery) {
31985
- return "comment_id" in delivery;
31986
- }
31987
- var DispatchTargetedFrameSchema = object({
31988
- event: DispatchEventSchema,
31989
- delivery: DispatchTargetedDeliverySchema
31990
- }).superRefine(({ event, delivery }, context) => {
31991
- if (event.type === "message.created" && !isCommentTargetedDelivery(delivery) && DispatchTargetedMessagePayloadSchema.safeParse(event.payload).success) {
31992
- return;
31813
+ function whyNotAPage(answer) {
31814
+ if (typeof answer === "string") {
31815
+ return `text that is not a JSON page, ${GATEWAY_PAGE}, so a retry may succeed.`;
31993
31816
  }
31994
- if (event.type === "comment.created" && isCommentTargetedDelivery(delivery) && DispatchTargetedCommentPayloadSchema.safeParse(event.payload).success) {
31995
- return;
31817
+ let what;
31818
+ if (Array.isArray(answer)) {
31819
+ 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";
31820
+ } else if (answer === null || typeof answer !== "object") {
31821
+ what = answer === null ? "null" : `a ${typeof answer}`;
31822
+ } else {
31823
+ const fields = answer;
31824
+ const lacking = [
31825
+ ...Array.isArray(fields.issues) ? [] : ["an issues array"],
31826
+ ...["total", "limit", "offset"].filter((name) => typeof fields[name] !== "number").map((name) => `a numeric ${name}`)
31827
+ ];
31828
+ if (lacking.length === 0)
31829
+ return;
31830
+ what = `an object without ${lacking.join(" or ")}`;
31996
31831
  }
31997
- context.addIssue({
31998
- code: "custom",
31999
- message: event.type === "comment.created" ? "targeted delivery requires a complete comment.created event" : "targeted delivery requires a complete message.created event"
32000
- });
32001
- });
32002
- var RecoverableDispatchDeliveryFailureSchema = object({
32003
- event: object({
32004
- type: _enum2(["message.created", "comment.created"]),
32005
- issue_key: string2().nullable(),
32006
- payload: object({ id: string2(), body: string2().optional() }).passthrough()
32007
- }).passthrough(),
32008
- delivery: DispatchTargetedDeliverySchema
32009
- }).refine(({ event, delivery }) => event.type === "comment.created" ? isCommentTargetedDelivery(delivery) : !isCommentTargetedDelivery(delivery) && DispatchTargetedResourceIDSchema.safeParse(event.payload.id).success, { message: "delivery resource must match its event type" });
32010
- function eventPictures(event) {
32011
- let text;
32012
- if (event.type.startsWith("message.")) {
32013
- const parsed = MessageEventPayloadSchema.safeParse(event.payload);
32014
- text = parsed.success ? parsed.data.body : undefined;
32015
- } else if (event.type.startsWith("comment.")) {
32016
- const parsed = CommentEventPayloadSchema.safeParse(event.payload);
32017
- text = parsed.success ? parsed.data.body : undefined;
32018
- } else if (event.type.startsWith("ask.")) {
32019
- const parsed = (event.type === "ask.edited" ? AskEditedEventPayloadSchema : AskEventPayloadSchema).safeParse(event.payload);
32020
- if (parsed.success) {
32021
- switch (event.type) {
32022
- case "ask.answered":
32023
- text = parsed.data.answer?.text;
32024
- break;
32025
- case "ask.resolved":
32026
- text = parsed.data.resolution?.reason;
32027
- break;
32028
- case "ask.opened":
32029
- case "ask.edited":
32030
- text = parsed.data.question;
32031
- break;
32032
- }
32033
- }
31832
+ return `${what}. Retrying will not help: the same request gets the same answer until that ` + "Dispatch is upgraded or fixed.";
31833
+ }
31834
+ function whyNotAnArray(answer) {
31835
+ if (typeof answer === "string")
31836
+ return `text that is not JSON, ${GATEWAY_PAGE}, so a retry may succeed`;
31837
+ if (answer === null)
31838
+ return "null";
31839
+ if (typeof answer !== "object")
31840
+ return `a ${typeof answer}`;
31841
+ if ("issues" in answer && Array.isArray(answer.issues)) {
31842
+ return "a page, so this Dispatch pages a request that carries no limit and no offset";
32034
31843
  }
32035
- return typeof text === "string" ? pictureAddresses(text) : [];
31844
+ return "an object that is not the listing";
32036
31845
  }
32037
- function senderLabel(envelope) {
32038
- const sender = envelope.source_session ?? envelope.source ?? "unknown";
32039
- return envelope.sender?.title === undefined ? sender : `${sender} (${envelope.sender.title})`;
31846
+ var GATEWAY_PAGE = "which looks like a proxy or gateway page rather than Dispatch's own answer";
31847
+ function gatewayAdvice(method, status) {
31848
+ if (!transientStatus(status)) {
31849
+ return "a retry gets the same answer until the Dispatch URL, or whatever answers in its place, is fixed";
31850
+ }
31851
+ if (method === "GET")
31852
+ return "a retry may succeed";
31853
+ 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";
32040
31854
  }
32041
- function replyWith(envelope) {
32042
- if (envelope.source !== "agent" || envelope.source_session === undefined)
32043
- return;
32044
- return {
32045
- tool: "envoy_send",
32046
- args: {
32047
- session_id: envelope.source_session,
32048
- ...envelope.event_id === undefined ? {} : { in_reply_to: envelope.event_id },
32049
- message: "..."
32050
- }
32051
- };
31855
+ function transientStatus(status) {
31856
+ return status >= 500 || status === 408 || status === 429;
32052
31857
  }
32053
- var DISPATCH_PAYLOAD_SCHEMAS = {
32054
- "issue.created": IssueEventPayloadSchema,
32055
- "issue.updated": IssueEventPayloadSchema,
32056
- "issue.closed": IssueEventPayloadSchema,
32057
- "artifact.created": ArtifactCreatedEventPayloadSchema,
32058
- "artifact.version": ArtifactVersionEventPayloadSchema,
32059
- "artifact.human_edited": ArtifactHumanEditedEventPayloadSchema,
32060
- "ask.opened": AskEventPayloadSchema,
32061
- "ask.anchor_refreshed": AskEventPayloadSchema,
32062
- "ask.edited": AskEditedEventPayloadSchema,
32063
- "ask.handed_back": AskEventPayloadSchema,
32064
- "ask.answered": AskEventPayloadSchema,
32065
- "ask.resolved": AskEventPayloadSchema,
32066
- "comment.created": CommentEventPayloadSchema,
32067
- "comment.anchor_refreshed": CommentEventPayloadSchema,
32068
- "comment.resolved": CommentEventPayloadSchema,
32069
- "comment.reopened": CommentEventPayloadSchema,
32070
- "comment.edited": CommentEventPayloadSchema,
32071
- "suggestion.accepted": CommentEventPayloadSchema,
32072
- "suggestion.rejected": CommentEventPayloadSchema,
32073
- "message.created": MessageEventPayloadSchema,
32074
- "message.delivery": MessageDeliveryEventPayloadSchema,
32075
- "message.answered": MessageEventPayloadSchema,
32076
- "child.status": ChildStatusEventPayloadSchema
32077
- };
32078
- function topicDocument(topic) {
32079
- if (topic?.startsWith(DISPATCH_DOCUMENT_TOPIC_PREFIX) !== true)
32080
- return;
32081
- const [project, slug] = topic.slice(DISPATCH_DOCUMENT_TOPIC_PREFIX.length).split(".", 3);
32082
- return project !== undefined && project !== "" && slug !== undefined && slug !== "" ? { project, slug } : undefined;
32083
- }
32084
- function dispatchOwner(event, topic) {
32085
- if (event.issue_key !== null)
32086
- return event.issue_key;
32087
- const document = topicDocument(topic);
32088
- if (document !== undefined)
32089
- return `${document.project} / ${document.slug}`;
32090
- return event.artifact_id ?? "unknown";
31858
+ function reachesDispatch(status) {
31859
+ return status >= 500;
32091
31860
  }
32092
- function dispatchCommentReplyWith(event, topic, comment) {
32093
- if (comment === undefined || comment.id === undefined)
32094
- return;
32095
- const reply = comment.ask_id;
32096
- const thread = reply === undefined || reply === null || reply === "" ? "reply_to" : "reply_to_ask";
32097
- const threadID = thread === "reply_to" ? comment.id : String(reply);
32098
- if (event.issue_key !== null) {
32099
- return {
32100
- command: commandLine("dispatch_comment", {
32101
- issue: event.issue_key,
32102
- [thread]: threadID,
32103
- body: "..."
32104
- })
32105
- };
31861
+ var REDACTED = "[redacted]";
31862
+ var EXCERPT_SCAN_LIMIT = 64 * 1024;
31863
+ var BEARER_PIECE = 8;
31864
+ function redactBearer(text, bearer) {
31865
+ if (bearer === "")
31866
+ return text.slice(0, EXCERPT_SCAN_LIMIT);
31867
+ const length = Math.min(BEARER_PIECE, bearer.length);
31868
+ const scanned = text.slice(0, EXCERPT_SCAN_LIMIT + length - 1);
31869
+ const covered = new Uint8Array(scanned.length);
31870
+ const pieces = new Set;
31871
+ for (let at = 0;at + length <= bearer.length; at++)
31872
+ pieces.add(bearer.slice(at, at + length));
31873
+ for (const piece of pieces) {
31874
+ let found = scanned.indexOf(piece);
31875
+ while (found !== -1) {
31876
+ covered.fill(1, found, found + length);
31877
+ found = scanned.indexOf(piece, found + 1);
31878
+ }
32106
31879
  }
32107
- let project = comment.project_key;
32108
- let artifact = comment.artifact_slug;
32109
- if (project === undefined || project === "" || artifact === undefined || artifact === "") {
32110
- [project, artifact] = dispatchOwner(event, topic).split(" / ", 2);
31880
+ let redacted = "";
31881
+ let kept = 0;
31882
+ for (let start = covered.indexOf(1);start !== -1; start = covered.indexOf(1, kept)) {
31883
+ redacted += `${scanned.slice(kept, start)}${REDACTED}`;
31884
+ const end = covered.indexOf(0, start);
31885
+ kept = end === -1 ? scanned.length : end;
32111
31886
  }
32112
- if (project === undefined || project === "" || artifact === undefined || artifact === "")
32113
- return;
32114
- return {
32115
- command: commandLine("dispatch_comment", {
32116
- project,
32117
- artifact,
32118
- [thread]: threadID,
32119
- body: "..."
32120
- })
32121
- };
31887
+ return `${redacted}${scanned.slice(kept, EXCERPT_SCAN_LIMIT)}`.slice(0, EXCERPT_SCAN_LIMIT);
32122
31888
  }
32123
- function askResolutionText(resolution) {
32124
- if (resolution === null || resolution === undefined)
32125
- return;
32126
- const kind = resolution.kind ?? "resolved";
32127
- const reason = resolution.reason ?? "";
32128
- return reason === "" ? kind : `${kind}: ${reason}`;
31889
+ function excerpt(text, token) {
31890
+ const plain = redactBearer(text, token.trim()).replace(/<(script|style)\b[^<>]*>(?:[\s\S]*?<\/\1\s*>|[\s\S]*$)/gi, " ").replace(/<[^<>]*>/g, " ");
31891
+ return textHead(plain.replace(/(\bauthorization["']?\s*[:=]\s*["']?(?:(?:bearer|basic|digest|token)\s+)?)[^\s"'<>,;]+/gi, `$1${REDACTED}`).replace(/(\bbearer\s+)[^\s"'<>,;]+/gi, `$1${REDACTED}`));
32129
31892
  }
32130
- function dispatchCompact(event, comment) {
32131
- if (event.type === "artifact.human_edited") {
32132
- const edit = ArtifactHumanEditedEventPayloadSchema.safeParse(event.payload);
32133
- if (!edit.success)
32134
- return;
32135
- return { askId: undefined, record: { edit: humanEditHead(edit.data) } };
31893
+
31894
+ class DispatchClient {
31895
+ token;
31896
+ fetchImpl;
31897
+ writeRetry;
31898
+ #baseUrl;
31899
+ #resolvedIssues = new Map;
31900
+ #signal;
31901
+ constructor(baseUrl, token, fetchImpl = fetch, signal, writeRetry = DISPATCH_WRITE_RETRY) {
31902
+ this.token = token;
31903
+ this.fetchImpl = fetchImpl;
31904
+ this.writeRetry = writeRetry;
31905
+ this.#baseUrl = baseUrl.replace(/\/+$/, "");
31906
+ this.#signal = requestSignal(signal);
32136
31907
  }
32137
- if (event.type === "comment.created") {
32138
- if (comment?.ask_id === undefined || comment.ask_id === null)
32139
- return;
32140
- const question = dispatchAskQuestion(comment);
32141
- return {
32142
- askId: comment.ask_id,
32143
- record: {
32144
- ...question === undefined ? {} : { question },
32145
- reply: comment.body ?? "",
32146
- ...comment.ask_state === undefined ? {} : { state: comment.ask_state },
32147
- ...comment.ask_waiting_on === undefined ? {} : { waiting_on: comment.ask_waiting_on }
32148
- }
32149
- };
31908
+ async issue(input) {
31909
+ return this.#json("POST", ["api", "v1", "issues"], input);
32150
31910
  }
32151
- if (!event.type.startsWith("ask."))
32152
- return;
32153
- const ask = (event.type === "ask.edited" ? AskEditedEventPayloadSchema : AskEventPayloadSchema).safeParse(event.payload);
32154
- if (!ask.success)
32155
- return;
32156
- let record = { question: textHead(ask.data.question ?? "") };
32157
- switch (event.type) {
32158
- case "ask.opened":
32159
- case "ask.edited": {
32160
- const options = (ask.data.options ?? []).map((option) => option.label ?? "").filter((label) => label !== "");
32161
- const quote = ask.data.anchor?.quote;
32162
- const { project, slug } = ask.data.anchor_artifact ?? {};
32163
- const document = project !== undefined && project !== "" && slug !== undefined && slug !== "" ? `${project}/${slug}` : undefined;
32164
- const previous = "previous" in ask.data && ask.data.previous !== undefined ? textHead(ask.data.previous.question) : undefined;
32165
- record = {
32166
- ...record,
32167
- ...options.length === 0 ? {} : { options },
32168
- ...quote === undefined || quote === "" ? {} : { quote: textHead(quote) },
32169
- ...document === undefined ? {} : { document },
32170
- ...previous === undefined ? {} : { previous }
32171
- };
32172
- break;
32173
- }
32174
- case "ask.answered": {
32175
- const previousAnswer = ask.data.previous_answer;
32176
- record = {
32177
- ...record,
32178
- answer: askAnswerText(ask.data.answer),
32179
- ...previousAnswer === null || previousAnswer === undefined ? {} : { previous_answer: askAnswerText(previousAnswer) }
32180
- };
32181
- break;
32182
- }
32183
- case "ask.resolved": {
32184
- const resolved = askResolutionText(ask.data.resolution);
32185
- record = resolved === undefined ? record : { ...record, resolved };
32186
- break;
32187
- }
32188
- default:
32189
- break;
31911
+ async resolveIssue(issueReference) {
31912
+ return this.#resolveIssue(issueReference);
32190
31913
  }
32191
- return { askId: ask.data.id, record };
32192
- }
32193
- function dispatchPayload(event) {
32194
- const schema = DISPATCH_PAYLOAD_SCHEMAS[event.type];
32195
- if (schema === undefined)
32196
- return event.payload;
32197
- const parsed = schema.safeParse(event.payload);
32198
- return parsed.success ? parsed.data : event.payload;
32199
- }
32200
- function hasTarget(value) {
32201
- return isObject2(value) && "target" in value;
32202
- }
32203
- function dispatchPayloadForReader(event, sessionID) {
32204
- const payload = dispatchPayload(event);
32205
- if (!hasTarget(payload))
32206
- return payload;
32207
- const target = payload.target;
32208
- return target === `session:${sessionID}` ? { ...payload, target: `you (${target})` } : payload;
32209
- }
32210
- function dispatchAskQuestion(comment) {
32211
- return comment?.ask_question !== undefined && comment.ask_question !== "" ? textHead(comment.ask_question) : undefined;
32212
- }
32213
- function dispatchReplyRef(event, topic, inReplyTo, comment) {
32214
- let kind;
32215
- let document = topicDocument(topic);
32216
- if (event.type.startsWith("ask.")) {
32217
- kind = "ask";
32218
- } else if (event.type.startsWith("message.")) {
32219
- kind = "message";
32220
- } else if (event.type === "comment.created") {
32221
- if (comment === undefined || comment.ask_id === undefined || comment.ask_id === null) {
32222
- return inReplyTo;
32223
- }
32224
- kind = "ask";
32225
- const { project_key: project, artifact_slug: slug } = comment;
32226
- if (project !== undefined && project !== "" && slug !== undefined && slug !== "") {
32227
- document = { project, slug };
32228
- }
32229
- } else {
32230
- return inReplyTo;
31914
+ async listIssuePage(options, page) {
31915
+ const path = ["api", "v1", "issues"];
31916
+ const query = { ...options, limit: page.limit, offset: page.offset };
31917
+ const answer = await this.#json("GET", path, undefined, query);
31918
+ const refusal = whyNotAPage(answer);
31919
+ if (refusal === undefined)
31920
+ return answer;
31921
+ throw new Error(`GET ${this.#url(path, query)} asked for a page ({issues, total, limit, offset}) and got ` + refusal);
32231
31922
  }
32232
- if (event.issue_key !== null) {
32233
- return dispatchChildRef(dispatchIssueRef(event.issue_key), kind, inReplyTo);
31923
+ async listAllIssues(options) {
31924
+ const path = ["api", "v1", "issues"];
31925
+ const query = { ...options };
31926
+ const answer = await this.#json("GET", path, undefined, query);
31927
+ if (Array.isArray(answer))
31928
+ return answer;
31929
+ throw new Error(`GET ${this.#url(path, query)} asked for the unpaged listing and got ${whyNotAnArray(answer)}.`);
32234
31930
  }
32235
- if (document === undefined)
32236
- return inReplyTo;
32237
- return dispatchChildRef(dispatchDocumentRef(document.project, document.slug), kind, inReplyTo);
32238
- }
32239
- function isObject2(value) {
32240
- return typeof value === "object" && value !== null;
32241
- }
32242
- function parseDispatchFrame(rawPayload) {
32243
- let value;
32244
- try {
32245
- value = JSON.parse(rawPayload);
32246
- } catch {
32247
- return { raw: rawPayload };
31931
+ async listProjectArtifacts(project, unlinked = false) {
31932
+ return this.#json("GET", ["api", "v1", "projects", project, "artifacts"], undefined, unlinked ? { unlinked: "true" } : undefined);
32248
31933
  }
32249
- if (isObject2(value) && "delivery" in value) {
32250
- const targeted = DispatchTargetedFrameSchema.safeParse(value);
32251
- if (targeted.success) {
32252
- const wireFrame = value;
32253
- return {
32254
- event: targeted.data.event,
32255
- notify: wireFrame.event.notify,
32256
- delivery: targeted.data.delivery
32257
- };
32258
- }
32259
- const recoverable = RecoverableDispatchDeliveryFailureSchema.safeParse(value);
32260
- if (recoverable.success) {
32261
- const delivery = recoverable.data.delivery;
32262
- const commentDelivery = isCommentTargetedDelivery(delivery);
32263
- const resource = commentDelivery ? "comment" : "message";
32264
- const id = commentDelivery ? delivery.comment_id : recoverable.data.event.payload.id;
32265
- return {
32266
- raw: value,
32267
- rejectedDelivery: {
32268
- resource,
32269
- id,
32270
- attempt: delivery.attempt,
32271
- mode: delivery.mode,
32272
- replyPath: dispatchReplyPath(resource, id),
32273
- replyFields: commentDelivery ? { target: delivery.target } : {},
32274
- issueKey: recoverable.data.event.issue_key,
32275
- body: recoverable.data.event.payload.body ?? ""
32276
- },
32277
- malformedDelivery: true
32278
- };
32279
- }
32280
- return { raw: value, malformedDelivery: true };
31934
+ async projectArtifact(project, input) {
31935
+ return this.#upload(["api", "v1", "projects", project, "artifacts"], input);
32281
31936
  }
32282
- const parsed = DispatchEventSchema.safeParse(value);
32283
- if (!parsed.success)
32284
- return { raw: value };
32285
- const wireEvent = value;
32286
- return {
32287
- event: parsed.data,
32288
- notify: wireEvent.notify,
32289
- delivery: undefined
32290
- };
32291
- }
32292
- function inboundTimestamp(milliseconds) {
32293
- if (milliseconds === undefined)
32294
- return "unknown";
32295
- const date = new Date(Math.floor(milliseconds / 1000) * 1000);
32296
- return Number.isNaN(date.getTime()) ? "unknown" : date.toISOString().replace(".000Z", "Z");
32297
- }
32298
- function renderInbound(raw, sessionID, subject) {
32299
- let value;
32300
- try {
32301
- value = JSON.parse(raw);
32302
- } catch {
32303
- return {
32304
- skip: false,
32305
- content: encode3({
32306
- envoy: { topic: subject ?? "unknown", unrecognised: "payload was not JSON" }
32307
- })
32308
- };
31937
+ async getProjectArtifact(project, slug) {
31938
+ return this.#json("GET", ["api", "v1", "projects", project, "artifacts", slug]);
32309
31939
  }
32310
- const parsed = InboundEnvelopeSchema.safeParse(value);
32311
- const parseIssues = parsed.success ? [] : parsed.error.issues.map((issue) => issue.path.join(".") || "envelope");
32312
- let envelope;
32313
- if (parsed.success) {
32314
- envelope = parsed.data;
32315
- } else {
32316
- const tolerant = TolerantInboundEnvelopeSchema.safeParse(value);
32317
- if (!tolerant.success) {
32318
- return {
32319
- skip: false,
32320
- content: encode3({ envoy: { unrecognised: parseIssues.join(", ") || "envelope" } })
32321
- };
32322
- }
32323
- const data = tolerant.data;
32324
- envelope = { ...data, source: data.source ?? "unknown" };
31940
+ async agentArtifact(sessionId, input) {
31941
+ return this.#upload(["api", "v1", "agents", sessionId, "artifacts"], input);
32325
31942
  }
32326
- let dispatchEvent;
32327
- let dispatchActor;
32328
- let dispatchIssue;
32329
- let dispatchReply;
32330
- let delivery;
32331
- let rejectedDelivery;
32332
- let malformedDelivery = false;
32333
- let pictures = [];
32334
- let inReplyTo = envelope.in_reply_to;
32335
- let askAuthor;
32336
- let trailer = "";
32337
- const dispatchRendered = envelope.source === "dispatch" && envelope.payload !== undefined;
32338
- if (envelope.source === "dispatch") {
32339
- const topic = subject ?? envelope.topic;
32340
- if (envelope.payload === undefined) {
32341
- dispatchIssue = "payload";
32342
- } else {
32343
- const frame = parseDispatchFrame(envelope.payload);
32344
- if ("event" in frame) {
32345
- if (frame.notify === false && topic?.startsWith(DISPATCH_TOPIC_PREFIX) === true) {
32346
- return { skip: true, content: "", envelope };
32347
- }
32348
- if (frame.event.actor.kind === "session" && frame.event.actor.id === sessionID) {
32349
- return { skip: true, content: "", envelope };
32350
- }
32351
- if (frame.event.type === "subscription.removed") {
32352
- const removed = SubscriptionRemovedEventPayloadSchema.safeParse(frame.event.payload);
32353
- if (!removed.success || removed.data.session_id !== sessionID) {
32354
- return { skip: true, content: "", envelope };
32355
- }
32356
- const who = removed.data.by?.id ?? "someone";
32357
- return {
32358
- skip: false,
32359
- content: `Unsubscribed from ${dispatchOwner(frame.event, topic)} by ${who}`,
32360
- envelope
32361
- };
32362
- }
32363
- if (frame.event.type === "ask.follower_added" || frame.event.type === "ask.follower_removed") {
32364
- const follower = AskFollowerEventPayloadSchema.safeParse(frame.event.payload);
32365
- if (!follower.success || follower.data.session_id !== sessionID) {
32366
- return { skip: true, content: "", envelope };
32367
- }
32368
- const who = follower.data.by?.id ?? "someone";
32369
- const owner = dispatchOwner(frame.event, topic);
32370
- const ask = follower.data.ask_id ?? "?";
32371
- return {
32372
- skip: false,
32373
- content: frame.event.type === "ask.follower_added" ? `Now following ask ${ask} on ${owner} (added by ${who}): its answer and replies reach you directly; ${commandLine("dispatch_follow", { ask, action: "unfollow" })} to stop.` : `No longer following ask ${ask} on ${owner} (removed by ${who}).`,
32374
- envelope
32375
- };
32376
- }
32377
- const comment = frame.event.type === "comment.created" ? CommentEventPayloadSchema.safeParse(frame.event.payload) : undefined;
32378
- const commentPayload = comment?.success === true ? comment.data : undefined;
32379
- const compact = dispatchCompact(frame.event, commentPayload);
32380
- if (frame.event.type.startsWith("ask.")) {
32381
- const asked = AskAuthorPayloadSchema.safeParse(frame.event.payload);
32382
- if (asked.success && asked.data.author.kind === "session") {
32383
- askAuthor = asked.data.author.id;
32384
- }
32385
- }
32386
- if (inReplyTo !== undefined) {
32387
- inReplyTo = dispatchReplyRef(frame.event, topic, inReplyTo, commentPayload);
32388
- }
32389
- dispatchReply = dispatchCommentReplyWith(frame.event, topic, commentPayload);
32390
- if (frame.event.type === "message.created") {
32391
- const message = DispatchTargetedMessagePayloadSchema.safeParse(frame.event.payload);
32392
- const requested = DispatchTargetedDeliverySchema.safeParse(frame.delivery);
32393
- if (message.success && requested.success && !isCommentTargetedDelivery(requested.data)) {
32394
- delivery = {
32395
- resource: "message",
32396
- id: message.data.id,
32397
- attempt: requested.data.attempt,
32398
- mode: requested.data.mode,
32399
- replyPath: dispatchReplyPath("message", message.data.id),
32400
- replyFields: {},
32401
- issueKey: frame.event.issue_key,
32402
- body: message.data.body,
32403
- ...typeof message.data.broadcast_id === "string" ? { broadcastId: message.data.broadcast_id } : {}
32404
- };
32405
- dispatchReply = {
32406
- command: commandLine("dispatch_message", {
32407
- ...frame.event.issue_key === null ? {} : { issue: frame.event.issue_key },
32408
- in_reply_to: message.data.id,
32409
- body: "..."
32410
- })
32411
- };
32412
- }
32413
- } else if (frame.event.type === "comment.created") {
32414
- const comment = DispatchTargetedCommentPayloadSchema.safeParse(frame.event.payload);
32415
- const requested = DispatchTargetedDeliverySchema.safeParse(frame.delivery);
32416
- if (comment.success && requested.success && isCommentTargetedDelivery(requested.data)) {
32417
- delivery = {
32418
- resource: "comment",
32419
- id: requested.data.comment_id,
32420
- attempt: requested.data.attempt,
32421
- mode: requested.data.mode,
32422
- replyPath: dispatchReplyPath("comment", requested.data.comment_id),
32423
- replyFields: { target: requested.data.target },
32424
- issueKey: frame.event.issue_key,
32425
- body: comment.data.body
32426
- };
32427
- }
32428
- }
32429
- const compactRecord = compact === undefined ? undefined : inReplyTo !== undefined || compact.askId === undefined ? compact.record : {
32430
- ask: dispatchReplyRef(frame.event, topic, compact.askId, commentPayload),
32431
- ...compact.record
32432
- };
32433
- dispatchEvent = {
32434
- owner: dispatchOwner(frame.event, topic),
32435
- type: frame.event.type,
32436
- actor: frame.event.actor,
32437
- ...compactRecord ?? { payload: dispatchPayloadForReader(frame.event, sessionID) }
32438
- };
32439
- dispatchActor = frame.event.actor;
32440
- pictures = eventPictures(frame.event);
32441
- if (frame.event.type === "artifact.human_edited") {
32442
- const edit = ArtifactHumanEditedEventPayloadSchema.safeParse(frame.event.payload);
32443
- if (edit.success)
32444
- trailer = humanEditDiffBlock(edit.data.diff, edit.data.diff_truncated);
32445
- }
32446
- } else {
32447
- dispatchEvent = frame.raw;
32448
- rejectedDelivery = frame.rejectedDelivery;
32449
- malformedDelivery = frame.malformedDelivery === true;
32450
- }
32451
- }
31943
+ async getAgentArtifact(sessionId, slug) {
31944
+ return this.#json("GET", ["api", "v1", "agents", sessionId, "artifacts", slug]);
32452
31945
  }
32453
- let parsedPayload;
32454
- if (!dispatchRendered && envelope.payload !== undefined && (envelope.source === "github" || envelope.payload !== envelope.payload_summary)) {
32455
- try {
32456
- parsedPayload = JSON.parse(envelope.payload);
32457
- } catch {
32458
- parsedPayload = envelope.payload;
32459
- }
31946
+ async getIssueArtifact(issue, slug) {
31947
+ return this.#json("GET", [
31948
+ "api",
31949
+ "v1",
31950
+ "issues",
31951
+ await this.#resolveIssue(issue),
31952
+ "artifacts",
31953
+ slug
31954
+ ]);
32460
31955
  }
32461
- const payloadSummary = envelope.payload_summary ?? "unknown";
32462
- const message = !dispatchRendered && envelope.payload !== undefined && envelope.payload !== envelope.payload_summary ? parsedPayload : undefined;
32463
- const summaryIsHead = typeof message === "string" && envelope.payload_summary !== undefined && message.startsWith(envelope.payload_summary.endsWith("\u2026") ? envelope.payload_summary.slice(0, -1) : envelope.payload_summary);
32464
- let foreignSession;
32465
- for (const part of [envelope.payload_summary ?? "", envelope.payload ?? ""]) {
32466
- for (const match of part.matchAll(FOREIGN_SESSION_ID)) {
32467
- if (match[0] !== envelope.source_session && match[0] !== sessionID && match[0] !== askAuthor) {
32468
- foreignSession = match[0];
31956
+ async search(query, options = {}) {
31957
+ return this.#json("GET", ["api", "v1", "search"], undefined, { q: query, ...options });
31958
+ }
31959
+ async getIssue(issue) {
31960
+ return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue)]);
31961
+ }
31962
+ async updateIssue(issue, input) {
31963
+ return this.#json("PATCH", ["api", "v1", "issues", await this.#resolveIssue(issue)], input);
31964
+ }
31965
+ async claimIssue(issue, input = {}) {
31966
+ return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "claim"], input);
31967
+ }
31968
+ async releaseIssueClaim(issue, input = {}) {
31969
+ return this.#json("DELETE", ["api", "v1", "issues", await this.#resolveIssue(issue), "claim"], input);
31970
+ }
31971
+ async getIssueEvents(issue, after = 0, limit = ISSUE_EVENTS_PAGE_MAX) {
31972
+ return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "events"], undefined, { after, limit });
31973
+ }
31974
+ async read(issueReference, options = {}) {
31975
+ const issueKey = await this.#resolveIssue(issueReference);
31976
+ const issue = await this.getIssue(issueKey);
31977
+ const requested = options.events;
31978
+ const count = requested === undefined ? DEFAULT_ISSUE_READ_EVENTS : requested === "all" ? issue.last_seq : Math.min(requested, issue.last_seq);
31979
+ const events = [];
31980
+ let after = Math.max(0, issue.last_seq - count);
31981
+ while (events.length < count) {
31982
+ const limit = Math.min(ISSUE_EVENTS_PAGE_MAX, count - events.length);
31983
+ const page = await this.getIssueEvents(issueKey, after, limit);
31984
+ events.push(...page);
31985
+ const last = page.at(-1);
31986
+ if (page.length < limit || last === undefined || events.length >= count)
32469
31987
  break;
31988
+ if (last.seq <= after) {
31989
+ throw new Error(`GET /api/v1/issues/${issueKey}/events?after=${after} answered no event after seq ${after}`);
32470
31990
  }
31991
+ after = last.seq;
32471
31992
  }
32472
- if (foreignSession !== undefined)
32473
- break;
31993
+ return { issue, events };
32474
31994
  }
32475
- const role = envelope.sender?.roles?.[0];
32476
- const reply = dispatchReply ?? replyWith(envelope);
32477
- const sourceIssue = parseIssues.includes("source") || KNOWN_SOURCES[envelope.source] !== undefined ? undefined : `source=${envelope.source}`;
32478
- const unrecognised = [
32479
- ...parseIssues,
32480
- ...sourceIssue === undefined ? [] : [sourceIssue],
32481
- ...dispatchIssue === undefined ? [] : [dispatchIssue]
32482
- ].join(", ") || undefined;
32483
- const rendered = {
32484
- ...envelope.topic === agentSubject(sessionID) ? { to: `you (${sessionID})` } : {},
32485
- from: senderLabel(envelope),
32486
- at: inboundTimestamp(envelope.issued_at),
32487
- id: envelope.event_id ?? "unknown",
32488
- ...envelope.expires_at === undefined ? {} : { by: inboundTimestamp(envelope.expires_at) },
32489
- ...envelope.urgency === undefined ? {} : { urgency: envelope.urgency },
32490
- ...envelope.expects_reply === undefined ? {} : { expects_reply: envelope.expects_reply },
32491
- ...inReplyTo === undefined ? {} : { re: inReplyTo },
32492
- ...envelope.supersedes === undefined ? {} : { supersedes: envelope.supersedes },
32493
- ...reply === undefined ? {} : { reply_with: reply },
32494
- ...role === undefined ? {} : {
32495
- reply_role: {
32496
- tool: "envoy_publish",
32497
- args: { topic: `notifications.role.${role}`, message: "..." }
32498
- }
32499
- },
32500
- ...dispatchRendered ? { dispatch: dispatchEvent } : {
32501
- ...summaryIsHead ? {} : { summary: payloadSummary },
32502
- ...message === undefined ? {} : { message }
32503
- },
32504
- ...foreignSession === undefined ? {} : {
32505
- note: `body names session ${foreignSession}; the sender is ${envelope.source_session ?? "unknown"}`
32506
- },
32507
- ...unrecognised === undefined ? {} : { unrecognised }
32508
- };
32509
- return {
32510
- skip: false,
32511
- content: trailer === "" ? encode3({ envoy: rendered }) : `${encode3({ envoy: rendered })}
32512
-
32513
- ${trailer}`,
32514
- envelope,
32515
- ...dispatchActor === undefined ? {} : { dispatchActor },
32516
- ...delivery === undefined ? {} : { delivery },
32517
- ...rejectedDelivery === undefined ? {} : { rejectedDelivery },
32518
- ...malformedDelivery ? { malformedDelivery: true } : {},
32519
- ...pictures.length === 0 ? {} : { pictures }
32520
- };
32521
- }
32522
-
32523
- // ../envoy-client/src/envoy-config.ts
32524
- import {
32525
- chmodSync,
32526
- closeSync as closeSync2,
32527
- existsSync,
32528
- lstatSync,
32529
- mkdtempSync,
32530
- openSync as openSync2,
32531
- readFileSync as readFileSync3,
32532
- readlinkSync,
32533
- rmSync as rmSync2,
32534
- statSync as statSync2
32535
- } from "fs";
32536
- import { homedir, tmpdir } from "os";
32537
- import * as path from "path";
32538
-
32539
- // ../envoy-client/src/json-position.ts
32540
- function jsonErrorPosition(text) {
32541
- let at = 0;
32542
- const fail = () => {
32543
- throw new RangeError("not JSON");
32544
- };
32545
- const space = () => {
32546
- while (at < text.length && `
32547
- \r`.includes(text.charAt(at)))
32548
- at += 1;
32549
- };
32550
- const expect = (char) => {
32551
- if (text.charAt(at) !== char)
32552
- fail();
32553
- at += 1;
32554
- };
32555
- const string = () => {
32556
- expect('"');
32557
- while (at < text.length) {
32558
- const char = text.charAt(at);
32559
- if (char === '"') {
32560
- at += 1;
32561
- return;
32562
- }
32563
- if (char < " ")
32564
- fail();
32565
- at += char === "\\" ? 2 : 1;
31995
+ async ask(issue, input) {
31996
+ return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "asks"], input);
31997
+ }
31998
+ async openAsks(sessionID, since) {
31999
+ return this.#json("GET", ["api", "v1", "asks", "open"], undefined, {
32000
+ author_session: sessionID,
32001
+ ...since === undefined ? {} : { since }
32002
+ });
32003
+ }
32004
+ async openAsksForProject(project) {
32005
+ return this.#json("GET", ["api", "v1", "asks", "open"], undefined, { project });
32006
+ }
32007
+ async listAgents() {
32008
+ return this.#json("GET", ["api", "v1", "agents"]);
32009
+ }
32010
+ async whoami() {
32011
+ return this.#json("GET", ["api", "v1", "whoami"]);
32012
+ }
32013
+ async createProject(input) {
32014
+ return this.#json("POST", ["api", "v1", "projects"], input);
32015
+ }
32016
+ async listProjects() {
32017
+ return this.#json("GET", ["api", "v1", "projects"]);
32018
+ }
32019
+ async listArchitectureSources(project) {
32020
+ try {
32021
+ return await this.#json("GET", ["api", "v1", "projects", project, "architecture-sources"]);
32022
+ } catch (error) {
32023
+ if (!isNoRoute(error))
32024
+ throw error;
32566
32025
  }
32567
- fail();
32568
- };
32569
- const value = () => {
32570
- space();
32571
- const char = text.charAt(at);
32572
- if (char === "{" || char === "[") {
32573
- const close = char === "{" ? "}" : "]";
32574
- at += 1;
32575
- space();
32576
- if (text.charAt(at) === close) {
32577
- at += 1;
32578
- return;
32579
- }
32580
- for (;; ) {
32581
- if (close === "}") {
32582
- space();
32583
- string();
32584
- space();
32585
- expect(":");
32586
- }
32587
- value();
32588
- space();
32589
- if (text.charAt(at) === ",") {
32590
- at += 1;
32591
- continue;
32592
- }
32593
- expect(close);
32594
- return;
32026
+ try {
32027
+ const source = await this.#json("GET", [
32028
+ "api",
32029
+ "v1",
32030
+ "projects",
32031
+ project,
32032
+ "architecture-source"
32033
+ ]);
32034
+ return source === null ? [] : [source];
32035
+ } catch (error) {
32036
+ if (error instanceof DispatchServiceError && error.status === 404 && error.code === "SOURCE_NOT_FOUND") {
32037
+ return [];
32595
32038
  }
32039
+ throw error;
32596
32040
  }
32597
- if (char === '"') {
32598
- string();
32599
- return;
32041
+ }
32042
+ async syncArchitectureSources(project) {
32043
+ try {
32044
+ return await this.#json("POST", [
32045
+ "api",
32046
+ "v1",
32047
+ "projects",
32048
+ project,
32049
+ "architecture-sources",
32050
+ "sync"
32051
+ ]);
32052
+ } catch (error) {
32053
+ if (!isNoRoute(error))
32054
+ throw error;
32600
32055
  }
32601
- for (const word of ["true", "false", "null"]) {
32602
- if (text.startsWith(word, at)) {
32603
- at += word.length;
32604
- return;
32605
- }
32056
+ const source = await this.#json("POST", [
32057
+ "api",
32058
+ "v1",
32059
+ "projects",
32060
+ project,
32061
+ "architecture-source",
32062
+ "sync"
32063
+ ]);
32064
+ return [source];
32065
+ }
32066
+ async syncArchitectureSource(project, repo) {
32067
+ const [owner, name, ...rest] = repo.split("/");
32068
+ if (!owner || !name || rest.length > 0) {
32069
+ throw new Error(`repository must be owner/name, got ${JSON.stringify(repo)}`);
32606
32070
  }
32607
- const number = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/.exec(text.slice(at));
32608
- if (number === null)
32609
- fail();
32610
- at += number?.[0].length ?? 0;
32611
- };
32612
- try {
32613
- value();
32614
- space();
32615
- if (at < text.length)
32616
- fail();
32617
- return;
32618
- } catch {
32619
- const before = text.slice(0, at).split(`
32620
- `);
32621
- return `line ${before.length}, column ${(before.at(-1)?.length ?? 0) + 1}`;
32071
+ return this.#json("POST", [
32072
+ "api",
32073
+ "v1",
32074
+ "projects",
32075
+ project,
32076
+ "architecture-sources",
32077
+ owner,
32078
+ name,
32079
+ "sync"
32080
+ ]);
32622
32081
  }
32623
- }
32624
-
32625
- // ../envoy-client/src/secret-file.ts
32626
- import { readFileSync as readFileSync2 } from "fs";
32627
- function sendable(value) {
32628
- return !/[\s\p{Cc}]/u.test(value);
32629
- }
32630
- function readSecretFile(variable, filePath) {
32631
- let contents;
32632
- try {
32633
- contents = readFileSync2(filePath, "utf8");
32634
- } catch (error) {
32635
- throw new Error(`${variable} names ${filePath}, which could not be read: ${messageFor(error)}`);
32082
+ async resolveAsk(id, input) {
32083
+ return this.#json("POST", ["api", "v1", "asks", id, "resolve"], input);
32636
32084
  }
32637
- const value = contents.trim();
32638
- if (value.length === 0)
32639
- throw new Error(`${variable} names ${filePath}, which is empty`);
32640
- if (!sendable(value)) {
32641
- throw new Error(`${variable} names ${filePath}, which holds whitespace or a control character`);
32085
+ async requestApproval(artifactID, input) {
32086
+ const answer = await this.#jsonAnswer("POST", ["api", "v1", "artifacts", artifactID, "approval-requests"], input);
32087
+ return { ...answer.payload, recorded: answer.status === 201 };
32642
32088
  }
32643
- return value;
32644
- }
32645
-
32646
- // ../envoy-client/src/envoy-config.ts
32647
- var COMMAND_TIMEOUT_MS = 1e4;
32648
- function nonEmpty(value) {
32649
- return value === undefined || value === "" ? undefined : value;
32650
- }
32651
- function absolute(name, value) {
32652
- if (value !== undefined && !path.isAbsolute(value)) {
32653
- throw new Error(`${name} is ${value}, which is not an absolute path`);
32089
+ async editAsk(id, input) {
32090
+ return this.#json("PATCH", ["api", "v1", "asks", id], input);
32654
32091
  }
32655
- return value;
32656
- }
32657
- function neutralConfig(env) {
32658
- const xdgConfigHome = nonEmpty(env.XDG_CONFIG_HOME);
32659
- if (xdgConfigHome !== undefined && !path.isAbsolute(xdgConfigHome)) {
32660
- return { error: `XDG_CONFIG_HOME is ${xdgConfigHome}, which is not an absolute path` };
32092
+ async comment(issue, input) {
32093
+ return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"], input);
32661
32094
  }
32662
- const configHome = xdgConfigHome ?? path.join(nonEmpty(env.HOME) ?? homedir(), ".config");
32663
- return { path: path.resolve(configHome, "legion", "envoy.json") };
32664
- }
32665
- var HARNESS_DIRECTORY_VARIABLE = {
32666
- omp: "PI_CODING_AGENT_DIR",
32667
- claude: "CLAUDE_CONFIG_DIR",
32668
- opencode: "OPENCODE_CONFIG_DIR"
32669
- };
32670
- var PLUGIN_HARNESSES = Object.keys(HARNESS_DIRECTORY_VARIABLE);
32671
- function namedDirectory(harness, env) {
32672
- if (harness === "omp") {
32673
- const profile = nonEmpty(env.OMP_PROFILE);
32674
- if (profile === undefined || profile === "default")
32675
- return;
32095
+ async listIssueAsks(issue, state) {
32096
+ return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "asks"], undefined, state === undefined ? undefined : { state });
32676
32097
  }
32677
- return nonEmpty(env[HARNESS_DIRECTORY_VARIABLE[harness]]);
32678
- }
32679
- function harnessDirectory(harness, env) {
32680
- for (const plugin of harness === "command" ? PLUGIN_HARNESSES : [harness]) {
32681
- if (harness === "command" && plugin === "claude" && env.CLAUDE_CODE_CHILD_SESSION !== "1") {
32682
- continue;
32683
- }
32684
- const directory = namedDirectory(plugin, env);
32685
- if (directory !== undefined)
32686
- return absolute(HARNESS_DIRECTORY_VARIABLE[plugin], directory);
32098
+ async getArtifactAsks(id, state) {
32099
+ return this.#json("GET", ["api", "v1", "artifacts", id, "asks"], undefined, state === undefined ? undefined : { state });
32687
32100
  }
32688
- return;
32689
- }
32690
- function handedConfigPath(env) {
32691
- const handed = nonEmpty(env.ENVOY_CONFIG_FILE);
32692
- return handed === undefined ? undefined : path.resolve(absolute("ENVOY_CONFIG_FILE", handed));
32693
- }
32694
- function envoyConfigPath(harness, env) {
32695
- const handedFirst = harness === "command" ? handedConfigPath(env) : undefined;
32696
- if (handedFirst !== undefined)
32697
- return handedFirst;
32698
- const directory = harnessDirectory(harness, env);
32699
- if (directory !== undefined)
32700
- return path.resolve(directory, "envoy.json");
32701
- const handed = handedConfigPath(env);
32702
- if (handed !== undefined)
32703
- return handed;
32704
- const neutral = neutralConfig(env);
32705
- if ("error" in neutral)
32706
- throw new Error(neutral.error);
32707
- return neutral.path;
32708
- }
32709
- var httpUrlSchema = url({ protocol: /^https?$/, error: "must be an http or https URL" });
32710
- var DispatchSectionSchema = strictObject({
32711
- enabled: boolean2().optional(),
32712
- serverUrl: httpUrlSchema.optional(),
32713
- token: string2().optional()
32714
- });
32715
- var EnvoySectionSchema = strictObject({
32716
- enabled: boolean2().optional(),
32717
- url: httpUrlSchema.optional(),
32718
- natsUrls: array(string2().trim().min(1, "must not be empty")).optional(),
32719
- token: string2().optional(),
32720
- natsSeed: string2().optional()
32721
- });
32722
- var EnvoyFileSchema = looseObject({
32723
- $schema: string2().optional(),
32724
- dispatch: DispatchSectionSchema.optional(),
32725
- envoy: EnvoySectionSchema.optional()
32726
- });
32727
- var CheckoutFileSchema = looseObject({
32728
- $schema: string2().optional(),
32729
- dispatch: DispatchSectionSchema.optional()
32730
- });
32731
- var AskgateSectionSchema = strictObject({ enabled: boolean2().optional() });
32732
- function offWithNotice(notice) {
32733
- return { enabled: false, notice, error: null };
32734
- }
32735
- function offWithError(error) {
32736
- return { enabled: false, notice: null, error };
32737
- }
32738
- function httpUrl2(value) {
32739
- let url2;
32740
- try {
32741
- url2 = new URL(value);
32742
- } catch {
32743
- return;
32101
+ async artifactAsk(id, input) {
32102
+ return this.#json("POST", ["api", "v1", "artifacts", id, "asks"], input);
32744
32103
  }
32745
- return url2.protocol === "http:" || url2.protocol === "https:" ? url2 : undefined;
32746
- }
32747
- function describeSchemaIssue(filePath, error) {
32748
- const issue = error.issues[0];
32749
- if (!issue)
32750
- return `${filePath}: invalid envoy.json`;
32751
- if (issue.code === "unrecognized_keys") {
32752
- const section = issue.path.join(".");
32753
- const keys = issue.keys.map((key) => `${section}.${key}`).join(", ");
32754
- return `${filePath}: unrecognized ${section} key(s): ${keys}`;
32104
+ async suggest(issue, input) {
32105
+ const { replace_with, ...comment } = input;
32106
+ return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"], {
32107
+ ...comment,
32108
+ suggestion: { replace_with }
32109
+ });
32755
32110
  }
32756
- return `${filePath}: ${issue.path.join(".")}: ${issue.message}`;
32757
- }
32758
- function danglingLink(filePath) {
32759
- try {
32760
- return lstatSync(filePath).isSymbolicLink() ? readlinkSync(filePath) : null;
32761
- } catch {
32762
- return null;
32111
+ async getArtifactComments(id) {
32112
+ return this.#json("GET", ["api", "v1", "artifacts", id, "comments"]);
32763
32113
  }
32764
- }
32765
- function parseFile(filePath, schema, checkout) {
32766
- let raw;
32767
- try {
32768
- raw = readFileSync3(filePath, "utf-8");
32769
- } catch (error) {
32770
- if (hasErrnoCode(error, "ENOENT") || hasErrnoCode(error, "ENOTDIR")) {
32771
- return { kind: "absent", link: danglingLink(filePath) };
32772
- }
32773
- return { kind: "invalid", reason: `${filePath}: could not be read (${messageFor(error)})` };
32114
+ async artifactComment(id, input) {
32115
+ return this.#json("POST", ["api", "v1", "artifacts", id, "comments"], input);
32774
32116
  }
32775
- let parsedJson;
32776
- try {
32777
- parsedJson = JSON.parse(raw);
32778
- } catch {
32779
- const position = jsonErrorPosition(raw);
32780
- return {
32781
- kind: "invalid",
32782
- reason: `${filePath}: invalid JSON${position === undefined ? "" : ` at ${position}`}`
32783
- };
32117
+ async artifactSuggest(id, input) {
32118
+ const { replace_with, ...comment } = input;
32119
+ return this.#json("POST", ["api", "v1", "artifacts", id, "comments"], {
32120
+ ...comment,
32121
+ suggestion: { replace_with }
32122
+ });
32784
32123
  }
32785
- if (typeof parsedJson === "object" && parsedJson !== null && "natsUrls" in parsedJson) {
32786
- return {
32787
- kind: "invalid",
32788
- reason: checkout ? `${filePath}: the top-level natsUrls is not read, and a checkout's envoy.json holds only a dispatch section` : `${filePath}: the top-level natsUrls is not read; move it to envoy.natsUrls`
32789
- };
32124
+ async message(issue, input) {
32125
+ return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "messages"], input);
32790
32126
  }
32791
- const parsed = schema.safeParse(parsedJson);
32792
- if (!parsed.success) {
32793
- return { kind: "invalid", reason: describeSchemaIssue(filePath, parsed.error) };
32127
+ async messageReply(id, input, options = {}) {
32128
+ return this.#json("POST", ["api", "v1", "messages", id, "reply"], input, options.followUp === true ? { follow_up: "true" } : undefined);
32794
32129
  }
32795
- return { kind: "valid", settings: parsed.data };
32796
- }
32797
- var FAILURE_KEPT_MS = 60000;
32798
- var COMMAND_OUTCOMES = Symbol.for("legion.envoy-config.commands.v1");
32799
- var processGlobal = globalThis;
32800
- var commandOutcomes = processGlobal[COMMAND_OUTCOMES] ?? new Map;
32801
- processGlobal[COMMAND_OUTCOMES] = commandOutcomes;
32802
- function runCommand(command, env, cwd) {
32803
- const childEnv = {};
32804
- for (const [name, variable] of Object.entries(env)) {
32805
- if (variable !== undefined)
32806
- childEnv[name] = variable;
32130
+ async deliveryReply(resource, id, input) {
32131
+ const collection = resource === "message" ? "messages" : "comments";
32132
+ await this.#json("POST", ["api", "v1", collection, id, "reply"], input);
32807
32133
  }
32808
- const directory = mkdtempSync(path.join(tmpdir(), "envoy-command-"));
32809
- try {
32810
- chmodSync(directory, 448);
32811
- const output = path.join(directory, "stdout");
32812
- const fd = openSync2(output, "wx", 384);
32813
- let result;
32814
- try {
32815
- result = Bun.spawnSync(["/bin/sh", "-c", command], {
32816
- cwd,
32817
- env: childEnv,
32818
- stdin: "ignore",
32819
- stdout: fd,
32820
- stderr: "ignore",
32821
- timeout: COMMAND_TIMEOUT_MS,
32822
- detached: true
32823
- });
32824
- } catch (error) {
32825
- return { failure: `could not start: ${messageFor(error)}`, timedOut: false };
32826
- } finally {
32827
- closeSync2(fd);
32828
- }
32829
- try {
32830
- process.kill(-result.pid, "SIGKILL");
32831
- } catch {}
32832
- if (result.exitedDueToTimeout) {
32833
- return {
32834
- failure: `did not finish within ${COMMAND_TIMEOUT_MS / 1000} s, and does not run again in this process`,
32835
- timedOut: true
32836
- };
32837
- }
32838
- if (!result.success) {
32839
- return {
32840
- failure: `exited with ${result.signalCode ?? `status ${result.exitCode}`}`,
32841
- timedOut: false
32842
- };
32843
- }
32844
- const value = readFileSync3(output, "utf-8").trim();
32845
- if (value.length === 0)
32846
- return { failure: "printed nothing", timedOut: false };
32847
- if (!sendable(value)) {
32848
- return {
32849
- failure: "printed more than one line, or whitespace inside its value",
32850
- timedOut: false
32851
- };
32852
- }
32853
- return { value };
32854
- } finally {
32855
- rmSync2(directory, { recursive: true, force: true });
32134
+ async getMessage(issue, id) {
32135
+ return this.#json("GET", [
32136
+ "api",
32137
+ "v1",
32138
+ "issues",
32139
+ await this.#resolveIssue(issue),
32140
+ "messages",
32141
+ id
32142
+ ]);
32856
32143
  }
32857
- }
32858
- function fileValue(value, field, filePath, env) {
32859
- if (!value.startsWith("!")) {
32860
- if (!sendable(value)) {
32861
- throw new Error(`${filePath}: ${field} holds whitespace or a control character`);
32862
- }
32863
- return value;
32144
+ async getMessageThread(id, session) {
32145
+ return this.#json("GET", ["api", "v1", "messages", id], undefined, { session });
32864
32146
  }
32865
- const command = value.slice(1);
32866
- const cwd = path.dirname(path.resolve(filePath));
32867
- const key = JSON.stringify([command, filePath, cwd]);
32868
- let outcome = commandOutcomes.get(key);
32869
- if (outcome === undefined || "failure" in outcome && !outcome.timedOut && Date.now() - outcome.at >= FAILURE_KEPT_MS) {
32870
- outcome = { ...runCommand(command, env, cwd), at: Date.now() };
32871
- commandOutcomes.set(key, outcome);
32147
+ async acceptMessageDelivery(id, attempt, input) {
32148
+ return this.#json("POST", ["api", "v1", "messages", id, "deliveries", String(attempt), "accept"], input);
32872
32149
  }
32873
- if ("failure" in outcome)
32874
- throw new Error(`${filePath}: ${field}'s command ${outcome.failure}`);
32875
- return outcome.value;
32876
- }
32877
- function statDevice(directory) {
32878
- try {
32879
- return statSync2(directory).dev;
32880
- } catch {
32881
- return;
32150
+ async artifact(issue, input) {
32151
+ return this.#upload(["api", "v1", "issues", await this.#resolveIssue(issue), "artifacts"], input);
32882
32152
  }
32883
- }
32884
- function moveNotice(oldFile, newFile, move, deviceOf) {
32885
- const oldDevice = deviceOf(path.dirname(oldFile));
32886
- let ancestor = path.dirname(newFile);
32887
- let newDevice = deviceOf(ancestor);
32888
- while (newDevice === undefined && path.dirname(ancestor) !== ancestor) {
32889
- ancestor = path.dirname(ancestor);
32890
- newDevice = deviceOf(ancestor);
32153
+ async getArtifact(id) {
32154
+ return this.#json("GET", ["api", "v1", "artifacts", id]);
32891
32155
  }
32892
- if (oldDevice !== undefined && newDevice !== undefined && oldDevice !== newDevice) {
32893
- return `${oldFile} is not read, and is on another filesystem than ${newFile} (a mount): create ${newFile}, and move ${oldFile} on the machine that owns it`;
32156
+ async docRead(id, version) {
32157
+ return version === undefined ? this.#json("GET", ["api", "v1", "artifacts", id, "text"]) : this.#json("GET", ["api", "v1", "artifacts", id, "versions", String(version)]);
32894
32158
  }
32895
- return `${oldFile} is not read: ${move}`;
32896
- }
32897
- function oldUserFileNotice(filePath, env, deviceOf) {
32898
- const home = nonEmpty(env.HOME) ?? homedir();
32899
- const old = path.join(home, ".config", "opencode", "envoy.json");
32900
- if (!existsSync(old))
32901
- return;
32902
- const selected = path.resolve(filePath);
32903
- const userFile = path.resolve(home, ".config", "legion", "envoy.json");
32904
- if (selected === userFile) {
32905
- return moveNotice(old, userFile, "mkdir -p ~/.config/legion && mv ~/.config/opencode/envoy.json ~/.config/legion/", deviceOf);
32159
+ async fileVersion(id, version) {
32160
+ const url = this.#url(["api", "v1", "artifacts", id, "versions", String(version)]);
32161
+ const response = await this.#send("GET", url, undefined, "*/*");
32162
+ if (!response.ok)
32163
+ return this.#response("GET", url, response);
32164
+ return {
32165
+ mime: response.headers.get("Content-Type") ?? "application/octet-stream",
32166
+ bytes: new Uint8Array(await response.arrayBuffer())
32167
+ };
32906
32168
  }
32907
- const profileFile = PLUGIN_HARNESSES.map((harness) => namedDirectory(harness, env)).some((directory) => directory !== undefined && path.isAbsolute(directory) && selected === path.resolve(directory, "envoy.json"));
32908
- if (profileFile) {
32909
- return `${old} is not read for this profile; copy or link it to ${filePath}, or write that file`;
32169
+ async artifactBlocks(id) {
32170
+ return this.#json("GET", ["api", "v1", "artifacts", id, "blocks"]);
32910
32171
  }
32911
- const configHome = nonEmpty(env.XDG_CONFIG_HOME);
32912
- const neutral = neutralConfig(env);
32913
- if (configHome !== undefined && path.isAbsolute(configHome) && "path" in neutral && selected === neutral.path) {
32914
- return `${old} is not read under XDG_CONFIG_HOME=${configHome}`;
32172
+ async docEdit(id, input) {
32173
+ return this.#json("POST", ["api", "v1", "artifacts", id, "edits"], input);
32915
32174
  }
32916
- return;
32917
- }
32918
- function missingConfigNotice(filePath, missing, off) {
32919
- const link = missing.link === null ? "" : ` (a link to ${missing.link}, which does not exist)`;
32920
- const old = missing.oldUserFileNotice === undefined ? "" : `; ${missing.oldUserFileNotice}`;
32921
- return `no envoy.json at ${filePath}${link}: ${off}${old}`;
32922
- }
32923
- function readEnvoyConfig(filePath, env, options) {
32924
- const deviceOf = options.deviceOf ?? statDevice;
32925
- const chosen = parseFile(filePath, EnvoyFileSchema, false);
32926
- if (chosen.kind === "invalid")
32927
- return { kind: "failed", path: filePath, error: chosen.reason };
32928
- const resolvedChosen = path.resolve(filePath);
32929
- const checkoutPath = path.resolve(options.cwd, ".envoy", "envoy.json");
32930
- const checkoutFile = checkoutPath === resolvedChosen ? { kind: "absent", link: null } : parseFile(checkoutPath, CheckoutFileSchema, true);
32931
- const own = chosen.kind === "valid" ? chosen.settings : {};
32932
- let checkout = null;
32933
- if (checkoutFile.kind === "invalid") {
32934
- checkout = { kind: "invalid", path: checkoutPath, error: checkoutFile.reason };
32935
- } else if (checkoutFile.kind === "valid") {
32936
- checkout = {
32937
- kind: "valid",
32938
- path: checkoutPath,
32939
- dispatch: checkoutFile.settings.dispatch ?? {},
32940
- envoyError: Object.hasOwn(checkoutFile.settings, "envoy") ? `${checkoutPath}: envoy is not read from a checkout's envoy.json; put it in ${filePath}` : null,
32941
- askgateError: Object.hasOwn(checkoutFile.settings, "askgate") ? `askgate in ${checkoutPath} is not read; set it in ${filePath}` : null
32942
- };
32175
+ async nameArtifactVersion(id, input) {
32176
+ return this.#json("POST", ["api", "v1", "artifacts", id, "versions"], input);
32943
32177
  }
32944
- const oldCheckout = path.resolve(options.cwd, ".opencode", "envoy.json");
32945
- const warnings = oldCheckout !== resolvedChosen && !existsSync(checkoutPath) && existsSync(oldCheckout) ? [
32946
- moveNotice(oldCheckout, checkoutPath, `mkdir -p ${path.dirname(checkoutPath)} && mv ${oldCheckout} ${checkoutPath}`, deviceOf)
32947
- ] : [];
32948
- const unreadOldUserFile = chosen.kind === "absent" ? oldUserFileNotice(filePath, env, deviceOf) : undefined;
32949
- return {
32950
- kind: "read",
32951
- path: filePath,
32952
- dispatch: own.dispatch ?? {},
32953
- envoy: own.envoy ?? {},
32954
- checkout,
32955
- missing: chosen.kind === "absent" ? {
32956
- link: chosen.link,
32957
- ...unreadOldUserFile === undefined ? {} : { oldUserFileNotice: unreadOldUserFile }
32958
- } : null,
32959
- warnings
32960
- };
32961
- }
32962
- function askgateSetting(filePath) {
32963
- const stayOn = (reason) => ({
32964
- enabled: true,
32965
- error: `${reason}; AskGate stays on`
32966
- });
32967
- let raw;
32968
- try {
32969
- raw = readFileSync3(filePath, "utf-8");
32970
- } catch (error) {
32971
- if (hasErrnoCode(error, "ENOENT") || hasErrnoCode(error, "ENOTDIR")) {
32972
- return { enabled: true, error: null };
32973
- }
32974
- return stayOn(`${filePath}: could not be read (${messageFor(error)}); askgate.enabled is not read`);
32178
+ async getArtifactEvents(id, after = 0, limit = 200) {
32179
+ return this.#json("GET", ["api", "v1", "artifacts", id, "events"], undefined, { after, limit });
32975
32180
  }
32976
- let parsedJson;
32977
- try {
32978
- parsedJson = JSON.parse(raw);
32979
- } catch {
32980
- const position = jsonErrorPosition(raw);
32981
- const at = position === undefined ? "" : ` at ${position}`;
32982
- return stayOn(`${filePath}: invalid JSON${at}; askgate.enabled is not read`);
32181
+ async getArtifactReferences(id) {
32182
+ return this.#json("GET", ["api", "v1", "artifacts", id, "references"]);
32983
32183
  }
32984
- if (typeof parsedJson !== "object" || parsedJson === null || !("askgate" in parsedJson)) {
32985
- return { enabled: true, error: null };
32184
+ async getAsk(id) {
32185
+ return this.#json("GET", ["api", "v1", "asks", id]);
32986
32186
  }
32987
- const parsed = object({ askgate: AskgateSectionSchema }).safeParse(parsedJson);
32988
- if (!parsed.success) {
32989
- const unknownKey = parsed.error.issues[0]?.code === "unrecognized_keys";
32990
- return stayOn(unknownKey ? `${describeSchemaIssue(filePath, parsed.error)}; the one askgate key is askgate.enabled, true or false` : `${filePath}: askgate.enabled must be true or false`);
32187
+ async followAsk(id, sessionId, actor) {
32188
+ await this.#json("PUT", ["api", "v1", "asks", id, "followers", sessionId], { actor });
32991
32189
  }
32992
- return { enabled: parsed.data.askgate.enabled ?? true, error: null };
32993
- }
32994
-
32995
- // ../envoy-client/src/bearer.ts
32996
- function bearerSource(env, section, written) {
32997
- const pointer = nonEmpty(env[`${section}_TOKEN_FILE`]);
32998
- if (pointer !== undefined) {
32999
- return { kind: "variable", token: readSecretFile(`${section}_TOKEN_FILE`, pointer) };
32190
+ async unfollowAsk(id, sessionId, actor) {
32191
+ await this.#json("DELETE", ["api", "v1", "asks", id, "followers", sessionId], { actor });
33000
32192
  }
33001
- const plain = nonEmpty(env[`${section}_TOKEN`]);
33002
- if (plain !== undefined) {
33003
- if (!sendable(plain)) {
33004
- throw new Error(`${section}_TOKEN holds whitespace or a control character`);
33005
- }
33006
- return { kind: "variable", token: plain };
32193
+ async getComment(id) {
32194
+ return this.#json("GET", ["api", "v1", "comments", id]);
33007
32195
  }
33008
- const bearer = written();
33009
- return bearer === undefined ? { kind: "none" } : { kind: "file", ...bearer };
33010
- }
33011
- function fileBearer(bearer, url, section, env) {
33012
- const named = httpUrl2(url)?.origin;
33013
- const paired = httpUrl2(bearer.server)?.origin;
33014
- if (named !== paired) {
33015
- throw new Error(`${section}_URL names ${named}, but ${bearer.path}'s ${bearer.field} is for ${paired}; set ${section}_TOKEN or ${section}_TOKEN_FILE for it`);
32196
+ async resolveComment(id, actor) {
32197
+ return this.#json("POST", ["api", "v1", "comments", id, "resolve"], { actor });
33016
32198
  }
33017
- if (bearer.checkout && bearer.token.startsWith("!")) {
33018
- throw new Error(`${bearer.path}: ${bearer.field} is a command, which a checkout's envoy.json cannot run`);
32199
+ async getComments(issue) {
32200
+ return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"]);
33019
32201
  }
33020
- if (bearer.token === "") {
33021
- throw new Error(`${bearer.field} in ${bearer.path} must be a non-empty bearer token`);
32202
+ async getIssueReferences(issue) {
32203
+ return this.#json("GET", [
32204
+ "api",
32205
+ "v1",
32206
+ "issues",
32207
+ await this.#resolveIssue(issue),
32208
+ "references"
32209
+ ]);
33022
32210
  }
33023
- return fileValue(bearer.token, bearer.field, bearer.path, env);
33024
- }
33025
-
33026
- // ../envoy-client/src/dispatch-config.ts
33027
- var DEFAULT_SERVER_URL = "http://localhost:8766";
33028
- function checkoutPair(checkout, serverUrl) {
33029
- const { token } = checkout.dispatch;
33030
- if (token === undefined) {
33031
- throw new Error(`${checkout.path}: dispatch.serverUrl requires dispatch.token in the same file`);
32211
+ async getReferences(query) {
32212
+ return this.#json("GET", ["api", "v1", "references"], undefined, {
32213
+ ..."to" in query ? { to: query.to } : { from: query.from },
32214
+ ...query.kind === undefined || query.kind.length === 0 ? {} : { kind: query.kind.join(",") },
32215
+ ...query.since === undefined ? {} : { since: query.since }
32216
+ });
33032
32217
  }
33033
- return {
33034
- kind: "file",
33035
- token,
33036
- field: "dispatch.token",
33037
- path: checkout.path,
33038
- server: serverUrl,
33039
- checkout: true
33040
- };
33041
- }
33042
- function writtenToken(config, checkout) {
33043
- if (checkout?.dispatch.token !== undefined) {
33044
- throw new Error(`${checkout.path}: dispatch.token requires dispatch.serverUrl in the same file`);
32218
+ async#resolveIssue(issueReference) {
32219
+ if (!issueReference.includes("#"))
32220
+ return issueReference;
32221
+ let resolved = this.#resolvedIssues.get(issueReference);
32222
+ if (!resolved) {
32223
+ resolved = this.#json("GET", ["api", "v1", "issues", "resolve"], undefined, {
32224
+ ref: issueReference
32225
+ }).then((resolution) => resolution.key);
32226
+ this.#resolvedIssues.set(issueReference, resolved);
32227
+ }
32228
+ try {
32229
+ return await resolved;
32230
+ } catch (error) {
32231
+ this.#resolvedIssues.delete(issueReference);
32232
+ throw error;
32233
+ }
33045
32234
  }
33046
- const own = config.dispatch;
33047
- if (own.token === undefined)
33048
- return;
33049
- const server = own.serverUrl ?? DEFAULT_SERVER_URL;
33050
- return {
33051
- token: own.token,
33052
- field: "dispatch.token",
33053
- path: config.path,
33054
- server,
33055
- checkout: false
33056
- };
33057
- }
33058
- function dispatchSettings(env, config) {
33059
- if (config.kind === "failed")
33060
- return offWithError(config.error);
33061
- const explicitUrl = nonEmpty(env.DISPATCH_URL);
33062
- const checkoutFile = explicitUrl === undefined ? config.checkout : null;
33063
- if (checkoutFile?.kind === "invalid")
33064
- return offWithError(checkoutFile.error);
33065
- const checkout = checkoutFile?.kind === "valid" ? checkoutFile : null;
33066
- const own = config.dispatch;
33067
- if (own.enabled === false) {
33068
- return offWithNotice(`${config.path} sets dispatch.enabled to false: Dispatch is off`);
32235
+ async#json(method, path, body, query) {
32236
+ return (await this.#jsonAnswer(method, path, body, query)).payload;
33069
32237
  }
33070
- if (checkout?.dispatch.enabled === false) {
33071
- return offWithNotice(`${checkout.path} sets dispatch.enabled to false: Dispatch is off`);
32238
+ async#jsonAnswer(method, path, body, query) {
32239
+ const url = this.#url(path, query);
32240
+ const response = await this.#send(method, url, body === undefined ? undefined : { content: JSON.stringify(body), type: "application/json" });
32241
+ return { status: response.status, payload: await this.#response(method, url, response) };
33072
32242
  }
33073
- const checkoutServer = checkout?.dispatch.serverUrl;
33074
- const addressed = explicitUrl !== undefined || checkoutServer !== undefined || own.serverUrl !== undefined || own.enabled === true;
33075
- if (!addressed) {
33076
- return offWithNotice(config.missing === null ? `${config.path} names no Dispatch server, and DISPATCH_URL is not set: Dispatch is off` : missingConfigNotice(config.path, config.missing, "Dispatch is off"));
32243
+ async#upload(path, input) {
32244
+ if ("content" in input)
32245
+ return this.#json("POST", path, input);
32246
+ const form = new FormData;
32247
+ form.set("name", input.name);
32248
+ if (input.summary !== undefined)
32249
+ form.set("summary", input.summary);
32250
+ if (input.actor !== undefined)
32251
+ form.set("actor", JSON.stringify(input.actor));
32252
+ form.set("file", input.file, input.name);
32253
+ return this.#form("POST", path, form);
33077
32254
  }
33078
- if (explicitUrl !== undefined && httpUrl2(explicitUrl) === undefined) {
33079
- return offWithError("DISPATCH_URL must be an http or https URL");
32255
+ async#form(method, path, form) {
32256
+ const url = this.#url(path);
32257
+ const encoded = new Response(form);
32258
+ const type = encoded.headers.get("Content-Type") ?? "multipart/form-data";
32259
+ const content = new Uint8Array(await encoded.arrayBuffer());
32260
+ const response = await this.#send(method, url, { content, type });
32261
+ return this.#response(method, url, response);
33080
32262
  }
33081
- try {
33082
- const source = checkout !== null && checkoutServer !== undefined ? checkoutPair(checkout, checkoutServer) : bearerSource(env, "DISPATCH", () => writtenToken(config, checkout));
33083
- if (source.kind === "none") {
33084
- return offWithError(explicitUrl === undefined ? `${config.path}: dispatch is enabled and no token is: set dispatch.token, or DISPATCH_TOKEN or DISPATCH_TOKEN_FILE` : `DISPATCH_URL is set and no token is: set DISPATCH_TOKEN or DISPATCH_TOKEN_FILE, or dispatch.token in ${config.path}`);
33085
- }
33086
- const url = (explicitUrl ?? (source.kind === "file" ? source.server : own.serverUrl ?? DEFAULT_SERVER_URL)).replace(/\/+$/, "");
33087
- const token = source.kind === "variable" ? source.token : fileBearer(source, url, "DISPATCH", env);
33088
- const publicUrl = nonEmpty(env.DISPATCH_PUBLIC_URL);
33089
- const publicParsed = publicUrl === undefined ? undefined : httpUrl2(publicUrl);
33090
- if (publicUrl !== undefined && (publicParsed === undefined || publicParsed.port === "0")) {
33091
- return offWithError("DISPATCH_PUBLIC_URL must be an http or https URL");
32263
+ async#send(method, url, body, accept = "application/json") {
32264
+ const headers = {
32265
+ Accept: accept,
32266
+ Authorization: `Bearer ${this.token}`
32267
+ };
32268
+ if (body !== undefined)
32269
+ headers["Content-Type"] = body.type;
32270
+ if (method !== "POST" && method !== "PATCH") {
32271
+ return this.fetchImpl(url, {
32272
+ method,
32273
+ headers,
32274
+ signal: this.#signal,
32275
+ ...body === undefined ? {} : { body: body.content }
32276
+ });
33092
32277
  }
33093
- return {
33094
- enabled: true,
33095
- url,
33096
- token,
33097
- ...publicUrl === undefined ? {} : { publicUrl: publicUrl.replace(/\/+$/, "") }
32278
+ const key = crypto.randomUUID();
32279
+ headers[IDEMPOTENCY_KEY_HEADER] = key;
32280
+ const { pausesMs, withinMs, silenceMs, pause = pauseFor } = this.writeRetry;
32281
+ const request = `${method} ${url}`;
32282
+ const started = this.#now();
32283
+ let reached = false;
32284
+ for (let attempt = 1;; attempt++) {
32285
+ let answer;
32286
+ let thrown;
32287
+ try {
32288
+ answer = await writeAnswer(await this.#attempt(url, method, headers, body, silenceMs), key);
32289
+ if (answer.echoed)
32290
+ KEYED_LAYER_SEEN.set(this.#baseUrl, this.#now());
32291
+ if (!answer.again)
32292
+ return answer.response;
32293
+ reached ||= answer.reached;
32294
+ } catch (error) {
32295
+ const name = error instanceof Error || error instanceof DOMException ? error.name : "";
32296
+ if (!(error instanceof WriteAttemptSilent) && (this.#signal.aborted || name === "AbortError" || name === "TimeoutError")) {
32297
+ throw this.#ended(error, request, attempt, true);
32298
+ }
32299
+ thrown = error;
32300
+ reached = true;
32301
+ }
32302
+ const scheduled = pausesMs[attempt - 1];
32303
+ const wait = Math.max(scheduled ?? 0, answer === undefined ? 0 : retryAfterMs(answer.response));
32304
+ const inTime = scheduled !== undefined && this.#now() - started + wait <= withinMs;
32305
+ if (!inTime || !(answer?.echoed || await this.#runsKeyedLayer(answer?.unjudged ?? false))) {
32306
+ if (answer !== undefined) {
32307
+ return this.#unsettled(method, url, answer.response, reached, attempt);
32308
+ }
32309
+ if (thrown instanceof WriteAttemptSilent) {
32310
+ throw new DispatchWriteUnsettledError(thrown, attempt, `${request} ${thrown.message}`);
32311
+ }
32312
+ throw thrown;
32313
+ }
32314
+ await answer?.response.body?.cancel().catch(() => {
32315
+ return;
32316
+ });
32317
+ try {
32318
+ await pause(wait, this.#signal);
32319
+ } catch (error) {
32320
+ throw this.#ended(error, request, attempt, reached);
32321
+ }
32322
+ }
32323
+ }
32324
+ #now() {
32325
+ return this.writeRetry.now?.() ?? performance.now();
32326
+ }
32327
+ async#attempt(url, method, headers, body, silenceMs) {
32328
+ const cut = new AbortController;
32329
+ const silent = () => cut.abort(new WriteAttemptSilent(silenceMs));
32330
+ let timer = setTimeout(silent, silenceMs);
32331
+ let answered = false;
32332
+ const progress = () => {
32333
+ if (answered)
32334
+ return;
32335
+ clearTimeout(timer);
32336
+ timer = setTimeout(silent, silenceMs);
33098
32337
  };
33099
- } catch (error) {
33100
- return offWithError(messageFor(error));
32338
+ try {
32339
+ return await this.fetchImpl(url, {
32340
+ method,
32341
+ signal: AbortSignal.any([this.#signal, cut.signal]),
32342
+ ...body === undefined ? { headers } : attemptBody(body, headers, progress)
32343
+ });
32344
+ } catch (error) {
32345
+ if (cut.signal.aborted && !this.#signal.aborted)
32346
+ throw cut.signal.reason;
32347
+ throw error;
32348
+ } finally {
32349
+ answered = true;
32350
+ clearTimeout(timer);
32351
+ }
33101
32352
  }
33102
- }
33103
- function activeDispatchSettings(resolution) {
33104
- if (resolution.enabled)
33105
- return resolution;
33106
- if (resolution.error !== null)
33107
- throw new Error(`dispatch config: ${resolution.error}`);
33108
- return null;
33109
- }
33110
-
33111
- // ../envoy-client/src/dispatch-first.ts
33112
- import { readFileSync as readFileSync4 } from "fs";
33113
- import { join as join3 } from "path";
33114
- var DISPATCH_FIRST_MARKER = "<dispatch-first-skill>";
33115
- function dispatchFirstSkillFile(skillsDirectory) {
33116
- return join3(skillsDirectory, "dispatch-first", "SKILL.md");
33117
- }
33118
- function readDispatchFirstContext(skillFile) {
33119
- let skill;
33120
- try {
33121
- skill = readFileSync4(skillFile, "utf8");
33122
- } catch (error) {
33123
- throw new Error(`the dispatch-first skill ${skillFile} could not be read: ${messageFor(error)}`);
32353
+ #ended(error, request, attempts, mayHaveReached) {
32354
+ const reason = this.#signal.aborted ? this.#signal.reason : error;
32355
+ const timedOut = (reason instanceof Error || reason instanceof DOMException) && reason.name === "TimeoutError";
32356
+ if (!timedOut || !mayHaveReached || !(error instanceof Error))
32357
+ return error;
32358
+ return new DispatchWriteUnsettledError(error, attempts, `${request} had no definitive answer when its deadline ended it`);
33124
32359
  }
33125
- const body = skill.replace(/^---\n[\s\S]*?\n---\n/, "").trim();
33126
- return [
33127
- DISPATCH_FIRST_MARKER,
33128
- "This session has Dispatch, so the dispatch-first skill is loaded for it. Follow it.",
33129
- "",
33130
- body,
33131
- "</dispatch-first-skill>"
33132
- ].join(`
33133
- `);
33134
- }
33135
-
33136
- // ../envoy-client/src/dispatch-http.ts
33137
- class DispatchServiceError extends Error {
33138
- code;
33139
- status;
33140
- candidates;
33141
- current;
33142
- mismatches;
33143
- name = "DispatchServiceError";
33144
- fromDispatch = true;
33145
- constructor(code, status, message, candidates, current, mismatches) {
33146
- super(message);
33147
- this.code = code;
33148
- this.status = status;
33149
- this.candidates = candidates;
33150
- this.current = current;
33151
- this.mismatches = mismatches;
32360
+ async#runsKeyedLayer(unjudged) {
32361
+ const origin = this.#baseUrl;
32362
+ if (unjudged)
32363
+ KEYED_LAYER_SEEN.delete(origin);
32364
+ const seen = KEYED_LAYER_SEEN.get(origin);
32365
+ if (seen !== undefined && this.#now() - seen < KEYED_LAYER_MEMORY_MS)
32366
+ return true;
32367
+ let probe = KEYED_LAYER_PROBES.get(origin);
32368
+ if (probe === undefined) {
32369
+ probe = this.#probeKeyedLayer().finally(() => KEYED_LAYER_PROBES.delete(origin));
32370
+ KEYED_LAYER_PROBES.set(origin, probe);
32371
+ }
32372
+ const runs = await probe;
32373
+ if (runs)
32374
+ KEYED_LAYER_SEEN.set(origin, this.#now());
32375
+ return runs;
33152
32376
  }
33153
- }
33154
-
33155
- class DispatchGatewayError extends DispatchServiceError {
33156
- answer;
33157
- advice;
33158
- fromDispatch = false;
33159
- transient;
33160
- mayHaveReachedDispatch;
33161
- constructor(status, answer, advice, message = `${answer}, so ${advice}.`) {
33162
- super(`HTTP_${status}`, status, message);
33163
- this.answer = answer;
33164
- this.advice = advice;
33165
- this.transient = transientStatus(status);
33166
- this.mayHaveReachedDispatch = reachesDispatch(status);
32377
+ async#probeKeyedLayer() {
32378
+ try {
32379
+ const response = await this.fetchImpl(`${this.#baseUrl}/healthz`, {
32380
+ method: "GET",
32381
+ headers: { Accept: "application/json", Authorization: `Bearer ${this.token}` },
32382
+ signal: AbortSignal.any([this.#signal, AbortSignal.timeout(KEY_LAYER_PROBE_MS)])
32383
+ });
32384
+ if (!isJson(response))
32385
+ return false;
32386
+ const health = await response.json();
32387
+ return typeof health === "object" && health !== null && Reflect.get(health, "idempotency_keys") === true;
32388
+ } catch {
32389
+ return false;
32390
+ }
33167
32391
  }
33168
- }
33169
- function asErrorShape(value) {
33170
- return typeof value === "object" && value !== null ? value : {};
33171
- }
33172
- function isJson(response) {
33173
- return response.headers.get("content-type")?.includes("application/json") ?? false;
33174
- }
33175
- function isNoRoute(error) {
33176
- return error instanceof DispatchServiceError && error.status === 404 && error.code === "NOT_FOUND" && error.message.startsWith("no route for ");
33177
- }
33178
- var ISSUE_EVENTS_PAGE_MAX = 200;
33179
- var DISPATCH_TOOL_DEADLINE_MS = 60000;
33180
- function requestSignal(signal) {
33181
- const deadline = AbortSignal.timeout(DISPATCH_TOOL_DEADLINE_MS);
33182
- return signal === undefined ? deadline : AbortSignal.any([signal, deadline]);
33183
- }
33184
- function whyNotAPage(answer) {
33185
- if (typeof answer === "string") {
33186
- return `text that is not a JSON page, ${GATEWAY_PAGE}, so a retry may succeed.`;
32392
+ async#unsettled(method, url, response, reached, attempts) {
32393
+ const refusal = await this.#response(method, url, response).catch((error) => error);
32394
+ if (reached && refusal instanceof DispatchServiceError) {
32395
+ const landedAlone = refusal instanceof DispatchGatewayError ? refusal.mayHaveReachedDispatch : refusal.status >= 500;
32396
+ if (!landedAlone)
32397
+ throw new DispatchWriteUnsettledError(refusal, attempts);
32398
+ }
32399
+ throw refusal;
33187
32400
  }
33188
- let what;
33189
- if (Array.isArray(answer)) {
33190
- 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";
33191
- } else if (answer === null || typeof answer !== "object") {
33192
- what = answer === null ? "null" : `a ${typeof answer}`;
33193
- } else {
33194
- const fields = answer;
33195
- const lacking = [
33196
- ...Array.isArray(fields.issues) ? [] : ["an issues array"],
33197
- ...["total", "limit", "offset"].filter((name) => typeof fields[name] !== "number").map((name) => `a numeric ${name}`)
33198
- ];
33199
- if (lacking.length === 0)
33200
- return;
33201
- what = `an object without ${lacking.join(" or ")}`;
32401
+ #url(path, query) {
32402
+ const url = new URL(`${path.map((segment) => encodeURIComponent(segment)).join("/")}`, `${this.#baseUrl}/`);
32403
+ if (query) {
32404
+ for (const [name, value] of Object.entries(query)) {
32405
+ if (typeof value === "string" || typeof value === "number") {
32406
+ url.searchParams.set(name, String(value));
32407
+ } else if (Array.isArray(value)) {
32408
+ for (const item of value)
32409
+ url.searchParams.append(name, String(item));
32410
+ }
32411
+ }
32412
+ }
32413
+ return url.toString();
33202
32414
  }
33203
- return `${what}. Retrying will not help: the same request gets the same answer until that ` + "Dispatch is upgraded or fixed.";
33204
- }
33205
- function whyNotAnArray(answer) {
33206
- if (typeof answer === "string")
33207
- return `text that is not JSON, ${GATEWAY_PAGE}, so a retry may succeed`;
33208
- if (answer === null)
33209
- return "null";
33210
- if (typeof answer !== "object")
33211
- return `a ${typeof answer}`;
33212
- if ("issues" in answer && Array.isArray(answer.issues)) {
33213
- return "a page, so this Dispatch pages a request that carries no limit and no offset";
32415
+ async#response(method, url, response) {
32416
+ const text = await response.text();
32417
+ let payload = text;
32418
+ if (text && isJson(response)) {
32419
+ try {
32420
+ payload = JSON.parse(text);
32421
+ } catch {
32422
+ payload = text;
32423
+ }
32424
+ }
32425
+ if (!response.ok) {
32426
+ const error = asErrorShape(payload);
32427
+ if (typeof error.error === "string") {
32428
+ if (response.status === 409 && error.code === IDEMPOTENCY_KEY_COMMITTED) {
32429
+ throw new DispatchWriteLandedError(IDEMPOTENCY_KEY_COMMITTED, response.status, method, url);
32430
+ }
32431
+ throw new DispatchServiceError(error.code ?? `HTTP_${response.status}`, response.status, error.error, error.candidates, error.current, error.mismatches);
32432
+ }
32433
+ const quoted = excerpt(text, this.token);
32434
+ let body;
32435
+ if (quoted !== "") {
32436
+ body = `a body that is not Dispatch's error JSON (${JSON.stringify(quoted)})`;
32437
+ } else if (text === "") {
32438
+ body = "an empty body";
32439
+ } else {
32440
+ const within = text.length > EXCERPT_SCAN_LIMIT ? ` in its first ${EXCERPT_SCAN_LIMIT / 1024} KiB` : "";
32441
+ const size = Buffer.byteLength(text).toLocaleString("en-US");
32442
+ body = `a body of ${size} bytes and no readable text${within}`;
32443
+ }
32444
+ const reasonPhrase = excerpt(response.statusText, this.token);
32445
+ const reason = reasonPhrase === "" ? "" : ` ${reasonPhrase}`;
32446
+ throw new DispatchGatewayError(response.status, `${method} ${url} answered ${response.status}${reason} with ${body}, ${GATEWAY_PAGE}`, gatewayAdvice(method, response.status));
32447
+ }
32448
+ const replayed = response.headers.get(IDEMPOTENCY_REPLAYED_HEADER)?.trim() === "?1";
32449
+ if (answerNotKept(response.status, replayed, payload)) {
32450
+ throw new DispatchWriteLandedError(IDEMPOTENCY_ANSWER_NOT_KEPT, response.status, method, url);
32451
+ }
32452
+ return payload;
33214
32453
  }
33215
- return "an object that is not the listing";
33216
32454
  }
33217
- var GATEWAY_PAGE = "which looks like a proxy or gateway page rather than Dispatch's own answer";
33218
- function gatewayAdvice(method, status) {
33219
- if (!transientStatus(status)) {
33220
- return "a retry gets the same answer until the Dispatch URL, or whatever answers in its place, is fixed";
33221
- }
33222
- if (method === "GET")
33223
- return "a retry may succeed";
33224
- 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";
32455
+
32456
+ // ../envoy-client/src/dispatch-owner.ts
32457
+ function dispatchIssueRef(key) {
32458
+ return `dispatch://${key}`;
33225
32459
  }
33226
- function transientStatus(status) {
33227
- return status >= 500 || status === 408 || status === 429;
32460
+ function dispatchDocumentRef(owner, slug) {
32461
+ return `dispatch://${owner}/artifact/${slug}`;
33228
32462
  }
33229
- function reachesDispatch(status) {
33230
- return status >= 500;
32463
+ function dispatchChildRef(ownerRef, kind, id) {
32464
+ return `${ownerRef}/${kind}/${id}`;
33231
32465
  }
33232
- var REDACTED = "[redacted]";
33233
- var EXCERPT_SCAN_LIMIT = 64 * 1024;
33234
- var BEARER_PIECE = 8;
33235
- function redactBearer(text, bearer) {
33236
- if (bearer === "")
33237
- return text.slice(0, EXCERPT_SCAN_LIMIT);
33238
- const length = Math.min(BEARER_PIECE, bearer.length);
33239
- const scanned = text.slice(0, EXCERPT_SCAN_LIMIT + length - 1);
33240
- const covered = new Uint8Array(scanned.length);
33241
- const pieces = new Set;
33242
- for (let at = 0;at + length <= bearer.length; at++)
33243
- pieces.add(bearer.slice(at, at + length));
33244
- for (const piece of pieces) {
33245
- let found = scanned.indexOf(piece);
33246
- while (found !== -1) {
33247
- covered.fill(1, found, found + length);
33248
- found = scanned.indexOf(piece, found + 1);
33249
- }
33250
- }
33251
- let redacted = "";
33252
- let kept = 0;
33253
- for (let start = covered.indexOf(1);start !== -1; start = covered.indexOf(1, kept)) {
33254
- redacted += `${scanned.slice(kept, start)}${REDACTED}`;
33255
- const end = covered.indexOf(0, start);
33256
- kept = end === -1 ? scanned.length : end;
32466
+ function parseBlockRef(document, fragment) {
32467
+ const target = parseBlockFragment(fragment);
32468
+ const parsed = parseDispatchRef(document);
32469
+ if (target === undefined || parsed === null || parsed.version !== undefined || parsed.kind !== "spec" && parsed.kind !== "artifact") {
32470
+ return null;
33257
32471
  }
33258
- return `${redacted}${scanned.slice(kept, EXCERPT_SCAN_LIMIT)}`.slice(0, EXCERPT_SCAN_LIMIT);
33259
- }
33260
- function excerpt(text, token) {
33261
- const plain = redactBearer(text, token.trim()).replace(/<(script|style)\b[^<>]*>(?:[\s\S]*?<\/\1\s*>|[\s\S]*$)/gi, " ").replace(/<[^<>]*>/g, " ");
33262
- return textHead(plain.replace(/(\bauthorization["']?\s*[:=]\s*["']?(?:(?:bearer|basic|digest|token)\s+)?)[^\s"'<>,;]+/gi, `$1${REDACTED}`).replace(/(\bbearer\s+)[^\s"'<>,;]+/gi, `$1${REDACTED}`));
32472
+ return {
32473
+ owner: parsed.owner,
32474
+ kind: "block",
32475
+ id: parsed.id,
32476
+ block: target.block,
32477
+ document,
32478
+ ...parsed.owner.kind === "project" ? { artifact: parsed.id } : {},
32479
+ ...target.pin === undefined ? {} : { pin: target.pin }
32480
+ };
33263
32481
  }
33264
-
33265
- class DispatchClient {
33266
- token;
33267
- fetchImpl;
33268
- #baseUrl;
33269
- #resolvedIssues = new Map;
33270
- #signal;
33271
- constructor(baseUrl, token, fetchImpl = fetch, signal) {
33272
- this.token = token;
33273
- this.fetchImpl = fetchImpl;
33274
- this.#baseUrl = baseUrl.replace(/\/+$/, "");
33275
- this.#signal = requestSignal(signal);
33276
- }
33277
- async issue(input) {
33278
- return this.#json("POST", ["api", "v1", "issues"], input);
33279
- }
33280
- async resolveIssue(issueReference) {
33281
- return this.#resolveIssue(issueReference);
33282
- }
33283
- async listIssuePage(options, page) {
33284
- const path = ["api", "v1", "issues"];
33285
- const query = { ...options, limit: page.limit, offset: page.offset };
33286
- const answer = await this.#json("GET", path, undefined, query);
33287
- const refusal = whyNotAPage(answer);
33288
- if (refusal === undefined)
33289
- return answer;
33290
- throw new Error(`GET ${this.#url(path, query)} asked for a page ({issues, total, limit, offset}) and got ` + refusal);
33291
- }
33292
- async listAllIssues(options) {
33293
- const path = ["api", "v1", "issues"];
33294
- const query = { ...options };
33295
- const answer = await this.#json("GET", path, undefined, query);
33296
- if (Array.isArray(answer))
33297
- return answer;
33298
- throw new Error(`GET ${this.#url(path, query)} asked for the unpaged listing and got ${whyNotAnArray(answer)}.`);
33299
- }
33300
- async listProjectArtifacts(project, unlinked = false) {
33301
- return this.#json("GET", ["api", "v1", "projects", project, "artifacts"], undefined, unlinked ? { unlinked: "true" } : undefined);
33302
- }
33303
- async projectArtifact(project, input) {
33304
- return this.#upload(["api", "v1", "projects", project, "artifacts"], input);
33305
- }
33306
- async getProjectArtifact(project, slug) {
33307
- return this.#json("GET", ["api", "v1", "projects", project, "artifacts", slug]);
33308
- }
33309
- async agentArtifact(sessionId, input) {
33310
- return this.#upload(["api", "v1", "agents", sessionId, "artifacts"], input);
33311
- }
33312
- async getAgentArtifact(sessionId, slug) {
33313
- return this.#json("GET", ["api", "v1", "agents", sessionId, "artifacts", slug]);
33314
- }
33315
- async getIssueArtifact(issue, slug) {
33316
- return this.#json("GET", [
33317
- "api",
33318
- "v1",
33319
- "issues",
33320
- await this.#resolveIssue(issue),
33321
- "artifacts",
33322
- slug
33323
- ]);
33324
- }
33325
- async search(query, options = {}) {
33326
- return this.#json("GET", ["api", "v1", "search"], undefined, { q: query, ...options });
33327
- }
33328
- async getIssue(issue) {
33329
- return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue)]);
32482
+ function parseDispatchRef(ref) {
32483
+ const hash = ref.indexOf("#");
32484
+ if (hash !== -1 && ref.startsWith("b-", hash + 1)) {
32485
+ return parseBlockRef(ref.slice(0, hash), ref.slice(hash + 3));
33330
32486
  }
33331
- async updateIssue(issue, input) {
33332
- return this.#json("PATCH", ["api", "v1", "issues", await this.#resolveIssue(issue)], input);
32487
+ const projectDocument = ref.match(/^dispatch:\/\/([A-Z][A-Z0-9]{1,9})\/artifact\/([^/@]+)(?:@v(\d+))?(?:\/(ask|comment)\/([^/]+))?$/);
32488
+ if (projectDocument) {
32489
+ const [, project, artifact, version, targetKind, targetID] = projectDocument;
32490
+ if (project === undefined || artifact === undefined || version !== undefined && Number(version) < 1) {
32491
+ return null;
32492
+ }
32493
+ if (targetKind === undefined) {
32494
+ return {
32495
+ owner: { kind: "project", project },
32496
+ kind: "artifact",
32497
+ id: artifact,
32498
+ ...version === undefined ? {} : { version: Number(version) }
32499
+ };
32500
+ }
32501
+ if (version !== undefined)
32502
+ return null;
32503
+ if (targetID === undefined || targetKind !== "ask" && targetKind !== "comment")
32504
+ return null;
32505
+ return {
32506
+ owner: { kind: "project", project },
32507
+ kind: targetKind,
32508
+ id: targetID,
32509
+ artifact
32510
+ };
33333
32511
  }
33334
- async claimIssue(issue, input = {}) {
33335
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "claim"], input);
32512
+ 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\/([^/]+))?$/);
32513
+ if (!issueReference)
32514
+ return null;
32515
+ const [, issue, spec, log, children, artifact, version, ask, comment, message] = issueReference;
32516
+ if (!issue || version !== undefined && Number(version) < 1)
32517
+ return null;
32518
+ const owner = { kind: "issue", issue };
32519
+ if (spec)
32520
+ return { owner, kind: "spec", id: spec };
32521
+ if (log)
32522
+ return { owner, kind: "log", id: log };
32523
+ if (children)
32524
+ return { owner, kind: "children", id: children };
32525
+ if (artifact) {
32526
+ return {
32527
+ owner,
32528
+ kind: "artifact",
32529
+ id: artifact,
32530
+ ...version === undefined ? {} : { version: Number(version) }
32531
+ };
33336
32532
  }
33337
- async releaseIssueClaim(issue, input = {}) {
33338
- return this.#json("DELETE", ["api", "v1", "issues", await this.#resolveIssue(issue), "claim"], input);
32533
+ if (ask)
32534
+ return { owner, kind: "ask", id: ask };
32535
+ if (comment)
32536
+ return { owner, kind: "comment", id: comment };
32537
+ if (message)
32538
+ return { owner, kind: "message", id: message };
32539
+ return { owner, kind: "issue", id: issue };
32540
+ }
32541
+
32542
+ // ../envoy-client/src/dispatch-pictures.ts
32543
+ var PICTURE_UPLOAD_MAX_BYTES = 25 * 1024 * 1024;
32544
+ var PICTURE_SHOWN_MAX_BYTES = 3750000;
32545
+ var pictureShownMaxText = `${PICTURE_SHOWN_MAX_BYTES.toLocaleString("en-US")} bytes (5 MB of base64)`;
32546
+ function oversizePictureText(name, bytes) {
32547
+ return `${name} is ${bytes.toLocaleString("en-US")} bytes, over the ${pictureShownMaxText} a model is shown`;
32548
+ }
32549
+ var PICTURES_SHOWN_MAX = 8;
32550
+ var PICTURES_SHOWN_MAX_BYTES = 10 * 1024 * 1024;
32551
+ function bytesAt(bytes, offset, expected) {
32552
+ return expected.every((byte, index) => bytes[offset + index] === byte);
32553
+ }
32554
+ function sniffPictureType(bytes) {
32555
+ if (bytesAt(bytes, 0, [137, 80, 78, 71, 13, 10, 26, 10]))
32556
+ return "image/png";
32557
+ if (bytesAt(bytes, 0, [255, 216, 255]))
32558
+ return "image/jpeg";
32559
+ if (bytesAt(bytes, 0, [71, 73, 70, 56]) && (bytes[4] === 55 || bytes[4] === 57) && bytes[5] === 97) {
32560
+ return "image/gif";
33339
32561
  }
33340
- async getIssueEvents(issue, after = 0, limit = ISSUE_EVENTS_PAGE_MAX) {
33341
- return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "events"], undefined, { after, limit });
32562
+ if (bytesAt(bytes, 0, [82, 73, 70, 70]) && bytesAt(bytes, 8, [87, 69, 66, 80])) {
32563
+ return "image/webp";
33342
32564
  }
33343
- async read(issueReference, options = {}) {
33344
- const issueKey = await this.#resolveIssue(issueReference);
33345
- const issue = await this.getIssue(issueKey);
33346
- const requested = options.events;
33347
- const count = requested === undefined ? DEFAULT_ISSUE_READ_EVENTS : requested === "all" ? issue.last_seq : Math.min(requested, issue.last_seq);
33348
- const events = [];
33349
- let after = Math.max(0, issue.last_seq - count);
33350
- while (events.length < count) {
33351
- const limit = Math.min(ISSUE_EVENTS_PAGE_MAX, count - events.length);
33352
- const page = await this.getIssueEvents(issueKey, after, limit);
33353
- events.push(...page);
33354
- const last = page.at(-1);
33355
- if (page.length < limit || last === undefined || events.length >= count)
32565
+ return;
32566
+ }
32567
+ function toolImage(bytes) {
32568
+ const mimeType = sniffPictureType(bytes);
32569
+ if (mimeType === undefined || bytes.length > PICTURE_SHOWN_MAX_BYTES)
32570
+ return;
32571
+ return { data: Buffer.from(bytes).toString("base64"), mimeType };
32572
+ }
32573
+ function imageBlocks(images) {
32574
+ return images.map(({ data, mimeType }) => ({ type: "image", data, mimeType }));
32575
+ }
32576
+ var PICTURE_SYNTAX = /!\[(?:\\.|[^\\\]])*\]\((dispatch:\/\/[^\s()]+@v[1-9][0-9]*)(?:\s+"(?:\\.|[^\\"])*")?\)/g;
32577
+ function pictureAddresses(text) {
32578
+ return [...text.matchAll(PICTURE_SYNTAX)].map((match) => match[1]);
32579
+ }
32580
+
32581
+ // ../envoy-client/src/human-edit.ts
32582
+ function humanEditHead(edit) {
32583
+ const editors = edit.editors ?? [];
32584
+ const by = editors.length === 0 ? "" : `, edited by ${editors.join(", ")}`;
32585
+ return `${edit.name ?? "document"} v${edit.from_version ?? "?"} to v${edit.to_version ?? "?"}${by}`;
32586
+ }
32587
+ var HUMAN_EDIT_DIFF_CUT_NOTE = "(diff cut at 4,096 bytes)";
32588
+ var HUMAN_EDIT_DIFF_MAX = 4096;
32589
+ function humanEditDiffBlock(diff, cut) {
32590
+ if (diff === undefined || diff === "")
32591
+ return cut === true ? HUMAN_EDIT_DIFF_CUT_NOTE : "";
32592
+ const bytes = new TextEncoder;
32593
+ let shown = diff;
32594
+ let note = cut === true;
32595
+ if (bytes.encode(shown).length > HUMAN_EDIT_DIFF_MAX) {
32596
+ let kept = "";
32597
+ let size = 0;
32598
+ for (const line of shown.split(`
32599
+ `).slice(0, -1)) {
32600
+ size += bytes.encode(`${line}
32601
+ `).length;
32602
+ if (size > HUMAN_EDIT_DIFF_MAX)
33356
32603
  break;
33357
- if (last.seq <= after) {
33358
- throw new Error(`GET /api/v1/issues/${issueKey}/events?after=${after} answered no event after seq ${after}`);
33359
- }
33360
- after = last.seq;
32604
+ kept += `${line}
32605
+ `;
33361
32606
  }
33362
- return { issue, events };
33363
- }
33364
- async ask(issue, input) {
33365
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "asks"], input);
33366
- }
33367
- async openAsks(sessionID, since) {
33368
- return this.#json("GET", ["api", "v1", "asks", "open"], undefined, {
33369
- author_session: sessionID,
33370
- ...since === undefined ? {} : { since }
33371
- });
33372
- }
33373
- async openAsksForProject(project) {
33374
- return this.#json("GET", ["api", "v1", "asks", "open"], undefined, { project });
33375
- }
33376
- async listAgents() {
33377
- return this.#json("GET", ["api", "v1", "agents"]);
33378
- }
33379
- async whoami() {
33380
- return this.#json("GET", ["api", "v1", "whoami"]);
33381
- }
33382
- async createProject(input) {
33383
- return this.#json("POST", ["api", "v1", "projects"], input);
33384
- }
33385
- async listProjects() {
33386
- return this.#json("GET", ["api", "v1", "projects"]);
32607
+ shown = kept;
32608
+ note = true;
33387
32609
  }
33388
- async listArchitectureSources(project) {
33389
- try {
33390
- return await this.#json("GET", ["api", "v1", "projects", project, "architecture-sources"]);
33391
- } catch (error) {
33392
- if (!isNoRoute(error))
33393
- throw error;
32610
+ if (shown === "")
32611
+ return HUMAN_EDIT_DIFF_CUT_NOTE;
32612
+ const longestRun = Math.max(0, ...(shown.match(/`+/g) ?? []).map((run) => run.length));
32613
+ const fence = "`".repeat(Math.max(3, longestRun + 1));
32614
+ const body = shown.endsWith(`
32615
+ `) ? shown : `${shown}
32616
+ `;
32617
+ return `${fence}diff
32618
+ ${body}${fence}${note ? `
32619
+ ${HUMAN_EDIT_DIFF_CUT_NOTE}` : ""}`;
32620
+ }
32621
+
32622
+ // ../envoy-client/src/delivery.ts
32623
+ var KNOWN_SOURCES = EnvelopeSchema.shape.source.enum;
32624
+ var FOREIGN_SESSION_ID = /\b01a0[0-9a-f]{4}-[0-9a-f]{4}-7[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}\b/g;
32625
+ var AskAuthorPayloadSchema = object({
32626
+ author: object({ kind: string2(), id: string2() }).passthrough()
32627
+ });
32628
+ var InboundSenderSchema = object({
32629
+ session_id: string2().optional(),
32630
+ machine: string2().optional(),
32631
+ cwd: string2().optional(),
32632
+ title: string2().optional(),
32633
+ roles: array(string2()).optional()
32634
+ });
32635
+ var InboundEnvelopeSchema = object({
32636
+ event_id: string2().optional(),
32637
+ source: string2(),
32638
+ source_event_id: string2().optional(),
32639
+ source_session: string2().optional(),
32640
+ topic: string2().optional(),
32641
+ dedupe_key: string2().optional(),
32642
+ issued_at: number2().int().optional(),
32643
+ expires_at: number2().int().optional(),
32644
+ payload_summary: string2().optional(),
32645
+ payload: string2().optional(),
32646
+ sender: InboundSenderSchema.optional(),
32647
+ in_reply_to: string2().optional(),
32648
+ supersedes: string2().optional(),
32649
+ urgency: string2().optional(),
32650
+ expects_reply: string2().optional()
32651
+ }).passthrough();
32652
+ function tolerantShape(shape) {
32653
+ return Object.fromEntries(Object.entries(shape).map(([key, schema]) => [key, _catch2(schema, undefined)]));
32654
+ }
32655
+ var TolerantInboundEnvelopeSchema = object({
32656
+ ...tolerantShape(InboundEnvelopeSchema.shape),
32657
+ source: InboundEnvelopeSchema.shape.source.optional().catch(undefined),
32658
+ sender: object(tolerantShape(InboundSenderSchema.shape)).optional().catch(undefined)
32659
+ }).passthrough();
32660
+ function dispatchReplyPath(resource, id) {
32661
+ const collection = resource === "message" ? "messages" : "comments";
32662
+ return `/api/v1/${collection}/${encodeURIComponent(id)}/reply`;
32663
+ }
32664
+ async function postDeliveryReply(config, sessionId, delivery, result) {
32665
+ await new DispatchClient(config.url, config.token).deliveryReply(delivery.resource, delivery.id, {
32666
+ actor: { kind: "session", id: sessionId },
32667
+ attempt: delivery.attempt,
32668
+ ...delivery.replyFields,
32669
+ ...result
32670
+ });
32671
+ }
32672
+ function expectsLaneReceipt(frame) {
32673
+ return frame.reply !== undefined && frame.reply !== "" && frame.subject === frame.directSubject && frame.envelopeTopic !== undefined && frame.envelopeTopic !== frame.directSubject;
32674
+ }
32675
+ async function* readArrivals(subscription, now = Date.now) {
32676
+ const source = subscription[Symbol.asyncIterator]();
32677
+ const arrived = [];
32678
+ let stopped;
32679
+ let left = false;
32680
+ let wake;
32681
+ const signal = () => {
32682
+ wake?.();
32683
+ wake = undefined;
32684
+ };
32685
+ (async () => {
32686
+ try {
32687
+ for (;; ) {
32688
+ const read = await source.next();
32689
+ if (read.done === true || left)
32690
+ break;
32691
+ arrived.push({ message: read.value, receivedAt: now() });
32692
+ signal();
32693
+ }
32694
+ stopped = { failed: false };
32695
+ } catch (error) {
32696
+ stopped = { error, failed: true };
32697
+ }
32698
+ signal();
32699
+ })();
32700
+ try {
32701
+ for (;; ) {
32702
+ const next = arrived.shift();
32703
+ if (next !== undefined) {
32704
+ yield next;
32705
+ continue;
32706
+ }
32707
+ if (stopped?.failed === true)
32708
+ throw stopped.error;
32709
+ if (stopped !== undefined)
32710
+ return;
32711
+ const { promise, resolve } = Promise.withResolvers();
32712
+ wake = resolve;
32713
+ await promise;
32714
+ }
32715
+ } finally {
32716
+ if (stopped === undefined) {
32717
+ left = true;
32718
+ Promise.resolve(source.return?.()).catch(() => {
32719
+ return;
32720
+ });
32721
+ }
32722
+ }
32723
+ }
32724
+ var DedupeIdentitySchema = object({
32725
+ event_id: string2().min(1).optional(),
32726
+ dedupe_key: string2().min(1).optional(),
32727
+ source: string2().optional(),
32728
+ source_event_id: string2().optional()
32729
+ });
32730
+ var DELIVERY_DEDUPE_KEY_LIMIT = 250000;
32731
+ var DELIVERY_EVENT_ID_LIMIT = 1e4;
32732
+ function createDeliveryDedupe(now = Date.now) {
32733
+ const keys = new Map;
32734
+ let events = new Map;
32735
+ let olderEvents = new Map;
32736
+ const pendingKeys = new Map;
32737
+ const pendingEvents = new Map;
32738
+ let claims = 0;
32739
+ return {
32740
+ claim(frame) {
32741
+ const eventId = frame?.event_id;
32742
+ if (eventId !== undefined && (events.has(eventId) || olderEvents.has(eventId))) {
32743
+ return;
32744
+ }
32745
+ const key = frame?.dedupe_key;
32746
+ const named = frame !== undefined && key !== undefined && dedupeKeyNamesItsEvent(frame);
32747
+ const at = now();
32748
+ if (named) {
32749
+ const claimedAt = keys.get(key);
32750
+ if (claimedAt !== undefined && at - claimedAt < DELIVERY_DUPLICATE_WINDOW_MS) {
32751
+ return;
32752
+ }
32753
+ for (const [oldest, deliveredAt] of keys) {
32754
+ if (at - deliveredAt < DELIVERY_DUPLICATE_WINDOW_MS)
32755
+ break;
32756
+ keys.delete(oldest);
32757
+ }
32758
+ keys.delete(key);
32759
+ if (keys.size >= DELIVERY_DEDUPE_KEY_LIMIT) {
32760
+ const oldest = keys.keys().next();
32761
+ if (oldest.done !== true)
32762
+ keys.delete(oldest.value);
32763
+ }
32764
+ keys.set(key, at);
32765
+ }
32766
+ const claim = ++claims;
32767
+ if (eventId !== undefined) {
32768
+ if (events.size >= DELIVERY_EVENT_ID_LIMIT / 2) {
32769
+ olderEvents = events;
32770
+ events = new Map;
32771
+ }
32772
+ events.set(eventId, claim);
32773
+ pendingEvents.set(eventId, claim);
32774
+ }
32775
+ if (named)
32776
+ pendingKeys.set(key, claim);
32777
+ let open = true;
32778
+ const close = () => {
32779
+ if (!open)
32780
+ return;
32781
+ open = false;
32782
+ if (eventId !== undefined && pendingEvents.get(eventId) === claim) {
32783
+ pendingEvents.delete(eventId);
32784
+ }
32785
+ if (named && pendingKeys.get(key) === claim)
32786
+ pendingKeys.delete(key);
32787
+ };
32788
+ let released = false;
32789
+ return {
32790
+ release() {
32791
+ close();
32792
+ if (released)
32793
+ return;
32794
+ released = true;
32795
+ if (named && keys.get(key) === at)
32796
+ keys.delete(key);
32797
+ if (eventId === undefined)
32798
+ return;
32799
+ if (events.get(eventId) === claim)
32800
+ events.delete(eventId);
32801
+ if (olderEvents.get(eventId) === claim)
32802
+ olderEvents.delete(eventId);
32803
+ },
32804
+ settle: close
32805
+ };
32806
+ },
32807
+ pending(frame) {
32808
+ const eventId = frame.event_id;
32809
+ const key = frame.dedupe_key;
32810
+ return eventId !== undefined && pendingEvents.has(eventId) || key !== undefined && dedupeKeyNamesItsEvent(frame) && pendingKeys.has(key);
32811
+ }
32812
+ };
32813
+ }
32814
+ function isCommentTargetedDelivery(delivery) {
32815
+ return "comment_id" in delivery;
32816
+ }
32817
+ var DispatchTargetedFrameSchema = object({
32818
+ event: DispatchEventSchema,
32819
+ delivery: DispatchTargetedDeliverySchema
32820
+ }).superRefine(({ event, delivery }, context) => {
32821
+ if (event.type === "message.created" && !isCommentTargetedDelivery(delivery) && DispatchTargetedMessagePayloadSchema.safeParse(event.payload).success) {
32822
+ return;
32823
+ }
32824
+ if (event.type === "comment.created" && isCommentTargetedDelivery(delivery) && DispatchTargetedCommentPayloadSchema.safeParse(event.payload).success) {
32825
+ return;
32826
+ }
32827
+ context.addIssue({
32828
+ code: "custom",
32829
+ message: event.type === "comment.created" ? "targeted delivery requires a complete comment.created event" : "targeted delivery requires a complete message.created event"
32830
+ });
32831
+ });
32832
+ var RecoverableDispatchDeliveryFailureSchema = object({
32833
+ event: object({
32834
+ type: _enum2(["message.created", "comment.created"]),
32835
+ issue_key: string2().nullable(),
32836
+ payload: object({ id: string2(), body: string2().optional() }).passthrough()
32837
+ }).passthrough(),
32838
+ delivery: DispatchTargetedDeliverySchema
32839
+ }).refine(({ event, delivery }) => event.type === "comment.created" ? isCommentTargetedDelivery(delivery) : !isCommentTargetedDelivery(delivery) && DispatchTargetedResourceIDSchema.safeParse(event.payload.id).success, { message: "delivery resource must match its event type" });
32840
+ function eventPictures(event) {
32841
+ let text;
32842
+ if (event.type.startsWith("message.")) {
32843
+ const parsed = MessageEventPayloadSchema.safeParse(event.payload);
32844
+ text = parsed.success ? parsed.data.body : undefined;
32845
+ } else if (event.type.startsWith("comment.")) {
32846
+ const parsed = CommentEventPayloadSchema.safeParse(event.payload);
32847
+ text = parsed.success ? parsed.data.body : undefined;
32848
+ } else if (event.type.startsWith("ask.")) {
32849
+ const parsed = (event.type === "ask.edited" ? AskEditedEventPayloadSchema : AskEventPayloadSchema).safeParse(event.payload);
32850
+ if (parsed.success) {
32851
+ switch (event.type) {
32852
+ case "ask.answered":
32853
+ text = parsed.data.answer?.text;
32854
+ break;
32855
+ case "ask.resolved":
32856
+ text = parsed.data.resolution?.reason;
32857
+ break;
32858
+ case "ask.opened":
32859
+ case "ask.edited":
32860
+ text = parsed.data.question;
32861
+ break;
32862
+ }
32863
+ }
32864
+ }
32865
+ return typeof text === "string" ? pictureAddresses(text) : [];
32866
+ }
32867
+ function senderLabel(envelope) {
32868
+ const sender = envelope.source_session ?? envelope.source ?? "unknown";
32869
+ return envelope.sender?.title === undefined ? sender : `${sender} (${envelope.sender.title})`;
32870
+ }
32871
+ function replyWith(envelope) {
32872
+ if (envelope.source !== "agent" || envelope.source_session === undefined)
32873
+ return;
32874
+ return {
32875
+ tool: "envoy_send",
32876
+ args: {
32877
+ session_id: envelope.source_session,
32878
+ ...envelope.event_id === undefined ? {} : { in_reply_to: envelope.event_id },
32879
+ message: "..."
32880
+ }
32881
+ };
32882
+ }
32883
+ var DISPATCH_PAYLOAD_SCHEMAS = {
32884
+ "issue.created": IssueEventPayloadSchema,
32885
+ "issue.updated": IssueEventPayloadSchema,
32886
+ "issue.closed": IssueEventPayloadSchema,
32887
+ "artifact.created": ArtifactCreatedEventPayloadSchema,
32888
+ "artifact.version": ArtifactVersionEventPayloadSchema,
32889
+ "artifact.human_edited": ArtifactHumanEditedEventPayloadSchema,
32890
+ "ask.opened": AskEventPayloadSchema,
32891
+ "ask.anchor_refreshed": AskEventPayloadSchema,
32892
+ "ask.edited": AskEditedEventPayloadSchema,
32893
+ "ask.handed_back": AskEventPayloadSchema,
32894
+ "ask.answered": AskEventPayloadSchema,
32895
+ "ask.resolved": AskEventPayloadSchema,
32896
+ "comment.created": CommentEventPayloadSchema,
32897
+ "comment.anchor_refreshed": CommentEventPayloadSchema,
32898
+ "comment.resolved": CommentEventPayloadSchema,
32899
+ "comment.reopened": CommentEventPayloadSchema,
32900
+ "comment.edited": CommentEventPayloadSchema,
32901
+ "suggestion.accepted": CommentEventPayloadSchema,
32902
+ "suggestion.rejected": CommentEventPayloadSchema,
32903
+ "message.created": MessageEventPayloadSchema,
32904
+ "message.delivery": MessageDeliveryEventPayloadSchema,
32905
+ "message.answered": MessageEventPayloadSchema,
32906
+ "child.status": ChildStatusEventPayloadSchema
32907
+ };
32908
+ function topicDocument(topic) {
32909
+ if (topic?.startsWith(DISPATCH_DOCUMENT_TOPIC_PREFIX) !== true)
32910
+ return;
32911
+ const [project, slug] = topic.slice(DISPATCH_DOCUMENT_TOPIC_PREFIX.length).split(".", 3);
32912
+ return project !== undefined && project !== "" && slug !== undefined && slug !== "" ? { project, slug } : undefined;
32913
+ }
32914
+ function dispatchOwner(event, topic) {
32915
+ if (event.issue_key !== null)
32916
+ return event.issue_key;
32917
+ const document = topicDocument(topic);
32918
+ if (document !== undefined)
32919
+ return `${document.project} / ${document.slug}`;
32920
+ return event.artifact_id ?? "unknown";
32921
+ }
32922
+ function dispatchCommentReplyWith(event, topic, comment) {
32923
+ if (comment === undefined || comment.id === undefined)
32924
+ return;
32925
+ const reply = comment.ask_id;
32926
+ const thread = reply === undefined || reply === null || reply === "" ? "reply_to" : "reply_to_ask";
32927
+ const threadID = thread === "reply_to" ? comment.id : String(reply);
32928
+ if (event.issue_key !== null) {
32929
+ return {
32930
+ command: commandLine("dispatch_comment", {
32931
+ issue: event.issue_key,
32932
+ [thread]: threadID,
32933
+ body: "..."
32934
+ })
32935
+ };
32936
+ }
32937
+ let project = comment.project_key;
32938
+ let artifact = comment.artifact_slug;
32939
+ if (project === undefined || project === "" || artifact === undefined || artifact === "") {
32940
+ [project, artifact] = dispatchOwner(event, topic).split(" / ", 2);
32941
+ }
32942
+ if (project === undefined || project === "" || artifact === undefined || artifact === "")
32943
+ return;
32944
+ return {
32945
+ command: commandLine("dispatch_comment", {
32946
+ project,
32947
+ artifact,
32948
+ [thread]: threadID,
32949
+ body: "..."
32950
+ })
32951
+ };
32952
+ }
32953
+ function askResolutionText(resolution) {
32954
+ if (resolution === null || resolution === undefined)
32955
+ return;
32956
+ const kind = resolution.kind ?? "resolved";
32957
+ const reason = resolution.reason ?? "";
32958
+ return reason === "" ? kind : `${kind}: ${reason}`;
32959
+ }
32960
+ function dispatchCompact(event, comment) {
32961
+ if (event.type === "artifact.human_edited") {
32962
+ const edit = ArtifactHumanEditedEventPayloadSchema.safeParse(event.payload);
32963
+ if (!edit.success)
32964
+ return;
32965
+ return { askId: undefined, record: { edit: humanEditHead(edit.data) } };
32966
+ }
32967
+ if (event.type === "comment.created") {
32968
+ if (comment?.ask_id === undefined || comment.ask_id === null)
32969
+ return;
32970
+ const question = dispatchAskQuestion(comment);
32971
+ return {
32972
+ askId: comment.ask_id,
32973
+ record: {
32974
+ ...question === undefined ? {} : { question },
32975
+ reply: comment.body ?? "",
32976
+ ...comment.ask_state === undefined ? {} : { state: comment.ask_state },
32977
+ ...comment.ask_waiting_on === undefined ? {} : { waiting_on: comment.ask_waiting_on }
32978
+ }
32979
+ };
32980
+ }
32981
+ if (!event.type.startsWith("ask."))
32982
+ return;
32983
+ const ask = (event.type === "ask.edited" ? AskEditedEventPayloadSchema : AskEventPayloadSchema).safeParse(event.payload);
32984
+ if (!ask.success)
32985
+ return;
32986
+ let record = { question: textHead(ask.data.question ?? "") };
32987
+ switch (event.type) {
32988
+ case "ask.opened":
32989
+ case "ask.edited": {
32990
+ const options = (ask.data.options ?? []).map((option) => option.label ?? "").filter((label) => label !== "");
32991
+ const quote = ask.data.anchor?.quote;
32992
+ const { project, slug } = ask.data.anchor_artifact ?? {};
32993
+ const document = project !== undefined && project !== "" && slug !== undefined && slug !== "" ? `${project}/${slug}` : undefined;
32994
+ const previous = "previous" in ask.data && ask.data.previous !== undefined ? textHead(ask.data.previous.question) : undefined;
32995
+ record = {
32996
+ ...record,
32997
+ ...options.length === 0 ? {} : { options },
32998
+ ...quote === undefined || quote === "" ? {} : { quote: textHead(quote) },
32999
+ ...document === undefined ? {} : { document },
33000
+ ...previous === undefined ? {} : { previous }
33001
+ };
33002
+ break;
33003
+ }
33004
+ case "ask.answered": {
33005
+ const previousAnswer = ask.data.previous_answer;
33006
+ record = {
33007
+ ...record,
33008
+ answer: askAnswerText(ask.data.answer),
33009
+ ...previousAnswer === null || previousAnswer === undefined ? {} : { previous_answer: askAnswerText(previousAnswer) }
33010
+ };
33011
+ break;
33012
+ }
33013
+ case "ask.resolved": {
33014
+ const resolved = askResolutionText(ask.data.resolution);
33015
+ record = resolved === undefined ? record : { ...record, resolved };
33016
+ break;
33017
+ }
33018
+ default:
33019
+ break;
33020
+ }
33021
+ return { askId: ask.data.id, record };
33022
+ }
33023
+ function dispatchPayload(event) {
33024
+ const schema = DISPATCH_PAYLOAD_SCHEMAS[event.type];
33025
+ if (schema === undefined)
33026
+ return event.payload;
33027
+ const parsed = schema.safeParse(event.payload);
33028
+ return parsed.success ? parsed.data : event.payload;
33029
+ }
33030
+ function hasTarget(value) {
33031
+ return isObject2(value) && "target" in value;
33032
+ }
33033
+ function dispatchPayloadForReader(event, sessionID) {
33034
+ const payload = dispatchPayload(event);
33035
+ if (!hasTarget(payload))
33036
+ return payload;
33037
+ const target = payload.target;
33038
+ return target === `session:${sessionID}` ? { ...payload, target: `you (${target})` } : payload;
33039
+ }
33040
+ function dispatchAskQuestion(comment) {
33041
+ return comment?.ask_question !== undefined && comment.ask_question !== "" ? textHead(comment.ask_question) : undefined;
33042
+ }
33043
+ function dispatchReplyRef(event, topic, inReplyTo, comment) {
33044
+ let kind;
33045
+ let document = topicDocument(topic);
33046
+ if (event.type.startsWith("ask.")) {
33047
+ kind = "ask";
33048
+ } else if (event.type.startsWith("message.")) {
33049
+ kind = "message";
33050
+ } else if (event.type === "comment.created") {
33051
+ if (comment === undefined || comment.ask_id === undefined || comment.ask_id === null) {
33052
+ return inReplyTo;
33053
+ }
33054
+ kind = "ask";
33055
+ const { project_key: project, artifact_slug: slug } = comment;
33056
+ if (project !== undefined && project !== "" && slug !== undefined && slug !== "") {
33057
+ document = { project, slug };
33058
+ }
33059
+ } else {
33060
+ return inReplyTo;
33061
+ }
33062
+ if (event.issue_key !== null) {
33063
+ return dispatchChildRef(dispatchIssueRef(event.issue_key), kind, inReplyTo);
33064
+ }
33065
+ if (document === undefined)
33066
+ return inReplyTo;
33067
+ return dispatchChildRef(dispatchDocumentRef(document.project, document.slug), kind, inReplyTo);
33068
+ }
33069
+ function isObject2(value) {
33070
+ return typeof value === "object" && value !== null;
33071
+ }
33072
+ function parseDispatchFrame(rawPayload) {
33073
+ let value;
33074
+ try {
33075
+ value = JSON.parse(rawPayload);
33076
+ } catch {
33077
+ return { raw: rawPayload };
33078
+ }
33079
+ if (isObject2(value) && "delivery" in value) {
33080
+ const targeted = DispatchTargetedFrameSchema.safeParse(value);
33081
+ if (targeted.success) {
33082
+ const wireFrame = value;
33083
+ return {
33084
+ event: targeted.data.event,
33085
+ notify: wireFrame.event.notify,
33086
+ delivery: targeted.data.delivery
33087
+ };
33088
+ }
33089
+ const recoverable = RecoverableDispatchDeliveryFailureSchema.safeParse(value);
33090
+ if (recoverable.success) {
33091
+ const delivery = recoverable.data.delivery;
33092
+ const commentDelivery = isCommentTargetedDelivery(delivery);
33093
+ const resource = commentDelivery ? "comment" : "message";
33094
+ const id = commentDelivery ? delivery.comment_id : recoverable.data.event.payload.id;
33095
+ return {
33096
+ raw: value,
33097
+ rejectedDelivery: {
33098
+ resource,
33099
+ id,
33100
+ attempt: delivery.attempt,
33101
+ mode: delivery.mode,
33102
+ replyPath: dispatchReplyPath(resource, id),
33103
+ replyFields: commentDelivery ? { target: delivery.target } : {},
33104
+ issueKey: recoverable.data.event.issue_key,
33105
+ body: recoverable.data.event.payload.body ?? ""
33106
+ },
33107
+ malformedDelivery: true
33108
+ };
33109
+ }
33110
+ return { raw: value, malformedDelivery: true };
33111
+ }
33112
+ const parsed = DispatchEventSchema.safeParse(value);
33113
+ if (!parsed.success)
33114
+ return { raw: value };
33115
+ const wireEvent = value;
33116
+ return {
33117
+ event: parsed.data,
33118
+ notify: wireEvent.notify,
33119
+ delivery: undefined
33120
+ };
33121
+ }
33122
+ function inboundTimestamp(milliseconds) {
33123
+ if (milliseconds === undefined)
33124
+ return "unknown";
33125
+ const date = new Date(Math.floor(milliseconds / 1000) * 1000);
33126
+ return Number.isNaN(date.getTime()) ? "unknown" : date.toISOString().replace(".000Z", "Z");
33127
+ }
33128
+ function renderInbound(raw, sessionID, subject) {
33129
+ let value;
33130
+ try {
33131
+ value = JSON.parse(raw);
33132
+ } catch {
33133
+ return {
33134
+ skip: false,
33135
+ content: encode3({
33136
+ envoy: { topic: subject ?? "unknown", unrecognised: "payload was not JSON" }
33137
+ })
33138
+ };
33139
+ }
33140
+ const parsed = InboundEnvelopeSchema.safeParse(value);
33141
+ const parseIssues = parsed.success ? [] : parsed.error.issues.map((issue) => issue.path.join(".") || "envelope");
33142
+ let envelope;
33143
+ if (parsed.success) {
33144
+ envelope = parsed.data;
33145
+ } else {
33146
+ const tolerant = TolerantInboundEnvelopeSchema.safeParse(value);
33147
+ if (!tolerant.success) {
33148
+ return {
33149
+ skip: false,
33150
+ content: encode3({ envoy: { unrecognised: parseIssues.join(", ") || "envelope" } })
33151
+ };
33152
+ }
33153
+ const data = tolerant.data;
33154
+ envelope = { ...data, source: data.source ?? "unknown" };
33155
+ }
33156
+ let dispatchEvent;
33157
+ let dispatchActor;
33158
+ let dispatchIssue;
33159
+ let dispatchReply;
33160
+ let delivery;
33161
+ let rejectedDelivery;
33162
+ let malformedDelivery = false;
33163
+ let pictures = [];
33164
+ let inReplyTo = envelope.in_reply_to;
33165
+ let askAuthor;
33166
+ let trailer = "";
33167
+ const dispatchRendered = envelope.source === "dispatch" && envelope.payload !== undefined;
33168
+ if (envelope.source === "dispatch") {
33169
+ const topic = subject ?? envelope.topic;
33170
+ if (envelope.payload === undefined) {
33171
+ dispatchIssue = "payload";
33172
+ } else {
33173
+ const frame = parseDispatchFrame(envelope.payload);
33174
+ if ("event" in frame) {
33175
+ if (frame.notify === false && topic?.startsWith(DISPATCH_TOPIC_PREFIX) === true) {
33176
+ return { skip: true, content: "", envelope };
33177
+ }
33178
+ if (frame.event.actor.kind === "session" && frame.event.actor.id === sessionID) {
33179
+ return { skip: true, content: "", envelope };
33180
+ }
33181
+ if (frame.event.type === "subscription.removed") {
33182
+ const removed = SubscriptionRemovedEventPayloadSchema.safeParse(frame.event.payload);
33183
+ if (!removed.success || removed.data.session_id !== sessionID) {
33184
+ return { skip: true, content: "", envelope };
33185
+ }
33186
+ const who = removed.data.by?.id ?? "someone";
33187
+ return {
33188
+ skip: false,
33189
+ content: `Unsubscribed from ${dispatchOwner(frame.event, topic)} by ${who}`,
33190
+ envelope
33191
+ };
33192
+ }
33193
+ if (frame.event.type === "ask.follower_added" || frame.event.type === "ask.follower_removed") {
33194
+ const follower = AskFollowerEventPayloadSchema.safeParse(frame.event.payload);
33195
+ if (!follower.success || follower.data.session_id !== sessionID) {
33196
+ return { skip: true, content: "", envelope };
33197
+ }
33198
+ const who = follower.data.by?.id ?? "someone";
33199
+ const owner = dispatchOwner(frame.event, topic);
33200
+ const ask = follower.data.ask_id ?? "?";
33201
+ return {
33202
+ skip: false,
33203
+ content: frame.event.type === "ask.follower_added" ? `Now following ask ${ask} on ${owner} (added by ${who}): its answer and replies reach you directly; ${commandLine("dispatch_follow", { ask, action: "unfollow" })} to stop.` : `No longer following ask ${ask} on ${owner} (removed by ${who}).`,
33204
+ envelope
33205
+ };
33206
+ }
33207
+ const comment = frame.event.type === "comment.created" ? CommentEventPayloadSchema.safeParse(frame.event.payload) : undefined;
33208
+ const commentPayload = comment?.success === true ? comment.data : undefined;
33209
+ const compact = dispatchCompact(frame.event, commentPayload);
33210
+ if (frame.event.type.startsWith("ask.")) {
33211
+ const asked = AskAuthorPayloadSchema.safeParse(frame.event.payload);
33212
+ if (asked.success && asked.data.author.kind === "session") {
33213
+ askAuthor = asked.data.author.id;
33214
+ }
33215
+ }
33216
+ if (inReplyTo !== undefined) {
33217
+ inReplyTo = dispatchReplyRef(frame.event, topic, inReplyTo, commentPayload);
33218
+ }
33219
+ dispatchReply = dispatchCommentReplyWith(frame.event, topic, commentPayload);
33220
+ if (frame.event.type === "message.created") {
33221
+ const message = DispatchTargetedMessagePayloadSchema.safeParse(frame.event.payload);
33222
+ const requested = DispatchTargetedDeliverySchema.safeParse(frame.delivery);
33223
+ if (message.success && requested.success && !isCommentTargetedDelivery(requested.data)) {
33224
+ delivery = {
33225
+ resource: "message",
33226
+ id: message.data.id,
33227
+ attempt: requested.data.attempt,
33228
+ mode: requested.data.mode,
33229
+ replyPath: dispatchReplyPath("message", message.data.id),
33230
+ replyFields: {},
33231
+ issueKey: frame.event.issue_key,
33232
+ body: message.data.body,
33233
+ ...typeof message.data.broadcast_id === "string" ? { broadcastId: message.data.broadcast_id } : {}
33234
+ };
33235
+ dispatchReply = {
33236
+ command: commandLine("dispatch_message", {
33237
+ ...frame.event.issue_key === null ? {} : { issue: frame.event.issue_key },
33238
+ in_reply_to: message.data.id,
33239
+ body: "..."
33240
+ })
33241
+ };
33242
+ }
33243
+ } else if (frame.event.type === "comment.created") {
33244
+ const comment = DispatchTargetedCommentPayloadSchema.safeParse(frame.event.payload);
33245
+ const requested = DispatchTargetedDeliverySchema.safeParse(frame.delivery);
33246
+ if (comment.success && requested.success && isCommentTargetedDelivery(requested.data)) {
33247
+ delivery = {
33248
+ resource: "comment",
33249
+ id: requested.data.comment_id,
33250
+ attempt: requested.data.attempt,
33251
+ mode: requested.data.mode,
33252
+ replyPath: dispatchReplyPath("comment", requested.data.comment_id),
33253
+ replyFields: { target: requested.data.target },
33254
+ issueKey: frame.event.issue_key,
33255
+ body: comment.data.body
33256
+ };
33257
+ }
33258
+ }
33259
+ const compactRecord = compact === undefined ? undefined : inReplyTo !== undefined || compact.askId === undefined ? compact.record : {
33260
+ ask: dispatchReplyRef(frame.event, topic, compact.askId, commentPayload),
33261
+ ...compact.record
33262
+ };
33263
+ dispatchEvent = {
33264
+ owner: dispatchOwner(frame.event, topic),
33265
+ type: frame.event.type,
33266
+ actor: frame.event.actor,
33267
+ ...compactRecord ?? { payload: dispatchPayloadForReader(frame.event, sessionID) }
33268
+ };
33269
+ dispatchActor = frame.event.actor;
33270
+ pictures = eventPictures(frame.event);
33271
+ if (frame.event.type === "artifact.human_edited") {
33272
+ const edit = ArtifactHumanEditedEventPayloadSchema.safeParse(frame.event.payload);
33273
+ if (edit.success)
33274
+ trailer = humanEditDiffBlock(edit.data.diff, edit.data.diff_truncated);
33275
+ }
33276
+ } else {
33277
+ dispatchEvent = frame.raw;
33278
+ rejectedDelivery = frame.rejectedDelivery;
33279
+ malformedDelivery = frame.malformedDelivery === true;
33280
+ }
33281
+ }
33282
+ }
33283
+ let parsedPayload;
33284
+ if (!dispatchRendered && envelope.payload !== undefined && (envelope.source === "github" || envelope.payload !== envelope.payload_summary)) {
33285
+ try {
33286
+ parsedPayload = JSON.parse(envelope.payload);
33287
+ } catch {
33288
+ parsedPayload = envelope.payload;
33289
+ }
33290
+ }
33291
+ const payloadSummary = envelope.payload_summary ?? "unknown";
33292
+ const message = !dispatchRendered && envelope.payload !== undefined && envelope.payload !== envelope.payload_summary ? parsedPayload : undefined;
33293
+ const summaryIsHead = typeof message === "string" && envelope.payload_summary !== undefined && message.startsWith(envelope.payload_summary.endsWith("\u2026") ? envelope.payload_summary.slice(0, -1) : envelope.payload_summary);
33294
+ let foreignSession;
33295
+ for (const part of [envelope.payload_summary ?? "", envelope.payload ?? ""]) {
33296
+ for (const match of part.matchAll(FOREIGN_SESSION_ID)) {
33297
+ if (match[0] !== envelope.source_session && match[0] !== sessionID && match[0] !== askAuthor) {
33298
+ foreignSession = match[0];
33299
+ break;
33300
+ }
33301
+ }
33302
+ if (foreignSession !== undefined)
33303
+ break;
33304
+ }
33305
+ const role = envelope.sender?.roles?.[0];
33306
+ const reply = dispatchReply ?? replyWith(envelope);
33307
+ const sourceIssue = parseIssues.includes("source") || KNOWN_SOURCES[envelope.source] !== undefined ? undefined : `source=${envelope.source}`;
33308
+ const unrecognised = [
33309
+ ...parseIssues,
33310
+ ...sourceIssue === undefined ? [] : [sourceIssue],
33311
+ ...dispatchIssue === undefined ? [] : [dispatchIssue]
33312
+ ].join(", ") || undefined;
33313
+ const rendered = {
33314
+ ...envelope.topic === agentSubject(sessionID) ? { to: `you (${sessionID})` } : {},
33315
+ from: senderLabel(envelope),
33316
+ at: inboundTimestamp(envelope.issued_at),
33317
+ id: envelope.event_id ?? "unknown",
33318
+ ...envelope.expires_at === undefined ? {} : { by: inboundTimestamp(envelope.expires_at) },
33319
+ ...envelope.urgency === undefined ? {} : { urgency: envelope.urgency },
33320
+ ...envelope.expects_reply === undefined ? {} : { expects_reply: envelope.expects_reply },
33321
+ ...inReplyTo === undefined ? {} : { re: inReplyTo },
33322
+ ...envelope.supersedes === undefined ? {} : { supersedes: envelope.supersedes },
33323
+ ...reply === undefined ? {} : { reply_with: reply },
33324
+ ...role === undefined ? {} : {
33325
+ reply_role: {
33326
+ tool: "envoy_publish",
33327
+ args: { topic: `notifications.role.${role}`, message: "..." }
33328
+ }
33329
+ },
33330
+ ...dispatchRendered ? { dispatch: dispatchEvent } : {
33331
+ ...summaryIsHead ? {} : { summary: payloadSummary },
33332
+ ...message === undefined ? {} : { message }
33333
+ },
33334
+ ...foreignSession === undefined ? {} : {
33335
+ note: `body names session ${foreignSession}; the sender is ${envelope.source_session ?? "unknown"}`
33336
+ },
33337
+ ...unrecognised === undefined ? {} : { unrecognised }
33338
+ };
33339
+ return {
33340
+ skip: false,
33341
+ content: trailer === "" ? encode3({ envoy: rendered }) : `${encode3({ envoy: rendered })}
33342
+
33343
+ ${trailer}`,
33344
+ envelope,
33345
+ ...dispatchActor === undefined ? {} : { dispatchActor },
33346
+ ...delivery === undefined ? {} : { delivery },
33347
+ ...rejectedDelivery === undefined ? {} : { rejectedDelivery },
33348
+ ...malformedDelivery ? { malformedDelivery: true } : {},
33349
+ ...pictures.length === 0 ? {} : { pictures }
33350
+ };
33351
+ }
33352
+
33353
+ // ../envoy-client/src/envoy-config.ts
33354
+ import {
33355
+ chmodSync,
33356
+ closeSync as closeSync2,
33357
+ existsSync,
33358
+ lstatSync,
33359
+ mkdtempSync,
33360
+ openSync as openSync2,
33361
+ readFileSync as readFileSync3,
33362
+ readlinkSync,
33363
+ rmSync as rmSync2,
33364
+ statSync as statSync2
33365
+ } from "fs";
33366
+ import { homedir, tmpdir } from "os";
33367
+ import * as path from "path";
33368
+
33369
+ // ../envoy-client/src/json-position.ts
33370
+ function jsonErrorPosition(text) {
33371
+ let at = 0;
33372
+ const fail = () => {
33373
+ throw new RangeError("not JSON");
33374
+ };
33375
+ const space = () => {
33376
+ while (at < text.length && `
33377
+ \r`.includes(text.charAt(at)))
33378
+ at += 1;
33379
+ };
33380
+ const expect = (char) => {
33381
+ if (text.charAt(at) !== char)
33382
+ fail();
33383
+ at += 1;
33384
+ };
33385
+ const string = () => {
33386
+ expect('"');
33387
+ while (at < text.length) {
33388
+ const char = text.charAt(at);
33389
+ if (char === '"') {
33390
+ at += 1;
33391
+ return;
33392
+ }
33393
+ if (char < " ")
33394
+ fail();
33395
+ at += char === "\\" ? 2 : 1;
33394
33396
  }
33395
- try {
33396
- const source = await this.#json("GET", [
33397
- "api",
33398
- "v1",
33399
- "projects",
33400
- project,
33401
- "architecture-source"
33402
- ]);
33403
- return source === null ? [] : [source];
33404
- } catch (error) {
33405
- if (error instanceof DispatchServiceError && error.status === 404 && error.code === "SOURCE_NOT_FOUND") {
33406
- return [];
33397
+ fail();
33398
+ };
33399
+ const value = () => {
33400
+ space();
33401
+ const char = text.charAt(at);
33402
+ if (char === "{" || char === "[") {
33403
+ const close = char === "{" ? "}" : "]";
33404
+ at += 1;
33405
+ space();
33406
+ if (text.charAt(at) === close) {
33407
+ at += 1;
33408
+ return;
33409
+ }
33410
+ for (;; ) {
33411
+ if (close === "}") {
33412
+ space();
33413
+ string();
33414
+ space();
33415
+ expect(":");
33416
+ }
33417
+ value();
33418
+ space();
33419
+ if (text.charAt(at) === ",") {
33420
+ at += 1;
33421
+ continue;
33422
+ }
33423
+ expect(close);
33424
+ return;
33407
33425
  }
33408
- throw error;
33409
33426
  }
33410
- }
33411
- async syncArchitectureSources(project) {
33412
- try {
33413
- return await this.#json("POST", [
33414
- "api",
33415
- "v1",
33416
- "projects",
33417
- project,
33418
- "architecture-sources",
33419
- "sync"
33420
- ]);
33421
- } catch (error) {
33422
- if (!isNoRoute(error))
33423
- throw error;
33427
+ if (char === '"') {
33428
+ string();
33429
+ return;
33424
33430
  }
33425
- const source = await this.#json("POST", [
33426
- "api",
33427
- "v1",
33428
- "projects",
33429
- project,
33430
- "architecture-source",
33431
- "sync"
33432
- ]);
33433
- return [source];
33434
- }
33435
- async syncArchitectureSource(project, repo) {
33436
- const [owner, name, ...rest] = repo.split("/");
33437
- if (!owner || !name || rest.length > 0) {
33438
- throw new Error(`repository must be owner/name, got ${JSON.stringify(repo)}`);
33431
+ for (const word of ["true", "false", "null"]) {
33432
+ if (text.startsWith(word, at)) {
33433
+ at += word.length;
33434
+ return;
33435
+ }
33439
33436
  }
33440
- return this.#json("POST", [
33441
- "api",
33442
- "v1",
33443
- "projects",
33444
- project,
33445
- "architecture-sources",
33446
- owner,
33447
- name,
33448
- "sync"
33449
- ]);
33437
+ const number = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/.exec(text.slice(at));
33438
+ if (number === null)
33439
+ fail();
33440
+ at += number?.[0].length ?? 0;
33441
+ };
33442
+ try {
33443
+ value();
33444
+ space();
33445
+ if (at < text.length)
33446
+ fail();
33447
+ return;
33448
+ } catch {
33449
+ const before = text.slice(0, at).split(`
33450
+ `);
33451
+ return `line ${before.length}, column ${(before.at(-1)?.length ?? 0) + 1}`;
33450
33452
  }
33451
- async resolveAsk(id, input) {
33452
- return this.#json("POST", ["api", "v1", "asks", id, "resolve"], input);
33453
+ }
33454
+
33455
+ // ../envoy-client/src/secret-file.ts
33456
+ import { readFileSync as readFileSync2 } from "fs";
33457
+ function sendable(value) {
33458
+ return !/[\s\p{Cc}]/u.test(value);
33459
+ }
33460
+ function readSecretFile(variable, filePath) {
33461
+ let contents;
33462
+ try {
33463
+ contents = readFileSync2(filePath, "utf8");
33464
+ } catch (error) {
33465
+ throw new Error(`${variable} names ${filePath}, which could not be read: ${messageFor(error)}`);
33453
33466
  }
33454
- async requestApproval(artifactID, input) {
33455
- const answer = await this.#jsonAnswer("POST", ["api", "v1", "artifacts", artifactID, "approval-requests"], input);
33456
- return { ...answer.payload, recorded: answer.status === 201 };
33467
+ const value = contents.trim();
33468
+ if (value.length === 0)
33469
+ throw new Error(`${variable} names ${filePath}, which is empty`);
33470
+ if (!sendable(value)) {
33471
+ throw new Error(`${variable} names ${filePath}, which holds whitespace or a control character`);
33457
33472
  }
33458
- async editAsk(id, input) {
33459
- return this.#json("PATCH", ["api", "v1", "asks", id], input);
33473
+ return value;
33474
+ }
33475
+
33476
+ // ../envoy-client/src/envoy-config.ts
33477
+ var COMMAND_TIMEOUT_MS = 1e4;
33478
+ function nonEmpty(value) {
33479
+ return value === undefined || value === "" ? undefined : value;
33480
+ }
33481
+ function absolute(name, value) {
33482
+ if (value !== undefined && !path.isAbsolute(value)) {
33483
+ throw new Error(`${name} is ${value}, which is not an absolute path`);
33460
33484
  }
33461
- async comment(issue, input) {
33462
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"], input);
33485
+ return value;
33486
+ }
33487
+ function neutralConfig(env) {
33488
+ const xdgConfigHome = nonEmpty(env.XDG_CONFIG_HOME);
33489
+ if (xdgConfigHome !== undefined && !path.isAbsolute(xdgConfigHome)) {
33490
+ return { error: `XDG_CONFIG_HOME is ${xdgConfigHome}, which is not an absolute path` };
33463
33491
  }
33464
- async listIssueAsks(issue, state) {
33465
- return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "asks"], undefined, state === undefined ? undefined : { state });
33492
+ const configHome = xdgConfigHome ?? path.join(nonEmpty(env.HOME) ?? homedir(), ".config");
33493
+ return { path: path.resolve(configHome, "legion", "envoy.json") };
33494
+ }
33495
+ var HARNESS_DIRECTORY_VARIABLE = {
33496
+ omp: "PI_CODING_AGENT_DIR",
33497
+ claude: "CLAUDE_CONFIG_DIR",
33498
+ opencode: "OPENCODE_CONFIG_DIR"
33499
+ };
33500
+ var PLUGIN_HARNESSES = Object.keys(HARNESS_DIRECTORY_VARIABLE);
33501
+ function namedDirectory(harness, env) {
33502
+ if (harness === "omp") {
33503
+ const profile = nonEmpty(env.OMP_PROFILE);
33504
+ if (profile === undefined || profile === "default")
33505
+ return;
33466
33506
  }
33467
- async getArtifactAsks(id, state) {
33468
- return this.#json("GET", ["api", "v1", "artifacts", id, "asks"], undefined, state === undefined ? undefined : { state });
33507
+ return nonEmpty(env[HARNESS_DIRECTORY_VARIABLE[harness]]);
33508
+ }
33509
+ function harnessDirectory(harness, env) {
33510
+ for (const plugin of harness === "command" ? PLUGIN_HARNESSES : [harness]) {
33511
+ if (harness === "command" && plugin === "claude" && env.CLAUDE_CODE_CHILD_SESSION !== "1") {
33512
+ continue;
33513
+ }
33514
+ const directory = namedDirectory(plugin, env);
33515
+ if (directory !== undefined)
33516
+ return absolute(HARNESS_DIRECTORY_VARIABLE[plugin], directory);
33469
33517
  }
33470
- async artifactAsk(id, input) {
33471
- return this.#json("POST", ["api", "v1", "artifacts", id, "asks"], input);
33518
+ return;
33519
+ }
33520
+ function handedConfigPath(env) {
33521
+ const handed = nonEmpty(env.ENVOY_CONFIG_FILE);
33522
+ return handed === undefined ? undefined : path.resolve(absolute("ENVOY_CONFIG_FILE", handed));
33523
+ }
33524
+ function envoyConfigPath(harness, env) {
33525
+ const handedFirst = harness === "command" ? handedConfigPath(env) : undefined;
33526
+ if (handedFirst !== undefined)
33527
+ return handedFirst;
33528
+ const directory = harnessDirectory(harness, env);
33529
+ if (directory !== undefined)
33530
+ return path.resolve(directory, "envoy.json");
33531
+ const handed = handedConfigPath(env);
33532
+ if (handed !== undefined)
33533
+ return handed;
33534
+ const neutral = neutralConfig(env);
33535
+ if ("error" in neutral)
33536
+ throw new Error(neutral.error);
33537
+ return neutral.path;
33538
+ }
33539
+ var httpUrlSchema = url({ protocol: /^https?$/, error: "must be an http or https URL" });
33540
+ var DispatchSectionSchema = strictObject({
33541
+ enabled: boolean2().optional(),
33542
+ serverUrl: httpUrlSchema.optional(),
33543
+ token: string2().optional()
33544
+ });
33545
+ var EnvoySectionSchema = strictObject({
33546
+ enabled: boolean2().optional(),
33547
+ url: httpUrlSchema.optional(),
33548
+ natsUrls: array(string2().trim().min(1, "must not be empty")).optional(),
33549
+ token: string2().optional(),
33550
+ natsSeed: string2().optional()
33551
+ });
33552
+ var EnvoyFileSchema = looseObject({
33553
+ $schema: string2().optional(),
33554
+ dispatch: DispatchSectionSchema.optional(),
33555
+ envoy: EnvoySectionSchema.optional()
33556
+ });
33557
+ var CheckoutFileSchema = looseObject({
33558
+ $schema: string2().optional(),
33559
+ dispatch: DispatchSectionSchema.optional()
33560
+ });
33561
+ var AskgateSectionSchema = strictObject({ enabled: boolean2().optional() });
33562
+ function offWithNotice(notice) {
33563
+ return { enabled: false, notice, error: null };
33564
+ }
33565
+ function offWithError(error) {
33566
+ return { enabled: false, notice: null, error };
33567
+ }
33568
+ function httpUrl2(value) {
33569
+ let url2;
33570
+ try {
33571
+ url2 = new URL(value);
33572
+ } catch {
33573
+ return;
33472
33574
  }
33473
- async suggest(issue, input) {
33474
- const { replace_with, ...comment } = input;
33475
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"], {
33476
- ...comment,
33477
- suggestion: { replace_with }
33478
- });
33575
+ return url2.protocol === "http:" || url2.protocol === "https:" ? url2 : undefined;
33576
+ }
33577
+ function describeSchemaIssue(filePath, error) {
33578
+ const issue = error.issues[0];
33579
+ if (!issue)
33580
+ return `${filePath}: invalid envoy.json`;
33581
+ if (issue.code === "unrecognized_keys") {
33582
+ const section = issue.path.join(".");
33583
+ const keys = issue.keys.map((key) => `${section}.${key}`).join(", ");
33584
+ return `${filePath}: unrecognized ${section} key(s): ${keys}`;
33479
33585
  }
33480
- async getArtifactComments(id) {
33481
- return this.#json("GET", ["api", "v1", "artifacts", id, "comments"]);
33586
+ return `${filePath}: ${issue.path.join(".")}: ${issue.message}`;
33587
+ }
33588
+ function danglingLink(filePath) {
33589
+ try {
33590
+ return lstatSync(filePath).isSymbolicLink() ? readlinkSync(filePath) : null;
33591
+ } catch {
33592
+ return null;
33482
33593
  }
33483
- async artifactComment(id, input) {
33484
- return this.#json("POST", ["api", "v1", "artifacts", id, "comments"], input);
33594
+ }
33595
+ function parseFile(filePath, schema, checkout) {
33596
+ let raw;
33597
+ try {
33598
+ raw = readFileSync3(filePath, "utf-8");
33599
+ } catch (error) {
33600
+ if (hasErrnoCode(error, "ENOENT") || hasErrnoCode(error, "ENOTDIR")) {
33601
+ return { kind: "absent", link: danglingLink(filePath) };
33602
+ }
33603
+ return { kind: "invalid", reason: `${filePath}: could not be read (${messageFor(error)})` };
33485
33604
  }
33486
- async artifactSuggest(id, input) {
33487
- const { replace_with, ...comment } = input;
33488
- return this.#json("POST", ["api", "v1", "artifacts", id, "comments"], {
33489
- ...comment,
33490
- suggestion: { replace_with }
33491
- });
33605
+ let parsedJson;
33606
+ try {
33607
+ parsedJson = JSON.parse(raw);
33608
+ } catch {
33609
+ const position = jsonErrorPosition(raw);
33610
+ return {
33611
+ kind: "invalid",
33612
+ reason: `${filePath}: invalid JSON${position === undefined ? "" : ` at ${position}`}`
33613
+ };
33492
33614
  }
33493
- async message(issue, input) {
33494
- return this.#json("POST", ["api", "v1", "issues", await this.#resolveIssue(issue), "messages"], input);
33615
+ if (typeof parsedJson === "object" && parsedJson !== null && "natsUrls" in parsedJson) {
33616
+ return {
33617
+ kind: "invalid",
33618
+ reason: checkout ? `${filePath}: the top-level natsUrls is not read, and a checkout's envoy.json holds only a dispatch section` : `${filePath}: the top-level natsUrls is not read; move it to envoy.natsUrls`
33619
+ };
33495
33620
  }
33496
- async messageReply(id, input, options = {}) {
33497
- return this.#json("POST", ["api", "v1", "messages", id, "reply"], input, options.followUp === true ? { follow_up: "true" } : undefined);
33621
+ const parsed = schema.safeParse(parsedJson);
33622
+ if (!parsed.success) {
33623
+ return { kind: "invalid", reason: describeSchemaIssue(filePath, parsed.error) };
33498
33624
  }
33499
- async getMessage(issue, id) {
33500
- return this.#json("GET", [
33501
- "api",
33502
- "v1",
33503
- "issues",
33504
- await this.#resolveIssue(issue),
33505
- "messages",
33506
- id
33507
- ]);
33625
+ return { kind: "valid", settings: parsed.data };
33626
+ }
33627
+ var FAILURE_KEPT_MS = 60000;
33628
+ var COMMAND_OUTCOMES = Symbol.for("legion.envoy-config.commands.v1");
33629
+ var processGlobal = globalThis;
33630
+ var commandOutcomes = processGlobal[COMMAND_OUTCOMES] ?? new Map;
33631
+ processGlobal[COMMAND_OUTCOMES] = commandOutcomes;
33632
+ function runCommand(command, env, cwd) {
33633
+ const childEnv = {};
33634
+ for (const [name, variable] of Object.entries(env)) {
33635
+ if (variable !== undefined)
33636
+ childEnv[name] = variable;
33508
33637
  }
33509
- async getMessageThread(id, session) {
33510
- return this.#json("GET", ["api", "v1", "messages", id], undefined, { session });
33638
+ const directory = mkdtempSync(path.join(tmpdir(), "envoy-command-"));
33639
+ try {
33640
+ chmodSync(directory, 448);
33641
+ const output = path.join(directory, "stdout");
33642
+ const fd = openSync2(output, "wx", 384);
33643
+ let result;
33644
+ try {
33645
+ result = Bun.spawnSync(["/bin/sh", "-c", command], {
33646
+ cwd,
33647
+ env: childEnv,
33648
+ stdin: "ignore",
33649
+ stdout: fd,
33650
+ stderr: "ignore",
33651
+ timeout: COMMAND_TIMEOUT_MS,
33652
+ detached: true
33653
+ });
33654
+ } catch (error) {
33655
+ return { failure: `could not start: ${messageFor(error)}`, timedOut: false };
33656
+ } finally {
33657
+ closeSync2(fd);
33658
+ }
33659
+ try {
33660
+ process.kill(-result.pid, "SIGKILL");
33661
+ } catch {}
33662
+ if (result.exitedDueToTimeout) {
33663
+ return {
33664
+ failure: `did not finish within ${COMMAND_TIMEOUT_MS / 1000} s, and does not run again in this process`,
33665
+ timedOut: true
33666
+ };
33667
+ }
33668
+ if (!result.success) {
33669
+ return {
33670
+ failure: `exited with ${result.signalCode ?? `status ${result.exitCode}`}`,
33671
+ timedOut: false
33672
+ };
33673
+ }
33674
+ const value = readFileSync3(output, "utf-8").trim();
33675
+ if (value.length === 0)
33676
+ return { failure: "printed nothing", timedOut: false };
33677
+ if (!sendable(value)) {
33678
+ return {
33679
+ failure: "printed more than one line, or whitespace inside its value",
33680
+ timedOut: false
33681
+ };
33682
+ }
33683
+ return { value };
33684
+ } finally {
33685
+ rmSync2(directory, { recursive: true, force: true });
33511
33686
  }
33512
- async acceptMessageDelivery(id, attempt, input) {
33513
- return this.#json("POST", ["api", "v1", "messages", id, "deliveries", String(attempt), "accept"], input);
33687
+ }
33688
+ function fileValue(value, field, filePath, env) {
33689
+ if (!value.startsWith("!")) {
33690
+ if (!sendable(value)) {
33691
+ throw new Error(`${filePath}: ${field} holds whitespace or a control character`);
33692
+ }
33693
+ return value;
33514
33694
  }
33515
- async artifact(issue, input) {
33516
- return this.#upload(["api", "v1", "issues", await this.#resolveIssue(issue), "artifacts"], input);
33695
+ const command = value.slice(1);
33696
+ const cwd = path.dirname(path.resolve(filePath));
33697
+ const key = JSON.stringify([command, filePath, cwd]);
33698
+ let outcome = commandOutcomes.get(key);
33699
+ if (outcome === undefined || "failure" in outcome && !outcome.timedOut && Date.now() - outcome.at >= FAILURE_KEPT_MS) {
33700
+ outcome = { ...runCommand(command, env, cwd), at: Date.now() };
33701
+ commandOutcomes.set(key, outcome);
33517
33702
  }
33518
- async getArtifact(id) {
33519
- return this.#json("GET", ["api", "v1", "artifacts", id]);
33703
+ if ("failure" in outcome)
33704
+ throw new Error(`${filePath}: ${field}'s command ${outcome.failure}`);
33705
+ return outcome.value;
33706
+ }
33707
+ function statDevice(directory) {
33708
+ try {
33709
+ return statSync2(directory).dev;
33710
+ } catch {
33711
+ return;
33520
33712
  }
33521
- async docRead(id, version) {
33522
- return version === undefined ? this.#json("GET", ["api", "v1", "artifacts", id, "text"]) : this.#json("GET", ["api", "v1", "artifacts", id, "versions", String(version)]);
33713
+ }
33714
+ function moveNotice(oldFile, newFile, move, deviceOf) {
33715
+ const oldDevice = deviceOf(path.dirname(oldFile));
33716
+ let ancestor = path.dirname(newFile);
33717
+ let newDevice = deviceOf(ancestor);
33718
+ while (newDevice === undefined && path.dirname(ancestor) !== ancestor) {
33719
+ ancestor = path.dirname(ancestor);
33720
+ newDevice = deviceOf(ancestor);
33523
33721
  }
33524
- async fileVersion(id, version) {
33525
- const url = this.#url(["api", "v1", "artifacts", id, "versions", String(version)]);
33526
- const response = await this.fetchImpl(url, {
33527
- method: "GET",
33528
- headers: { Accept: "*/*", Authorization: `Bearer ${this.token}` },
33529
- signal: this.#signal
33530
- });
33531
- if (!response.ok)
33532
- return this.#response("GET", url, response);
33533
- return {
33534
- mime: response.headers.get("Content-Type") ?? "application/octet-stream",
33535
- bytes: new Uint8Array(await response.arrayBuffer())
33536
- };
33722
+ if (oldDevice !== undefined && newDevice !== undefined && oldDevice !== newDevice) {
33723
+ return `${oldFile} is not read, and is on another filesystem than ${newFile} (a mount): create ${newFile}, and move ${oldFile} on the machine that owns it`;
33537
33724
  }
33538
- async artifactBlocks(id) {
33539
- return this.#json("GET", ["api", "v1", "artifacts", id, "blocks"]);
33725
+ return `${oldFile} is not read: ${move}`;
33726
+ }
33727
+ function oldUserFileNotice(filePath, env, deviceOf) {
33728
+ const home = nonEmpty(env.HOME) ?? homedir();
33729
+ const old = path.join(home, ".config", "opencode", "envoy.json");
33730
+ if (!existsSync(old))
33731
+ return;
33732
+ const selected = path.resolve(filePath);
33733
+ const userFile = path.resolve(home, ".config", "legion", "envoy.json");
33734
+ if (selected === userFile) {
33735
+ return moveNotice(old, userFile, "mkdir -p ~/.config/legion && mv ~/.config/opencode/envoy.json ~/.config/legion/", deviceOf);
33540
33736
  }
33541
- async docEdit(id, input) {
33542
- return this.#json("POST", ["api", "v1", "artifacts", id, "edits"], input);
33737
+ const profileFile = PLUGIN_HARNESSES.map((harness) => namedDirectory(harness, env)).some((directory) => directory !== undefined && path.isAbsolute(directory) && selected === path.resolve(directory, "envoy.json"));
33738
+ if (profileFile) {
33739
+ return `${old} is not read for this profile; copy or link it to ${filePath}, or write that file`;
33543
33740
  }
33544
- async nameArtifactVersion(id, input) {
33545
- return this.#json("POST", ["api", "v1", "artifacts", id, "versions"], input);
33741
+ const configHome = nonEmpty(env.XDG_CONFIG_HOME);
33742
+ const neutral = neutralConfig(env);
33743
+ if (configHome !== undefined && path.isAbsolute(configHome) && "path" in neutral && selected === neutral.path) {
33744
+ return `${old} is not read under XDG_CONFIG_HOME=${configHome}`;
33546
33745
  }
33547
- async getArtifactEvents(id, after = 0, limit = 200) {
33548
- return this.#json("GET", ["api", "v1", "artifacts", id, "events"], undefined, { after, limit });
33746
+ return;
33747
+ }
33748
+ function missingConfigNotice(filePath, missing, off) {
33749
+ const link = missing.link === null ? "" : ` (a link to ${missing.link}, which does not exist)`;
33750
+ const old = missing.oldUserFileNotice === undefined ? "" : `; ${missing.oldUserFileNotice}`;
33751
+ return `no envoy.json at ${filePath}${link}: ${off}${old}`;
33752
+ }
33753
+ function readEnvoyConfig(filePath, env, options) {
33754
+ const deviceOf = options.deviceOf ?? statDevice;
33755
+ const chosen = parseFile(filePath, EnvoyFileSchema, false);
33756
+ if (chosen.kind === "invalid")
33757
+ return { kind: "failed", path: filePath, error: chosen.reason };
33758
+ const resolvedChosen = path.resolve(filePath);
33759
+ const checkoutPath = path.resolve(options.cwd, ".envoy", "envoy.json");
33760
+ const checkoutFile = checkoutPath === resolvedChosen ? { kind: "absent", link: null } : parseFile(checkoutPath, CheckoutFileSchema, true);
33761
+ const own = chosen.kind === "valid" ? chosen.settings : {};
33762
+ let checkout = null;
33763
+ if (checkoutFile.kind === "invalid") {
33764
+ checkout = { kind: "invalid", path: checkoutPath, error: checkoutFile.reason };
33765
+ } else if (checkoutFile.kind === "valid") {
33766
+ checkout = {
33767
+ kind: "valid",
33768
+ path: checkoutPath,
33769
+ dispatch: checkoutFile.settings.dispatch ?? {},
33770
+ envoyError: Object.hasOwn(checkoutFile.settings, "envoy") ? `${checkoutPath}: envoy is not read from a checkout's envoy.json; put it in ${filePath}` : null,
33771
+ askgateError: Object.hasOwn(checkoutFile.settings, "askgate") ? `askgate in ${checkoutPath} is not read; set it in ${filePath}` : null
33772
+ };
33549
33773
  }
33550
- async getArtifactReferences(id) {
33551
- return this.#json("GET", ["api", "v1", "artifacts", id, "references"]);
33774
+ const oldCheckout = path.resolve(options.cwd, ".opencode", "envoy.json");
33775
+ const warnings = oldCheckout !== resolvedChosen && !existsSync(checkoutPath) && existsSync(oldCheckout) ? [
33776
+ moveNotice(oldCheckout, checkoutPath, `mkdir -p ${path.dirname(checkoutPath)} && mv ${oldCheckout} ${checkoutPath}`, deviceOf)
33777
+ ] : [];
33778
+ const unreadOldUserFile = chosen.kind === "absent" ? oldUserFileNotice(filePath, env, deviceOf) : undefined;
33779
+ return {
33780
+ kind: "read",
33781
+ path: filePath,
33782
+ dispatch: own.dispatch ?? {},
33783
+ envoy: own.envoy ?? {},
33784
+ checkout,
33785
+ missing: chosen.kind === "absent" ? {
33786
+ link: chosen.link,
33787
+ ...unreadOldUserFile === undefined ? {} : { oldUserFileNotice: unreadOldUserFile }
33788
+ } : null,
33789
+ warnings
33790
+ };
33791
+ }
33792
+ function askgateSetting(filePath) {
33793
+ const stayOn = (reason) => ({
33794
+ enabled: true,
33795
+ error: `${reason}; AskGate stays on`
33796
+ });
33797
+ let raw;
33798
+ try {
33799
+ raw = readFileSync3(filePath, "utf-8");
33800
+ } catch (error) {
33801
+ if (hasErrnoCode(error, "ENOENT") || hasErrnoCode(error, "ENOTDIR")) {
33802
+ return { enabled: true, error: null };
33803
+ }
33804
+ return stayOn(`${filePath}: could not be read (${messageFor(error)}); askgate.enabled is not read`);
33552
33805
  }
33553
- async getAsk(id) {
33554
- return this.#json("GET", ["api", "v1", "asks", id]);
33806
+ let parsedJson;
33807
+ try {
33808
+ parsedJson = JSON.parse(raw);
33809
+ } catch {
33810
+ const position = jsonErrorPosition(raw);
33811
+ const at = position === undefined ? "" : ` at ${position}`;
33812
+ return stayOn(`${filePath}: invalid JSON${at}; askgate.enabled is not read`);
33555
33813
  }
33556
- async followAsk(id, sessionId, actor) {
33557
- await this.#json("PUT", ["api", "v1", "asks", id, "followers", sessionId], { actor });
33814
+ if (typeof parsedJson !== "object" || parsedJson === null || !("askgate" in parsedJson)) {
33815
+ return { enabled: true, error: null };
33558
33816
  }
33559
- async unfollowAsk(id, sessionId, actor) {
33560
- await this.#json("DELETE", ["api", "v1", "asks", id, "followers", sessionId], { actor });
33817
+ const parsed = object({ askgate: AskgateSectionSchema }).safeParse(parsedJson);
33818
+ if (!parsed.success) {
33819
+ const unknownKey = parsed.error.issues[0]?.code === "unrecognized_keys";
33820
+ return stayOn(unknownKey ? `${describeSchemaIssue(filePath, parsed.error)}; the one askgate key is askgate.enabled, true or false` : `${filePath}: askgate.enabled must be true or false`);
33561
33821
  }
33562
- async getComment(id) {
33563
- return this.#json("GET", ["api", "v1", "comments", id]);
33822
+ return { enabled: parsed.data.askgate.enabled ?? true, error: null };
33823
+ }
33824
+
33825
+ // ../envoy-client/src/bearer.ts
33826
+ function bearerSource(env, section, written) {
33827
+ const pointer = nonEmpty(env[`${section}_TOKEN_FILE`]);
33828
+ if (pointer !== undefined) {
33829
+ return { kind: "variable", token: readSecretFile(`${section}_TOKEN_FILE`, pointer) };
33564
33830
  }
33565
- async resolveComment(id, actor) {
33566
- return this.#json("POST", ["api", "v1", "comments", id, "resolve"], { actor });
33831
+ const plain = nonEmpty(env[`${section}_TOKEN`]);
33832
+ if (plain !== undefined) {
33833
+ if (!sendable(plain)) {
33834
+ throw new Error(`${section}_TOKEN holds whitespace or a control character`);
33835
+ }
33836
+ return { kind: "variable", token: plain };
33567
33837
  }
33568
- async getComments(issue) {
33569
- return this.#json("GET", ["api", "v1", "issues", await this.#resolveIssue(issue), "comments"]);
33838
+ const bearer = written();
33839
+ return bearer === undefined ? { kind: "none" } : { kind: "file", ...bearer };
33840
+ }
33841
+ function fileBearer(bearer, url, section, env) {
33842
+ const named = httpUrl2(url)?.origin;
33843
+ const paired = httpUrl2(bearer.server)?.origin;
33844
+ if (named !== paired) {
33845
+ throw new Error(`${section}_URL names ${named}, but ${bearer.path}'s ${bearer.field} is for ${paired}; set ${section}_TOKEN or ${section}_TOKEN_FILE for it`);
33570
33846
  }
33571
- async getIssueReferences(issue) {
33572
- return this.#json("GET", [
33573
- "api",
33574
- "v1",
33575
- "issues",
33576
- await this.#resolveIssue(issue),
33577
- "references"
33578
- ]);
33847
+ if (bearer.checkout && bearer.token.startsWith("!")) {
33848
+ throw new Error(`${bearer.path}: ${bearer.field} is a command, which a checkout's envoy.json cannot run`);
33579
33849
  }
33580
- async getReferences(query) {
33581
- return this.#json("GET", ["api", "v1", "references"], undefined, {
33582
- ..."to" in query ? { to: query.to } : { from: query.from },
33583
- ...query.kind === undefined || query.kind.length === 0 ? {} : { kind: query.kind.join(",") },
33584
- ...query.since === undefined ? {} : { since: query.since }
33585
- });
33850
+ if (bearer.token === "") {
33851
+ throw new Error(`${bearer.field} in ${bearer.path} must be a non-empty bearer token`);
33586
33852
  }
33587
- async#resolveIssue(issueReference) {
33588
- if (!issueReference.includes("#"))
33589
- return issueReference;
33590
- let resolved = this.#resolvedIssues.get(issueReference);
33591
- if (!resolved) {
33592
- resolved = this.#json("GET", ["api", "v1", "issues", "resolve"], undefined, {
33593
- ref: issueReference
33594
- }).then((resolution) => resolution.key);
33595
- this.#resolvedIssues.set(issueReference, resolved);
33596
- }
33597
- try {
33598
- return await resolved;
33599
- } catch (error) {
33600
- this.#resolvedIssues.delete(issueReference);
33601
- throw error;
33602
- }
33853
+ return fileValue(bearer.token, bearer.field, bearer.path, env);
33854
+ }
33855
+
33856
+ // ../envoy-client/src/dispatch-config.ts
33857
+ var DEFAULT_SERVER_URL = "http://localhost:8766";
33858
+ function checkoutPair(checkout, serverUrl) {
33859
+ const { token } = checkout.dispatch;
33860
+ if (token === undefined) {
33861
+ throw new Error(`${checkout.path}: dispatch.serverUrl requires dispatch.token in the same file`);
33603
33862
  }
33604
- async#json(method, path, body, query) {
33605
- return (await this.#jsonAnswer(method, path, body, query)).payload;
33863
+ return {
33864
+ kind: "file",
33865
+ token,
33866
+ field: "dispatch.token",
33867
+ path: checkout.path,
33868
+ server: serverUrl,
33869
+ checkout: true
33870
+ };
33871
+ }
33872
+ function writtenToken(config, checkout) {
33873
+ if (checkout?.dispatch.token !== undefined) {
33874
+ throw new Error(`${checkout.path}: dispatch.token requires dispatch.serverUrl in the same file`);
33606
33875
  }
33607
- async#jsonAnswer(method, path, body, query) {
33608
- const headers = {
33609
- Accept: "application/json",
33610
- Authorization: `Bearer ${this.token}`
33611
- };
33612
- if (body !== undefined)
33613
- headers["Content-Type"] = "application/json";
33614
- const url = this.#url(path, query);
33615
- const response = await this.fetchImpl(url, {
33616
- method,
33617
- headers,
33618
- signal: this.#signal,
33619
- ...body === undefined ? {} : { body: JSON.stringify(body) }
33620
- });
33621
- return { status: response.status, payload: await this.#response(method, url, response) };
33876
+ const own = config.dispatch;
33877
+ if (own.token === undefined)
33878
+ return;
33879
+ const server = own.serverUrl ?? DEFAULT_SERVER_URL;
33880
+ return {
33881
+ token: own.token,
33882
+ field: "dispatch.token",
33883
+ path: config.path,
33884
+ server,
33885
+ checkout: false
33886
+ };
33887
+ }
33888
+ function dispatchSettings(env, config) {
33889
+ if (config.kind === "failed")
33890
+ return offWithError(config.error);
33891
+ const explicitUrl = nonEmpty(env.DISPATCH_URL);
33892
+ const checkoutFile = explicitUrl === undefined ? config.checkout : null;
33893
+ if (checkoutFile?.kind === "invalid")
33894
+ return offWithError(checkoutFile.error);
33895
+ const checkout = checkoutFile?.kind === "valid" ? checkoutFile : null;
33896
+ const own = config.dispatch;
33897
+ if (own.enabled === false) {
33898
+ return offWithNotice(`${config.path} sets dispatch.enabled to false: Dispatch is off`);
33622
33899
  }
33623
- async#upload(path, input) {
33624
- if ("content" in input)
33625
- return this.#json("POST", path, input);
33626
- const form = new FormData;
33627
- form.set("name", input.name);
33628
- if (input.summary !== undefined)
33629
- form.set("summary", input.summary);
33630
- if (input.actor !== undefined)
33631
- form.set("actor", JSON.stringify(input.actor));
33632
- form.set("file", input.file, input.name);
33633
- return this.#form("POST", path, form);
33900
+ if (checkout?.dispatch.enabled === false) {
33901
+ return offWithNotice(`${checkout.path} sets dispatch.enabled to false: Dispatch is off`);
33634
33902
  }
33635
- async#form(method, path, body) {
33636
- const url = this.#url(path);
33637
- const response = await this.fetchImpl(url, {
33638
- method,
33639
- headers: { Accept: "application/json", Authorization: `Bearer ${this.token}` },
33640
- body,
33641
- signal: this.#signal
33642
- });
33643
- return this.#response(method, url, response);
33903
+ const checkoutServer = checkout?.dispatch.serverUrl;
33904
+ const addressed = explicitUrl !== undefined || checkoutServer !== undefined || own.serverUrl !== undefined || own.enabled === true;
33905
+ if (!addressed) {
33906
+ return offWithNotice(config.missing === null ? `${config.path} names no Dispatch server, and DISPATCH_URL is not set: Dispatch is off` : missingConfigNotice(config.path, config.missing, "Dispatch is off"));
33644
33907
  }
33645
- #url(path, query) {
33646
- const url = new URL(`${path.map((segment) => encodeURIComponent(segment)).join("/")}`, `${this.#baseUrl}/`);
33647
- if (query) {
33648
- for (const [name, value] of Object.entries(query)) {
33649
- if (typeof value === "string" || typeof value === "number") {
33650
- url.searchParams.set(name, String(value));
33651
- } else if (Array.isArray(value)) {
33652
- for (const item of value)
33653
- url.searchParams.append(name, String(item));
33654
- }
33655
- }
33656
- }
33657
- return url.toString();
33908
+ if (explicitUrl !== undefined && httpUrl2(explicitUrl) === undefined) {
33909
+ return offWithError("DISPATCH_URL must be an http or https URL");
33658
33910
  }
33659
- async#response(method, url, response) {
33660
- const text = await response.text();
33661
- let payload = text;
33662
- if (text && isJson(response)) {
33663
- try {
33664
- payload = JSON.parse(text);
33665
- } catch {
33666
- payload = text;
33667
- }
33911
+ try {
33912
+ const source = checkout !== null && checkoutServer !== undefined ? checkoutPair(checkout, checkoutServer) : bearerSource(env, "DISPATCH", () => writtenToken(config, checkout));
33913
+ if (source.kind === "none") {
33914
+ return offWithError(explicitUrl === undefined ? `${config.path}: dispatch is enabled and no token is: set dispatch.token, or DISPATCH_TOKEN or DISPATCH_TOKEN_FILE` : `DISPATCH_URL is set and no token is: set DISPATCH_TOKEN or DISPATCH_TOKEN_FILE, or dispatch.token in ${config.path}`);
33668
33915
  }
33669
- if (!response.ok) {
33670
- const error = asErrorShape(payload);
33671
- if (typeof error.error === "string") {
33672
- throw new DispatchServiceError(error.code ?? `HTTP_${response.status}`, response.status, error.error, error.candidates, error.current, error.mismatches);
33673
- }
33674
- const quoted = excerpt(text, this.token);
33675
- let body;
33676
- if (quoted !== "") {
33677
- body = `a body that is not Dispatch's error JSON (${JSON.stringify(quoted)})`;
33678
- } else if (text === "") {
33679
- body = "an empty body";
33680
- } else {
33681
- const within = text.length > EXCERPT_SCAN_LIMIT ? ` in its first ${EXCERPT_SCAN_LIMIT / 1024} KiB` : "";
33682
- const size = Buffer.byteLength(text).toLocaleString("en-US");
33683
- body = `a body of ${size} bytes and no readable text${within}`;
33684
- }
33685
- const reasonPhrase = excerpt(response.statusText, this.token);
33686
- const reason = reasonPhrase === "" ? "" : ` ${reasonPhrase}`;
33687
- throw new DispatchGatewayError(response.status, `${method} ${url} answered ${response.status}${reason} with ${body}, ${GATEWAY_PAGE}`, gatewayAdvice(method, response.status));
33916
+ const url = (explicitUrl ?? (source.kind === "file" ? source.server : own.serverUrl ?? DEFAULT_SERVER_URL)).replace(/\/+$/, "");
33917
+ const token = source.kind === "variable" ? source.token : fileBearer(source, url, "DISPATCH", env);
33918
+ const publicUrl = nonEmpty(env.DISPATCH_PUBLIC_URL);
33919
+ const publicParsed = publicUrl === undefined ? undefined : httpUrl2(publicUrl);
33920
+ if (publicUrl !== undefined && (publicParsed === undefined || publicParsed.port === "0")) {
33921
+ return offWithError("DISPATCH_PUBLIC_URL must be an http or https URL");
33688
33922
  }
33689
- return payload;
33923
+ return {
33924
+ enabled: true,
33925
+ url,
33926
+ token,
33927
+ ...publicUrl === undefined ? {} : { publicUrl: publicUrl.replace(/\/+$/, "") }
33928
+ };
33929
+ } catch (error) {
33930
+ return offWithError(messageFor(error));
33931
+ }
33932
+ }
33933
+ function activeDispatchSettings(resolution) {
33934
+ if (resolution.enabled)
33935
+ return resolution;
33936
+ if (resolution.error !== null)
33937
+ throw new Error(`dispatch config: ${resolution.error}`);
33938
+ return null;
33939
+ }
33940
+
33941
+ // ../envoy-client/src/dispatch-first.ts
33942
+ import { readFileSync as readFileSync4 } from "fs";
33943
+ import { join as join3 } from "path";
33944
+ var DISPATCH_FIRST_MARKER = "<dispatch-first-skill>";
33945
+ function dispatchFirstSkillFile(skillsDirectory) {
33946
+ return join3(skillsDirectory, "dispatch-first", "SKILL.md");
33947
+ }
33948
+ function readDispatchFirstContext(skillFile) {
33949
+ let skill;
33950
+ try {
33951
+ skill = readFileSync4(skillFile, "utf8");
33952
+ } catch (error) {
33953
+ throw new Error(`the dispatch-first skill ${skillFile} could not be read: ${messageFor(error)}`);
33690
33954
  }
33955
+ const body = skill.replace(/^---\n[\s\S]*?\n---\n/, "").trim();
33956
+ return [
33957
+ DISPATCH_FIRST_MARKER,
33958
+ "This session has Dispatch, so the dispatch-first skill is loaded for it. Follow it.",
33959
+ "",
33960
+ body,
33961
+ "</dispatch-first-skill>"
33962
+ ].join(`
33963
+ `);
33691
33964
  }
33692
33965
 
33693
33966
  // ../envoy-client/src/tool-input-errors.ts
@@ -35793,11 +36066,15 @@ function parseEnvoyToolArguments(operation, parameters) {
35793
36066
 
35794
36067
  // ../pi-shared/src/interface.ts
35795
36068
  import { logger } from "@oh-my-pi/pi-utils";
36069
+
36070
+ // ../pi-shared/src/envoy-notice.ts
36071
+ var LOCAL_ENVOY_NOTICE = { localNotice: true };
36072
+
36073
+ // ../pi-shared/src/interface.ts
35796
36074
  var ENVOY_PLUGIN_INTERFACE_VERSION = 5;
35797
36075
  var ENVOY_PLUGIN_INTERFACE_KEY = Symbol.for("legion.pi-shared.envoy-plugin-interface");
35798
36076
  var LEGION_PLUGIN_LOADED_KEY = Symbol.for("legion.pi-legion.loaded");
35799
36077
  var LEGACY_LEGION_LOADED_KEY = Symbol.for("legion.pi-envoy.legion-loaded");
35800
- var LOCAL_ENVOY_NOTICE = { localNotice: true };
35801
36078
  var store = globalThis;
35802
36079
  var mismatchWarned = false;
35803
36080
  function envoyPluginInterface() {
@@ -36057,7 +36334,7 @@ var import_nats2 = __toESM(require_mod4(), 1);
36057
36334
 
36058
36335
  // package.json
36059
36336
  var name = "@sjawhar/pi-envoy";
36060
- var version2 = "11.9.0";
36337
+ var version2 = "13.0.0";
36061
36338
 
36062
36339
  // src/agent-stream.ts
36063
36340
  var encoder2 = new TextEncoder;