@sjawhar/claude-envoy 6.5.0 → 6.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/dispatch.js CHANGED
@@ -980,7 +980,7 @@ __export(exports_coerce, {
980
980
  });
981
981
 
982
982
  // ../envoy-client/src/dispatch-cli.ts
983
- import { closeSync as closeSync4, constants as constants4, fstatSync as fstatSync3, openSync as openSync4, readFileSync as readFileSync7 } from "fs";
983
+ import { closeSync as closeSync4, constants as constants5, fstatSync as fstatSync3, openSync as openSync4, readFileSync as readFileSync7 } from "fs";
984
984
 
985
985
  // ../envoy-client/src/askgate-marker.ts
986
986
  import { createHash, randomBytes } from "crypto";
@@ -1231,9 +1231,6 @@ function reachedNothing(error) {
1231
1231
  }
1232
1232
 
1233
1233
  class LoggableError extends Error {
1234
- constructor(message) {
1235
- super(message);
1236
- }
1237
1234
  }
1238
1235
  var SERVER_REFUSALS = [
1239
1236
  "Authorization Violation",
@@ -14926,21 +14923,22 @@ var ISSUE_UPDATE_OPTIONS_RULE = "include_children, unlink_children and include_p
14926
14923
  var ISSUE_UPDATE_RULE = `${ISSUE_UPDATE_FIELDS_RULE} ${ISSUE_UPDATE_DONE_RULE}; ${ISSUE_UPDATE_REASON_RULE}; ${ISSUE_UPDATE_LABELS_RULE}. ${ISSUE_UPDATE_OPTIONS_RULE}`;
14927
14924
  function issueStatusOptionsProblem(input) {
14928
14925
  const options = issueStatusOptionsOf(input);
14926
+ const optionInput = input;
14929
14927
  if (options.length === 0)
14930
14928
  return;
14931
14929
  const named = options.join(", ").replace(/, ([^,]*)$/, " and $1");
14932
14930
  const others = ISSUE_UPDATE_PATCH_FIELDS.filter((field) => input[field] !== undefined);
14933
14931
  return brokenParts([
14934
14932
  [
14935
- !(input["include_children"] === true && input["unlink_children"] === true),
14933
+ !(optionInput.include_children === true && optionInput.unlink_children === true),
14936
14934
  "include_children does not go with unlink_children. The open children move with the issue or leave it, so name one of the two."
14937
14935
  ],
14938
14936
  [
14939
- !(input["include_children"] === true && input["status"] === "done"),
14937
+ !(optionInput.include_children === true && optionInput.status === "done"),
14940
14938
  "include_children does not go with status done. Only a person who is signed in at a browser can close the open issues under an issue together with it, and this call presents a token. That person does it on the issue's page in Dispatch: Close issue, then Move them with it."
14941
14939
  ],
14942
14940
  [
14943
- typeof input["status"] === "string",
14941
+ typeof optionInput.status === "string",
14944
14942
  `status is required with ${named}. Add status, or drop ${named}.`
14945
14943
  ],
14946
14944
  [
@@ -15093,8 +15091,8 @@ var RESULT_SHAPE_RULE = `${RESULT_RETRACT_RULE} A call with retract takes reason
15093
15091
  function resultProblem(value) {
15094
15092
  const input = value;
15095
15093
  const carried = RESULT_RECORD_FIELDS.filter((field) => input[field] !== undefined);
15096
- if (typeof input["retract"] === "string") {
15097
- const reason = input["reason"];
15094
+ if (typeof input.retract === "string") {
15095
+ const reason = input.reason;
15098
15096
  if (typeof reason !== "string" || reason.trim() === "") {
15099
15097
  return "retract needs reason, the words that say why the result is wrong.";
15100
15098
  }
@@ -15103,7 +15101,7 @@ function resultProblem(value) {
15103
15101
  }
15104
15102
  return;
15105
15103
  }
15106
- if (input["reason"] !== undefined) {
15104
+ if (input.reason !== undefined) {
15107
15105
  return "reason goes with retract, and this call carries no retract. Name the result to retract, or drop reason.";
15108
15106
  }
15109
15107
  const missing = RESULT_REQUIRED_FIELDS.filter((field) => input[field] === undefined);
@@ -15714,7 +15712,7 @@ var dispatchToolSpecs = [
15714
15712
  {
15715
15713
  name: "dispatch_project_update",
15716
15714
  example: { project: "CORE", proven_sessions: "on" },
15717
- description: "Turn a project's proven-sessions setting on or off. With it on, an architect's write of an " + "issue's spec or Verification document passes only on a credential that proves the " + "architect's session. A role-holder publication then passes only on a credential that " + "proves legion-daemon:<project>. on sends PUT /api/v1/projects/{key}/proven-sessions, which " + "any credential that may write the project's issues may send. off sends DELETE on the same " + "path, which needs the person scope: a credential without it is refused with 403 " + "OAUTH_SCOPE_REQUIRED, and the shared token and a pod's token hold none. A token scoped to " + "another project is refused with 403 PROJECT_SCOPE. Only the project's roll-out issue " + "turns it on, once the project's daemon and pods write with their own tokens. Turned on " + "before that, it stops every architect write and every role-holder publication on the " + "shared token, until a person turns it off. The answer names the project and the setting " + "as Dispatch stored it.",
15715
+ description: "Turn a project's proven-sessions setting on or off. With it on, an architect's write of an " + "issue's spec or Verification document passes only on a credential that proves the " + "architect's session. A role-holder publication then passes only on a credential that " + "proves legion-daemon:<project>, or legion-daemon:<P> of another project's daemon on a " + "broker token that names P. on sends PUT /api/v1/projects/{key}/proven-sessions, which " + "any credential that may write the project's issues may send. off sends DELETE on the same " + "path, which needs the person scope: a credential without it is refused with 403 " + "OAUTH_SCOPE_REQUIRED, and the shared token and a pod's token hold none. A token scoped to " + "another project turns the setting on, as the shared token does, and off only with the " + "person scope. A token scoped to one project gets 403 PROJECT_SCOPE for a project that " + "does not exist and for a private project that it does not name. Only the project's " + "roll-out issue turns it on, once the project's daemon and pods write with their own " + "tokens. Turned on before that, it stops every architect write and every role-holder " + "publication on the shared token, until a person turns it off. The answer names the " + "project and the setting as Dispatch stored it.",
15718
15716
  arguments: (z) => ({
15719
15717
  project: z.string().describe("Project key whose setting to change, such as CORE."),
15720
15718
  proven_sessions: z.enum(["on", "off"]).describe("on turns the setting on; off turns it off and needs the person scope.")
@@ -15767,7 +15765,7 @@ var dispatchToolSpecs = [
15767
15765
  {
15768
15766
  name: "dispatch_whoami",
15769
15767
  example: {},
15770
- description: "Who Dispatch takes this session for: {session, owner, service, project, project_scope}. session is the session Dispatch records your writes as. It is the session your credential proved, and the tool says so when that is not the session you run in. owner is the lowercase email of the person you act for, and is the first choice of assignee for issues you create. owner is null under the shared token and under a broker token that names a service and no person. With a null owner, a create with no assignee falls back to the parent's assignee, when the parent is in the issue's own project, and then to the project's default assignee, which every project names, so every issue you create has an assignee. A question on an issue reaches the person it was handed to, else the issue's assignee, else the project's default assignee. service is the subject of the verified service-account token that authenticated you, or the service a broker token naming no person names: a job's identity as its job entry lists it, the Kubernetes account an exchange entry lists, or the fleet of a machine nobody has signed in on; else null. project_scope is a broker token's project scope, and null for every other credential. A job's broker token has the project scope named or public, holds no OAuth scope and writes as its service: a route that needs an OAuth scope refuses it with 403 OAUTH_SCOPE_REQUIRED before Dispatch's project check runs. named may write its one project, and that check judges its write to another project as it judges a person's named token's for the same project: 403 PROJECT_SCOPE until dispatch://INFRA-4799 changes that answer for both. public names no one project, so it may write wherever a token that names no project may. An exchange entry's broker token that names its account has the project scope named and no project, and writes as that account wherever a token that names no project may. A machine's broker token that names a service has the project scope person; it may read and is refused every write with SIGN_IN_REQUIRED, which names the command a person signs in on that machine with. project is the one project key your credential may write, or null when it names none.",
15768
+ description: "Who Dispatch takes this session for: {session, owner, service, project, project_scope}. session is the session Dispatch records your writes as. It is the session your credential proved, and the tool says so when that is not the session you run in. owner is the lowercase email of the person you act for, and is the first choice of assignee for issues you create. owner is null under the shared token and under a broker token that names a service and no person. With a null owner, a create with no assignee falls back to the parent's assignee, when the parent is in the issue's own project, and then to the project's default assignee, which every project names, so every issue you create has an assignee. A question on an issue reaches the person it was handed to, else the issue's assignee, else the project's default assignee. service is the subject of the verified service-account token that authenticated you, or the service a broker token naming no person names: a job's identity as its job entry lists it, the Kubernetes account an exchange entry lists, or the fleet of a machine nobody has signed in on; else null. project_scope is a broker token's project scope, and null for every other credential. A job's broker token has the project scope named or public, holds no OAuth scope and writes as its service: a route that needs an OAuth scope refuses it with 403 OAUTH_SCOPE_REQUIRED before Dispatch's project check runs. named names one project, and that check judges its writes as it judges a person's named token's for the same project: it refuses a write that belongs to the deployment, such as a project create, with 403 PROJECT_SCOPE_DEPLOYMENT. public names no one project, so it may write wherever a token that names no project may. An exchange entry's broker token that names its account has the project scope named and no project, and writes as that account wherever a token that names no project may. A machine's broker token that names a service has the project scope person; it may read and is refused every write with SIGN_IN_REQUIRED, which names the command a person signs in on that machine with. project is the project your credential's token names, or null when it names none. A token that names a project also writes other projects' objects, as a credential that names none does. The one exception is a private project that the token does not name.",
15771
15769
  arguments: () => ({}),
15772
15770
  strict: true
15773
15771
  },
@@ -15781,7 +15779,7 @@ var dispatchToolSpecs = [
15781
15779
  {
15782
15780
  name: "dispatch_api",
15783
15781
  example: { path: "/api/v1/issues/DSP-1/events?limit=200" },
15784
- description: "Send one request of a route of Dispatch's HTTP API under /api/v1, with this session's own credential, and print the answer's body: Dispatch's JSON, indented, for jq to read; any other body of a 2xx, such as a file version's bytes or a document version's Markdown, as it came. It sends a GET of path unless method names another: path is a route beginning /api/v1, with its query after ?; dispatch api --path /api/v1 lists every route. With method it sends POST, PUT, PATCH or DELETE instead, and body, when given, as the request's JSON body (Content-Type: application/json), read from a file with --body-file <file> or from stdin with --body-file -; a body goes only with a method. A write that a named dispatch command makes goes through that command (dispatch --help lists them): dispatch api is for a route no command sends. In a session whose AskGate reviews Dispatch writes it sends GET alone, and refuses each method, naming the dispatch command that makes that write, and exits 1. It sends the request once, and once more only after Dispatch answers that the token it presented is not live (Dispatch then authenticated nothing, so nothing ran), with no redirect followed and no Idempotency-Key. On a 2xx answer it exits 0 and prints Dispatch's JSON as above, and any other body unchanged, with nothing added: an answer with Content-Disposition: attachment (a file version, a ?download=true read) is stored content, printed byte for byte whatever its type, JSON included. A 2xx whose body holds a credential the command presented (its token or its request's DPoP proof) is not printed: it exits 1 with CREDENTIAL_ECHOED, naming the status and saying a write may have been made. Any other answer exits 1 with its code: when Dispatch refuses the request, the command prints Dispatch's error with its code and, where Dispatch gives one, its hint; an answer that is neither a 2xx nor Dispatch's JSON, such as a proxy's page, is named by its status. A usage error, such as a path outside /api/v1 or a body with no method, exits 2. Where no host runs the command, as in a GitHub Actions job, it reads Dispatch from the environment alone, and a broker trade names the session of DISPATCH_SESSION_ID, else of AGENT_SECRETS_SESSION. Under Claude Code, a JSON answer longer than the output limit is written to a file the output names; a body printed as it came is written whole.",
15782
+ description: "Send one request of a route of Dispatch's HTTP API under /api/v1, with this session's own credential, and print the answer's body: Dispatch's JSON, indented, for jq to read; any other body of a 2xx, such as a file version's bytes or a document version's Markdown, as it came. It sends a GET of path unless method names another: path is a route beginning /api/v1, with its query after ?; dispatch api --path /api/v1 lists every route. With method it sends POST, PUT, PATCH or DELETE instead, and body, when given, as the request's JSON body (Content-Type: application/json), read from a file with --body-file <file> or from stdin with --body-file -; a body goes only with a method. A write that a named dispatch command makes goes through that command (dispatch --help lists them), or, for an issue comment POST that carries an Idempotency-Key, through dispatch proxy: dispatch api is for a route no command sends. In a session whose AskGate reviews Dispatch writes it sends GET alone, and refuses each method, naming the dispatch command that makes that write, and exits 1. It sends the request once, and once more only after Dispatch answers that the token it presented is not live (Dispatch then authenticated nothing, so nothing ran), with no redirect followed and no Idempotency-Key. On a 2xx answer it exits 0 and prints Dispatch's JSON as above, and any other body unchanged, with nothing added: an answer with Content-Disposition: attachment (a file version, a ?download=true read) is stored content, printed byte for byte whatever its type, JSON included. A 2xx whose body holds a credential the command presented (its token or its request's DPoP proof) is not printed: it exits 1 with CREDENTIAL_ECHOED, naming the status and saying a write may have been made. Any other answer exits 1 with its code: when Dispatch refuses the request, the command prints Dispatch's error with its code and, where Dispatch gives one, its hint; an answer that is neither a 2xx nor Dispatch's JSON, such as a proxy's page, is named by its status. A usage error, such as a path outside /api/v1 or a body with no method, exits 2. Where no host runs the command, as in a GitHub Actions job, it reads Dispatch from the environment alone, and a broker trade names the session of DISPATCH_SESSION_ID, else of AGENT_SECRETS_SESSION. Under Claude Code, a JSON answer longer than the output limit is written to a file the output names; a body printed as it came is written whole.",
15785
15783
  arguments: (z) => ({
15786
15784
  path: z.string({ min: 1 }).describe('The route, beginning /api/v1, with its query after ?, such as /api/v1/issues/ACME-12/events?limit=200. No scheme or host, no . or .. segment, and no ", <, >, ^, `, { or } before the query: percent-encode them.'),
15787
15785
  method: z.enum(DISPATCH_API_METHODS).describe("The method sent in place of GET: POST, PUT, PATCH or DELETE. Omit it to send a GET.").optional(),
@@ -16572,6 +16570,52 @@ var DispatchTargetedDeliverySchema = union([
16572
16570
  DispatchTargetedCommentDeliverySchema,
16573
16571
  DispatchTargetedMessageDeliverySchema
16574
16572
  ]);
16573
+ function isCommentTargetedDelivery(delivery) {
16574
+ return "comment_id" in delivery;
16575
+ }
16576
+ var DispatchTargetedFrameSchema = object({
16577
+ event: DispatchEventSchema,
16578
+ delivery: DispatchTargetedDeliverySchema
16579
+ }).superRefine(({ event, delivery }, context) => {
16580
+ if (event.type === "message.created" && !isCommentTargetedDelivery(delivery) && DispatchTargetedMessagePayloadSchema.safeParse(event.payload).success) {
16581
+ return;
16582
+ }
16583
+ if (event.type === "comment.created" && isCommentTargetedDelivery(delivery) && DispatchTargetedCommentPayloadSchema.safeParse(event.payload).success) {
16584
+ return;
16585
+ }
16586
+ context.addIssue({
16587
+ code: "custom",
16588
+ message: event.type === "comment.created" ? "targeted delivery requires a complete comment.created event" : "targeted delivery requires a complete message.created event"
16589
+ });
16590
+ });
16591
+ var RecoverableDispatchDeliveryFailureSchema = object({
16592
+ event: object({
16593
+ type: _enum2(["message.created", "comment.created"]),
16594
+ issue_key: string2().nullable(),
16595
+ payload: object({ id: string2(), body: string2().optional() }).passthrough()
16596
+ }).passthrough(),
16597
+ delivery: DispatchTargetedDeliverySchema
16598
+ }).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" });
16599
+ function readDispatchPayload(value) {
16600
+ if (typeof value === "object" && value !== null && "delivery" in value) {
16601
+ const targeted = DispatchTargetedFrameSchema.safeParse(value);
16602
+ if (targeted.success) {
16603
+ const { event: wireEvent } = value;
16604
+ return {
16605
+ kind: "event",
16606
+ event: targeted.data.event,
16607
+ wireEvent,
16608
+ delivery: targeted.data.delivery
16609
+ };
16610
+ }
16611
+ const recovered = RecoverableDispatchDeliveryFailureSchema.safeParse(value);
16612
+ if (recovered.success)
16613
+ return { kind: "recovered", failure: recovered.data };
16614
+ return { kind: "raw", targeted: true };
16615
+ }
16616
+ const parsed = DispatchEventSchema.safeParse(value);
16617
+ return parsed.success ? { kind: "event", event: parsed.data, wireEvent: value } : { kind: "raw", targeted: false };
16618
+ }
16575
16619
  // ../contracts/src/dispatch-api-user.ts
16576
16620
  var UserIssueStateSchema = strictObject({
16577
16621
  pinned: boolean2(),
@@ -20689,7 +20733,186 @@ function fileTextBytes(text) {
20689
20733
  return encoder2.encode(text);
20690
20734
  }
20691
20735
 
20736
+ // ../envoy-client/src/dispatch-login-command.ts
20737
+ var LOGIN_COMMAND = "login";
20738
+ var LOGIN_SENTENCE = "Logs this machine in at the secrets broker, once per machine, for a machine with no identity of its own, such as a laptop.";
20739
+ function loginHelp() {
20740
+ return [
20741
+ "Usage: dispatch login --device [--person <address>]",
20742
+ "",
20743
+ `${LOGIN_SENTENCE} It prints a code and the page to type it into; the person the login names approves it there, signed in to Dispatch. The login is then kept in the file AGENT_SECRETS_DEVICE_LOGIN_FILE names (default ~/.config/legion/device-login.json), mode 0600, and every session that sets AGENT_SECRETS_MACHINE_IDENTITY=device-login trades it for its broker token.`,
20744
+ "",
20745
+ "Flags:",
20746
+ " --device",
20747
+ " Log in with the broker's device grant: the only way there is, and required.",
20748
+ " --person <address>",
20749
+ " The person who approves the login, by the address they sign in to Dispatch with; else AGENT_SECRETS_PERSON.",
20750
+ "",
20751
+ "It reads AGENT_SECRETS_URL, the broker, and needs no Dispatch host or session.",
20752
+ "",
20753
+ "It exits 0 once the login is kept; 1 when the broker could not be reached or refused it, the person denied it, its code expired, or the login could not be kept; and 2 on a usage error, before any request.",
20754
+ "",
20755
+ "Example: dispatch login --device --person ada@example.com",
20756
+ ""
20757
+ ].join(`
20758
+ `);
20759
+ }
20760
+
20761
+ // ../envoy-client/src/dispatch-proxy-command.ts
20762
+ import { resolve as resolve2 } from "path";
20763
+ var PROXY_COMMAND = "proxy";
20764
+ var PROXY_SENTENCE = "Runs a command with a proxy on a unix socket that sends the command's Dispatch reads, and its comment POSTs that carry an Idempotency-Key, with this session's broker token.";
20765
+ var SOCKET_PATH_MAX_BYTES = 107;
20766
+ function proxyExitLine(requests, trades, renewed) {
20767
+ return `dispatch proxy: ${requests} requests, ${trades} trades, ${renewed} after BROKER_TOKEN_NOT_ACTIVE`;
20768
+ }
20769
+ function proxyHelp() {
20770
+ return [
20771
+ "Usage: dispatch proxy --socket <path> [--dry-run] -- <command> [<argument>...]",
20772
+ "",
20773
+ PROXY_SENTENCE,
20774
+ "",
20775
+ "The proxy listens on a unix socket at <path> for the whole run of <command>. It sends each",
20776
+ "request it takes to the Dispatch server and the session that a dispatch command resolves in",
20777
+ "the same environment, with this session's broker token and a new DPoP proof. So the tool",
20778
+ "holds no credential and signs nothing. It adds the path of each request to the path of the",
20779
+ "Dispatch URL, and it does not decode the query. The proxy trades for the token once before it",
20780
+ "starts the command, and again only when the token has less than 5 minutes to live, or after",
20781
+ "Dispatch answers 401 BROKER_TOKEN_NOT_ACTIVE. It runs only under DISPATCH_TOKEN_BROKER=1.",
20782
+ "",
20783
+ "What it sends:",
20784
+ " GET /api/... any GET whose path starts with /api/",
20785
+ " POST /api/v1/issues/<key>/comments a comment that carries an Idempotency-Key header",
20786
+ "It sends no other write. A tool reads much and writes little. Where a dispatch command sends a",
20787
+ "write, the write goes through that command, so AskGate reviews it wherever AskGate gates that",
20788
+ "command. The proxy's refusal of the write names that command. Where no other dispatch command",
20789
+ "sends a write under /api/v1, the refusal names dispatch api --method, which sends it outside a",
20790
+ "session whose AskGate reviews Dispatch writes. The comment needs a key so that a resend posts",
20791
+ "it once. The comment POST passes no AskGate review. The proxy is not one of the writes that",
20792
+ "AskGate gates, and the Dispatch server checks no marker. A session that holds a Dispatch token",
20793
+ "can post the same comment with that token already.",
20794
+ "",
20795
+ "It listens on a unix socket only, made with mode 0600, and opens no TCP port. The roles of a",
20796
+ "pod share the pod's network, so a port would let another role act as this one. A socket path",
20797
+ "that exists is refused, so give it a path in a new directory (mktemp -d). A socket that a",
20798
+ "killed proxy left behind refuses the next start.",
20799
+ "",
20800
+ "How a tool calls it: the command runs with DISPATCH_PROXY_SOCKET set to the socket's path.",
20801
+ "The host in a URL is not read. Write the path and the query.",
20802
+ ' curl --unix-socket "$DISPATCH_PROXY_SOCKET" http://dispatch/api/v1/issues',
20803
+ " In Python, an http.client.HTTPConnection whose connect opens an AF_UNIX socket:",
20804
+ " import http.client, os, socket",
20805
+ " class ProxyConnection(http.client.HTTPConnection):",
20806
+ " def connect(self):",
20807
+ " self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)",
20808
+ ' self.sock.connect(os.environ["DISPATCH_PROXY_SOCKET"])',
20809
+ ' connection = ProxyConnection("dispatch")',
20810
+ ' connection.request("GET", "/api/v1/issues?project=DSP")',
20811
+ " answer = connection.getresponse()",
20812
+ " print(answer.status, answer.read())",
20813
+ "",
20814
+ "What it answers: Dispatch's status, headers and body as Dispatch sent them. An answer that",
20815
+ "carries Transfer-Encoding as well as Content-Length is the one exception: it comes back",
20816
+ "without that Content-Length (RFC 9112, section 6.3), with its body chunked. It follows no",
20817
+ "redirect. Its own refusals have a JSON body with a code and an error, and each code starts",
20818
+ "with PROXY_. No code of Dispatch's does. It never answers 403 or 404 of its own.",
20819
+ " 400 PROXY_TARGET_REFUSED a target that names a host (http://... or //...)",
20820
+ " 405 PROXY_METHOD_REFUSED each other method or path, and a comment POST with no",
20821
+ " Idempotency-Key. The error names the dispatch command to",
20822
+ " use, where one exists. For a write under /api/v1 that no",
20823
+ " other dispatch command sends, it names dispatch api",
20824
+ " --method. It also refuses a target that holds a # or a",
20825
+ " control character, and a path with a . or .. segment",
20826
+ " (plain or percent-encoded), a backslash, or %2F or %5C in",
20827
+ " either case: each can reach another route than the one the",
20828
+ " target names.",
20829
+ " 502 PROXY_TRADE_REFUSED the token has ended and the broker refused a new one. The",
20830
+ " error is in the broker's words.",
20831
+ " 502 PROXY_DISPATCH_UNREACHABLE Dispatch did not answer",
20832
+ "",
20833
+ "Flags:",
20834
+ " --socket <path>",
20835
+ " The socket to listen on. Also --socket=<path>. A path over 107 bytes is refused.",
20836
+ " --dry-run",
20837
+ " Checks the arguments and the environment, prints the Dispatch server, the session and",
20838
+ " the socket it would use, and starts nothing.",
20839
+ " --help",
20840
+ " Prints this help.",
20841
+ "Every word after -- is the command's, flags included.",
20842
+ "",
20843
+ "It exits with the command's status. A command that a signal ended is 128 plus the signal's",
20844
+ "number. A command that does not exist is 127, and one that cannot run is 126. It exits 2 when",
20845
+ "it cannot start, and runs no command then. It sends SIGTERM, SIGINT and SIGHUP on to the",
20846
+ "command and serves until the command ends. Then it removes its socket. The last line it",
20847
+ "writes on standard error is:",
20848
+ " dispatch proxy: <n> requests, <m> trades, <r> after BROKER_TOKEN_NOT_ACTIVE",
20849
+ "Here n counts the requests sent to Dispatch, m the trades that gave a token, and r those of",
20850
+ "them that followed a BROKER_TOKEN_NOT_ACTIVE answer.",
20851
+ "",
20852
+ 'Example: dispatch proxy --socket "$(mktemp -d)/d.sock" -- python3 work-cost.py',
20853
+ ""
20854
+ ].join(`
20855
+ `);
20856
+ }
20857
+ function parseProxyArgv(rest, cwd) {
20858
+ const separator = rest.indexOf("--");
20859
+ const own = separator === -1 ? rest : rest.slice(0, separator);
20860
+ if (own.includes("--help"))
20861
+ return { kind: "help" };
20862
+ let socket;
20863
+ let dryRun = false;
20864
+ for (let at = 0;at < own.length; at += 1) {
20865
+ const word = own[at] ?? "";
20866
+ if (word === "--dry-run") {
20867
+ dryRun = true;
20868
+ continue;
20869
+ }
20870
+ if (word !== "--socket" && !word.startsWith("--socket=")) {
20871
+ return {
20872
+ kind: "refused",
20873
+ problem: separator === -1 ? `${JSON.stringify(word)} is no flag of dispatch proxy, and the command goes after --.` : `${JSON.stringify(word)} is no flag of dispatch proxy.`
20874
+ };
20875
+ }
20876
+ if (socket !== undefined)
20877
+ return { kind: "refused", problem: "--socket is given twice." };
20878
+ let value;
20879
+ if (word === "--socket") {
20880
+ at += 1;
20881
+ value = own[at];
20882
+ } else {
20883
+ value = word.slice("--socket=".length);
20884
+ }
20885
+ if (value === undefined || value === "" || value.startsWith("-")) {
20886
+ return { kind: "refused", problem: "--socket takes the path of the socket to listen on." };
20887
+ }
20888
+ socket = value;
20889
+ }
20890
+ if (socket === undefined) {
20891
+ return { kind: "refused", problem: "--socket <path> is missing." };
20892
+ }
20893
+ const command = separator === -1 ? [] : rest.slice(separator + 1);
20894
+ if (command.length === 0) {
20895
+ return {
20896
+ kind: "refused",
20897
+ problem: "No command is given: write it after --, as -- <command> [<argument>...]."
20898
+ };
20899
+ }
20900
+ const path = resolve2(cwd, socket);
20901
+ const bytes = Buffer.byteLength(path);
20902
+ if (bytes > SOCKET_PATH_MAX_BYTES) {
20903
+ return {
20904
+ kind: "refused",
20905
+ problem: `The socket path ${JSON.stringify(path)} is ${bytes} bytes, over the ${SOCKET_PATH_MAX_BYTES} a unix socket path holds. Give a shorter path, such as one in a new directory of mktemp -d.`
20906
+ };
20907
+ }
20908
+ return { kind: "run", socket: path, dryRun, command };
20909
+ }
20910
+
20692
20911
  // ../envoy-client/src/dispatch-command.ts
20912
+ var COMMANDS_OUTSIDE_THE_SPECS = [
20913
+ { name: PROXY_COMMAND, sentence: PROXY_SENTENCE, help: proxyHelp },
20914
+ { name: LOGIN_COMMAND, sentence: LOGIN_SENTENCE, help: loginHelp }
20915
+ ];
20693
20916
  var PREFIXED_FLAGS = [
20694
20917
  {
20695
20918
  tool: "dispatch_comment",
@@ -20961,7 +21184,10 @@ function parseCommand(argv, io) {
20961
21184
  return { kind: "help" };
20962
21185
  const tool = toolForCommand(command);
20963
21186
  if (tool === undefined) {
20964
- const commands = [...toolsByCommand.keys()].join(", ");
21187
+ const commands = [
21188
+ ...toolsByCommand.keys(),
21189
+ ...COMMANDS_OUTSIDE_THE_SPECS.map(({ name }) => name)
21190
+ ].join(", ");
20965
21191
  return {
20966
21192
  kind: "refused",
20967
21193
  problems: [`unknown command ${quoteWord(command)}; the commands are: ${commands}`]
@@ -21238,17 +21464,21 @@ function commandHelp(tool) {
21238
21464
  `);
21239
21465
  }
21240
21466
  function commandsHelp() {
21241
- const width = Math.max(...[...toolsByCommand.keys()].map((command) => command.length));
21467
+ const rows = [
21468
+ ...dispatchToolSpecs.map((spec) => ({
21469
+ name: commandName(spec.name),
21470
+ sentence: /^.*?[.!?](?=\s|$)/s.exec(spec.description)?.[0] ?? spec.description
21471
+ })),
21472
+ ...COMMANDS_OUTSIDE_THE_SPECS
21473
+ ];
21474
+ const width = Math.max(...rows.map(({ name }) => name.length));
21242
21475
  return [
21243
21476
  "Usage: dispatch <command> [flags]",
21244
- ...dispatchToolSpecs.map((spec) => {
21245
- const sentence = /^.*?[.!?](?=\s|$)/s.exec(spec.description)?.[0] ?? spec.description;
21246
- return ` ${commandName(spec.name).padEnd(width)} ${sentence}`;
21247
- }),
21477
+ ...rows.map(({ name, sentence }) => ` ${name.padEnd(width)} ${sentence}`),
21248
21478
  "",
21249
- "Run dispatch <command> --help for its flags and an example. --dry-run checks a command's arguments as the call would and prints them as given. It stores nothing. A command whose dry run asks Dispatch something past that check (dispatch artifact: how Dispatch would store its text; dispatch result: the pull-request body line the record would print) says so in its --help.",
21479
+ "Run dispatch <command> --help for its flags and an example. Every command but dispatch login takes --dry-run, which checks its arguments as the call would and prints them as given. It stores nothing. A command whose dry run asks Dispatch something past that check (dispatch artifact: how Dispatch would store its text; dispatch result: the pull-request body line the record would print) says so in its --help. dispatch proxy's dry run also checks its environment and prints the Dispatch server, the session and the socket it would use, and starts nothing.",
21250
21480
  "",
21251
- "dispatch login --device logs a machine with no identity of its own, such as a laptop, in at the secrets broker, once per machine; it is no Dispatch call, and needs no host or session (dispatch login --help).",
21481
+ "dispatch login --device is no Dispatch call: it needs no host or session.",
21252
21482
  ""
21253
21483
  ].join(`
21254
21484
  `);
@@ -26029,12 +26259,10 @@ var WRITE_ROUTES = [
26029
26259
  commands: ["architecture-sync"]
26030
26260
  }
26031
26261
  ];
26262
+ var WRITE_ROUTE_SEGMENTS = WRITE_ROUTES.map((row) => ({ row, segments: row.pattern.split("/") }));
26032
26263
  function writeRoute(method, path) {
26033
26264
  const segments = path.split("/");
26034
- return WRITE_ROUTES.find((row) => {
26035
- const pattern = row.pattern.split("/");
26036
- return row.method === method && pattern.length === segments.length && pattern.every((part, at) => part.startsWith("{") ? segments[at] !== "" : part === segments[at]);
26037
- });
26265
+ return WRITE_ROUTE_SEGMENTS.find((route) => route.row.method === method && route.segments.length === segments.length && route.segments.every((part, at) => part.startsWith("{") ? segments[at] !== "" : part === segments[at]))?.row;
26038
26266
  }
26039
26267
 
26040
26268
  class ApiGateRefusal extends Error {
@@ -26114,7 +26342,7 @@ function refusalWithCode(error, ...clauses) {
26114
26342
  const told = joined !== "" && /[.!?]$/.test(error.message) ? `${error.message} ${suffix.charAt(0).toUpperCase()}${suffix.slice(1)}` : `${error.message}${joined}`;
26115
26343
  return new DispatchServiceError(error.code, error.status, `${error.code}: ${told}`, error);
26116
26344
  }
26117
- function parentStatusConflictLines(error, tool, args, legionIssue) {
26345
+ function parentStatusConflictLines(error, tool, args) {
26118
26346
  if (!dispatchAnswered(error, 409) || error.code !== "PARENT_STATUS_CONFLICT")
26119
26347
  return;
26120
26348
  const issues = error.issues ?? [];
@@ -26125,28 +26353,15 @@ function parentStatusConflictLines(error, tool, args, legionIssue) {
26125
26353
  return [
26126
26354
  messageFor(error),
26127
26355
  ...issues.map((issue) => `${issue.key} [${issue.status}] ${issue.title}`),
26128
- ...nextSteps(tool, args, parents, children, legionIssue)
26356
+ ...nextSteps(tool, args, parents, children)
26129
26357
  ];
26130
26358
  }
26131
26359
  var CHILD_FLAGS = "dispatch issue-update --status takes --unlink-children, which removes its open children from it, or, with a status other than done, --include-children, which moves the open issues under the issue with it. A person signed in at a browser closes them with it on the issue's page.";
26132
26360
  var PARENT_FLAG = "dispatch issue-update --status takes --include-parent, which moves each issue above the issue that is not in work to in_progress.";
26133
- function otherProjectSentence(named, keys) {
26134
- const project = named === undefined ? undefined : issueProject(named);
26135
- if (project === undefined)
26136
- return "";
26137
- const others = keys.filter((key) => {
26138
- const other = issueProject(key);
26139
- return other !== undefined && other !== project;
26140
- });
26141
- if (others.length === 0)
26142
- return "";
26143
- const one = others.length === 1;
26144
- return ` ${others.join(", ")} ${one ? "is" : "are"} not in the project of ${named}. A credential scoped to one project is refused a step that writes ${one ? "it" : "them"} (403 PROJECT_SCOPE), so a person, or a credential that names no project, must make that step.`;
26145
- }
26146
26361
  function includeParentCall(key) {
26147
26362
  return `${commandLine("dispatch_issue_update", { issue: key, status: "in_progress", include_parent: true })}, which also moves each issue above ${key} that is not in work`;
26148
26363
  }
26149
- function nextSteps(tool, args, parents, children, legionIssue) {
26364
+ function nextSteps(tool, args, parents, children) {
26150
26365
  if (tool === "dispatch_issue") {
26151
26366
  return parents.map((key) => `dispatch issue takes no flag that moves a done parent. Reopen ${key} first, with ${includeParentCall(key)}, then run dispatch issue again; or run it with --parent naming an open issue, or with no --parent.`);
26152
26367
  }
@@ -26154,9 +26369,7 @@ function nextSteps(tool, args, parents, children, legionIssue) {
26154
26369
  const written = issueUpdate ? args : {};
26155
26370
  const fields = Object.keys(written).filter((field) => field !== "issue" && written[field] !== undefined);
26156
26371
  const issue = optionalString(written, "issue");
26157
- const named = issueUpdate ? issue ?? legionIssue : undefined;
26158
26372
  const childHolds = children.length > 0;
26159
- const childScope = otherProjectSentence(named, children);
26160
26373
  const status = optionalString(written, "status");
26161
26374
  const parent = optionalString(written, "parent");
26162
26375
  const alone = `--status${status === "done" ? " and --reason" : ""} alone`;
@@ -26169,7 +26382,7 @@ function nextSteps(tool, args, parents, children, legionIssue) {
26169
26382
  const afterStatus = childHolds ? ", after the status change," : "";
26170
26383
  return [
26171
26384
  ...childHolds ? [
26172
- `${CHILD_FLAGS} Each goes with ${alone}, so run the status change first, in a call of its own, and the reparent after it: ${reparent}.${childScope}`
26385
+ `${CHILD_FLAGS} Each goes with ${alone}, so run the status change first, in a call of its own, and the reparent after it: ${reparent}.`
26173
26386
  ] : [],
26174
26387
  ...parents.map((key) => `dispatch issue-update takes no flag that moves the parent a reparent names. Move ${key} into work first, with ${includeParentCall(key)}; then${afterStatus} run the reparent again: ${reparent}.`)
26175
26388
  ];
@@ -26177,8 +26390,8 @@ function nextSteps(tool, args, parents, children, legionIssue) {
26177
26390
  const others = ISSUE_UPDATE_PATCH_FIELDS.some((field) => written[field] !== undefined);
26178
26391
  const apart = (subject) => others ? ` ${subject} with ${alone}, so send the call's other changes in a call of their own.` : "";
26179
26392
  return [
26180
- ...childHolds ? [`${CHILD_FLAGS}${apart("Each goes")}${childScope}`] : [],
26181
- ...parents.length > 0 ? [`${PARENT_FLAG}${apart("It goes")}${otherProjectSentence(named, parents)}`] : []
26393
+ ...childHolds ? [`${CHILD_FLAGS}${apart("Each goes")}`] : [],
26394
+ ...parents.length > 0 ? [`${PARENT_FLAG}${apart("It goes")}`] : []
26182
26395
  ];
26183
26396
  }
26184
26397
  function dispatchAnswered(error, status) {
@@ -29947,6 +30160,16 @@ function hostSession(hostName, env) {
29947
30160
  const file = (env.DISPATCH_HOST === undefined ? null : handedConfigFile(env)) ?? sessionConfigFile(host, env);
29948
30161
  return { host, sessionId, file };
29949
30162
  }
30163
+ function hostSessionDirectory(hostName, env) {
30164
+ const hosted = hostSession(hostName, env);
30165
+ if ("problem" in hosted)
30166
+ return hosted;
30167
+ try {
30168
+ return { ...hosted, dir: sessionDirectory(env, hosted.sessionId) };
30169
+ } catch (error) {
30170
+ return { problem: messageFor(error) };
30171
+ }
30172
+ }
29950
30173
  async function hostedDispatch(file, env, options) {
29951
30174
  if (file.path === null)
29952
30175
  return { problem: `dispatch: ${file.error}`, warnings: [] };
@@ -32483,7 +32706,7 @@ function parseFrameJSON(text) {
32483
32706
  const containers = typeof value === "object" && value !== null ? [value] : [];
32484
32707
  for (let next = containers.pop();next !== undefined; next = containers.pop()) {
32485
32708
  const members = next;
32486
- delete members["__proto__"];
32709
+ Reflect.deleteProperty(members, "__proto__");
32487
32710
  let names = Object.keys(members);
32488
32711
  if (names.some((name) => name.search(LONE_SURROGATE) !== -1)) {
32489
32712
  const held = names.map((name) => members[name]);
@@ -32674,32 +32897,6 @@ function createDeliveryDedupe(now = Date.now) {
32674
32897
  }
32675
32898
  };
32676
32899
  }
32677
- function isCommentTargetedDelivery(delivery) {
32678
- return "comment_id" in delivery;
32679
- }
32680
- var DispatchTargetedFrameSchema = object({
32681
- event: DispatchEventSchema,
32682
- delivery: DispatchTargetedDeliverySchema
32683
- }).superRefine(({ event, delivery }, context) => {
32684
- if (event.type === "message.created" && !isCommentTargetedDelivery(delivery) && DispatchTargetedMessagePayloadSchema.safeParse(event.payload).success) {
32685
- return;
32686
- }
32687
- if (event.type === "comment.created" && isCommentTargetedDelivery(delivery) && DispatchTargetedCommentPayloadSchema.safeParse(event.payload).success) {
32688
- return;
32689
- }
32690
- context.addIssue({
32691
- code: "custom",
32692
- message: event.type === "comment.created" ? "targeted delivery requires a complete comment.created event" : "targeted delivery requires a complete message.created event"
32693
- });
32694
- });
32695
- var RecoverableDispatchDeliveryFailureSchema = object({
32696
- event: object({
32697
- type: _enum2(["message.created", "comment.created"]),
32698
- issue_key: string2().nullable(),
32699
- payload: object({ id: string2(), body: string2().optional() }).passthrough()
32700
- }).passthrough(),
32701
- delivery: DispatchTargetedDeliverySchema
32702
- }).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" });
32703
32900
  function eventPictures(event) {
32704
32901
  let text;
32705
32902
  if (event.type.startsWith("message.")) {
@@ -32731,16 +32928,22 @@ function carriedItem(event) {
32731
32928
  const resource = event.type.startsWith("comment.") || event.type.startsWith("suggestion.") ? "comment" : event.type.startsWith("message.") ? "message" : undefined;
32732
32929
  if (resource === undefined || !isObject3(event.payload))
32733
32930
  return;
32734
- const id = event.payload["id"];
32931
+ const { id } = event.payload;
32735
32932
  if (typeof id !== "string" || id === "")
32736
32933
  return;
32737
32934
  return { resource, id, issueKey: event.issue_key };
32738
32935
  }
32739
32936
  function payloadWasOmitted(payload) {
32740
- return isObject3(payload) && payload["payload_omitted"] === true;
32937
+ if (!isObject3(payload))
32938
+ return false;
32939
+ const { payload_omitted } = payload;
32940
+ return payload_omitted === true;
32741
32941
  }
32742
32942
  function bodyWasCut(payload) {
32743
- return isObject3(payload) && payload["body_truncated"] === true || payloadWasOmitted(payload);
32943
+ if (!isObject3(payload))
32944
+ return false;
32945
+ const { body_truncated } = payload;
32946
+ return body_truncated === true || payloadWasOmitted(payload);
32744
32947
  }
32745
32948
  function wholeItemRoute(item) {
32746
32949
  return `GET /api/v1/${item.resource === "comment" ? "comments" : "messages"}/${item.id}`;
@@ -32985,7 +33188,10 @@ var DISPATCH_BOOKKEEPING = new Set([
32985
33188
  ]);
32986
33189
  function dispatchPayloadForReader(event, sessionID, issuedAt, toReader) {
32987
33190
  const whole = dispatchPayload(event);
32988
- const changed = event.type !== "issue.created" && isObject3(whole) && Array.isArray(whole["changed"]) ? whole["changed"] : [];
33191
+ let changedField;
33192
+ if (event.type !== "issue.created" && isObject3(whole))
33193
+ ({ changed: changedField } = whole);
33194
+ const changed = Array.isArray(changedField) ? changedField : [];
32989
33195
  const payload = withoutEmptyFields(whole, (key, item) => changed.includes(key) || (key === "suggestion" || key === "forced") && item !== null && item !== undefined);
32990
33196
  if (!isObject3(payload) || Array.isArray(payload))
32991
33197
  return payload;
@@ -33100,27 +33306,25 @@ function parseDispatchFrame(rawPayload, wholeBody) {
33100
33306
  try {
33101
33307
  value = parseFrameJSON(rawPayload);
33102
33308
  } catch {
33103
- return { raw: rawPayload };
33309
+ return {};
33104
33310
  }
33105
- if (isObject3(value) && "delivery" in value) {
33106
- const targeted = DispatchTargetedFrameSchema.safeParse(value);
33107
- if (targeted.success) {
33108
- const wireFrame = value;
33311
+ const reading = readDispatchPayload(value);
33312
+ switch (reading.kind) {
33313
+ case "event": {
33314
+ const { notify, quiet } = reading.wireEvent;
33109
33315
  return {
33110
- event: withWholeBody(targeted.data.event, wholeBody),
33111
- notify: wireFrame.event.notify,
33112
- quiet: wireFrame.event.quiet,
33113
- delivery: targeted.data.delivery
33316
+ event: withWholeBody(reading.event, wholeBody),
33317
+ notify,
33318
+ quiet,
33319
+ delivery: reading.delivery
33114
33320
  };
33115
33321
  }
33116
- const recoverable = RecoverableDispatchDeliveryFailureSchema.safeParse(value);
33117
- if (recoverable.success) {
33118
- const delivery = recoverable.data.delivery;
33322
+ case "recovered": {
33323
+ const { delivery, event } = reading.failure;
33119
33324
  const commentDelivery = isCommentTargetedDelivery(delivery);
33120
33325
  const resource = commentDelivery ? "comment" : "message";
33121
- const id = commentDelivery ? delivery.comment_id : recoverable.data.event.payload.id;
33326
+ const id = commentDelivery ? delivery.comment_id : event.payload.id;
33122
33327
  return {
33123
- raw: value,
33124
33328
  rejectedDelivery: {
33125
33329
  resource,
33126
33330
  id,
@@ -33128,24 +33332,15 @@ function parseDispatchFrame(rawPayload, wholeBody) {
33128
33332
  mode: delivery.mode,
33129
33333
  replyPath: dispatchReplyPath(resource, id),
33130
33334
  replyFields: commentDelivery ? { target: delivery.target } : {},
33131
- issueKey: recoverable.data.event.issue_key,
33132
- body: recoverable.data.event.payload.body ?? ""
33335
+ issueKey: event.issue_key,
33336
+ body: event.payload.body ?? ""
33133
33337
  },
33134
33338
  malformedDelivery: true
33135
33339
  };
33136
33340
  }
33137
- return { raw: value, malformedDelivery: true };
33341
+ case "raw":
33342
+ return reading.targeted ? { malformedDelivery: true } : {};
33138
33343
  }
33139
- const parsed = DispatchEventSchema.safeParse(value);
33140
- if (!parsed.success)
33141
- return { raw: value };
33142
- const wireEvent = value;
33143
- return {
33144
- event: withWholeBody(parsed.data, wholeBody),
33145
- notify: wireEvent.notify,
33146
- quiet: wireEvent.quiet,
33147
- delivery: undefined
33148
- };
33149
33344
  }
33150
33345
  var INBOUND_CARD_MAX_BYTES = 1 << 20;
33151
33346
  function encodeWithin(value, maxBytes) {
@@ -33160,6 +33355,28 @@ function encodeWithin(value, maxBytes) {
33160
33355
  return lines.join(`
33161
33356
  `);
33162
33357
  }
33358
+ function headerActor(actor) {
33359
+ const { kind, id, act, service } = actor;
33360
+ return {
33361
+ kind,
33362
+ ...id === undefined ? {} : { id },
33363
+ ...act === undefined ? {} : { act: ActorActSchema.safeParse(act).data ?? "not shown" },
33364
+ ...kind !== "session" || service === undefined ? {} : { service: typeof service === "string" ? service : "not shown" }
33365
+ };
33366
+ }
33367
+ function dispatchCardAsText(rendered, event, reason, bound) {
33368
+ let text;
33369
+ try {
33370
+ text = JSON.stringify(event);
33371
+ } catch {}
33372
+ const asText = text === undefined ? undefined : encodeWithin({ envoy: { ...rendered, dispatch: text } }, bound);
33373
+ if (asText !== undefined)
33374
+ return asText;
33375
+ const notShown = `not shown: ${reason}`;
33376
+ const owner = event.owner === undefined ? {} : { owner: event.owner };
33377
+ const header = { type: event.type, actor: headerActor(event.actor), payload: notShown };
33378
+ return encodeWithin({ envoy: { ...rendered, dispatch: { ...owner, ...header } } }, bound) ?? encodeWithin({ envoy: { dispatch: { ...owner, ...header } } }, bound) ?? encodeWithin({ envoy: { dispatch: header } }, bound) ?? encode5({ envoy: { dispatch: { payload: notShown } } });
33379
+ }
33163
33380
  function inboundTimestamp(milliseconds) {
33164
33381
  if (milliseconds === undefined)
33165
33382
  return "unknown";
@@ -33267,13 +33484,13 @@ function renderInbound(raw, sessionID, subject, wholeBody) {
33267
33484
  dispatchReply = dispatchCommentReplyWith(frame.event, topic, commentPayload);
33268
33485
  if (frame.event.type === "message.created") {
33269
33486
  const message = DispatchTargetedMessagePayloadSchema.safeParse(frame.event.payload);
33270
- const requested = DispatchTargetedDeliverySchema.safeParse(frame.delivery);
33271
- if (message.success && requested.success && !isCommentTargetedDelivery(requested.data)) {
33487
+ const requested = frame.delivery;
33488
+ if (message.success && requested !== undefined && !isCommentTargetedDelivery(requested)) {
33272
33489
  delivery = {
33273
33490
  resource: "message",
33274
33491
  id: message.data.id,
33275
- attempt: requested.data.attempt,
33276
- mode: requested.data.mode,
33492
+ attempt: requested.attempt,
33493
+ mode: requested.mode,
33277
33494
  replyPath: dispatchReplyPath("message", message.data.id),
33278
33495
  replyFields: {},
33279
33496
  issueKey: frame.event.issue_key,
@@ -33291,15 +33508,15 @@ function renderInbound(raw, sessionID, subject, wholeBody) {
33291
33508
  }
33292
33509
  } else if (frame.event.type === "comment.created") {
33293
33510
  const comment = DispatchTargetedCommentPayloadSchema.safeParse(frame.event.payload);
33294
- const requested = DispatchTargetedDeliverySchema.safeParse(frame.delivery);
33295
- if (comment.success && requested.success && isCommentTargetedDelivery(requested.data)) {
33511
+ const requested = frame.delivery;
33512
+ if (comment.success && requested !== undefined && isCommentTargetedDelivery(requested)) {
33296
33513
  delivery = {
33297
33514
  resource: "comment",
33298
- id: requested.data.comment_id,
33299
- attempt: requested.data.attempt,
33300
- mode: requested.data.mode,
33301
- replyPath: dispatchReplyPath("comment", requested.data.comment_id),
33302
- replyFields: { target: requested.data.target },
33515
+ id: requested.comment_id,
33516
+ attempt: requested.attempt,
33517
+ mode: requested.mode,
33518
+ replyPath: dispatchReplyPath("comment", requested.comment_id),
33519
+ replyFields: { target: requested.target },
33303
33520
  issueKey: frame.event.issue_key,
33304
33521
  body: comment.data.body,
33305
33522
  ...comment.data.body_truncated === true ? { bodyTruncated: true } : {}
@@ -33318,7 +33535,9 @@ function renderInbound(raw, sessionID, subject, wholeBody) {
33318
33535
  let actor = frame.event.actor;
33319
33536
  if ("origin" in frame.event.actor) {
33320
33537
  const { origin, ...rest } = frame.event.actor;
33321
- const title = isObject3(origin) ? origin["session_title"] : undefined;
33538
+ let title;
33539
+ if (isObject3(origin))
33540
+ ({ session_title: title } = origin);
33322
33541
  actor = typeof title === "string" && title !== "" ? { ...rest, origin: { session_title: title } } : rest;
33323
33542
  }
33324
33543
  const owner = dispatchOwner(frame.event, topic);
@@ -33340,7 +33559,7 @@ function renderInbound(raw, sessionID, subject, wholeBody) {
33340
33559
  trailer = humanEditDiffBlock(edit.data.diff, edit.data.diff_truncated);
33341
33560
  }
33342
33561
  } else {
33343
- dispatchEvent = frame.raw;
33562
+ dispatchIssue = "payload";
33344
33563
  rejectedDelivery = frame.rejectedDelivery;
33345
33564
  malformedDelivery = frame.malformedDelivery === true;
33346
33565
  }
@@ -33395,7 +33614,7 @@ function renderInbound(raw, sessionID, subject, wholeBody) {
33395
33614
  args: { topic: `notifications.role.${role}`, message: "..." }
33396
33615
  }
33397
33616
  },
33398
- ...dispatchRendered ? { dispatch: dispatchEvent } : {
33617
+ ...dispatchRendered ? dispatchEvent === undefined ? {} : { dispatch: dispatchEvent } : {
33399
33618
  ...summaryIsHead ? {} : { summary: payloadSummary },
33400
33619
  ...message === undefined ? {} : { message }
33401
33620
  },
@@ -33405,7 +33624,6 @@ function renderInbound(raw, sessionID, subject, wholeBody) {
33405
33624
  },
33406
33625
  ...unrecognised === undefined ? {} : { unrecognised }
33407
33626
  };
33408
- const payloadKey = dispatchRendered ? "dispatch" : "message";
33409
33627
  const payloadValue = dispatchRendered ? dispatchEvent : message;
33410
33628
  const cardBound = Math.max(INBOUND_CARD_MAX_BYTES, 2 * (Buffer.byteLength(raw) + (wholeBody === undefined ? 0 : Buffer.byteLength(escapeString(wholeBody)))));
33411
33629
  let card;
@@ -33419,7 +33637,7 @@ function renderInbound(raw, sessionID, subject, wholeBody) {
33419
33637
  }
33420
33638
  if (card === undefined) {
33421
33639
  payloadShownAsText ??= `its layout is larger than the ${cardBound} bytes a card holds`;
33422
- card = encode5({ envoy: { ...rendered, [payloadKey]: envelope.payload } });
33640
+ card = dispatchEvent === undefined ? encode5({ envoy: { ...rendered, message: envelope.payload } }) : dispatchCardAsText(rendered, dispatchEvent, payloadShownAsText, cardBound);
33423
33641
  }
33424
33642
  return {
33425
33643
  skip: false,
@@ -34188,7 +34406,8 @@ async function resolveOwnerArguments(tool, input, cwd, env, exec, dashboardUrls,
34188
34406
  if (tool === "dispatch_read" && typeof args.message === "string") {
34189
34407
  return { args, ref, owner: null };
34190
34408
  }
34191
- if (tool === "dispatch_result" && typeof args["retract"] === "string") {
34409
+ const { retract } = args;
34410
+ if (tool === "dispatch_result" && typeof retract === "string") {
34192
34411
  return { args, ref, owner: null };
34193
34412
  }
34194
34413
  const legionIssue = env.LEGION_ISSUE;
@@ -35581,7 +35800,8 @@ async function relatedCommand(context) {
35581
35800
  };
35582
35801
  }
35583
35802
  function printsJson(tool, args) {
35584
- return tool === "dispatch_issues" && args["json"] === true;
35803
+ const { json } = args;
35804
+ return tool === "dispatch_issues" && json === true;
35585
35805
  }
35586
35806
  async function issuesCommand(context) {
35587
35807
  const { args, client, input } = context;
@@ -35647,7 +35867,8 @@ async function issuesCommand(context) {
35647
35867
  };
35648
35868
  }
35649
35869
  function dryRunAsksDispatch(tool, args) {
35650
- return tool === "dispatch_result" && args["retract"] === undefined;
35870
+ const { retract } = args;
35871
+ return tool === "dispatch_result" && retract === undefined;
35651
35872
  }
35652
35873
  async function resultCommand(context) {
35653
35874
  const { args, client, actor } = context;
@@ -35739,23 +35960,6 @@ async function resultsCommand(context) {
35739
35960
 
35740
35961
  // ../envoy-client/src/dispatch-commands/login.ts
35741
35962
  import { hostname as hostname4 } from "os";
35742
- var LOGIN_HELP = [
35743
- "Usage: dispatch login --device [--person <address>]",
35744
- "",
35745
- "Logs this machine in at the secrets broker, once per machine, for a machine with no identity of its own, such as a laptop. It prints a code and the page to type it into; the person the login names approves it there, signed in to Dispatch. The login is then kept in the file AGENT_SECRETS_DEVICE_LOGIN_FILE names (default ~/.config/legion/device-login.json), mode 0600, and every session that sets AGENT_SECRETS_MACHINE_IDENTITY=device-login trades it for its broker token.",
35746
- "",
35747
- "Flags:",
35748
- " --device",
35749
- " Log in with the broker's device grant: the only way there is, and required.",
35750
- " --person <address>",
35751
- ` The person who approves the login, by the address they sign in to Dispatch with; else ${PERSON_VAR}.`,
35752
- "",
35753
- `It reads ${BROKER_URL_VAR}, the broker, and needs no Dispatch host or session.`,
35754
- "",
35755
- `Example: ${DEVICE_LOGIN_COMMAND} --person ada@example.com`,
35756
- ""
35757
- ].join(`
35758
- `);
35759
35963
  function parseLogin(argv) {
35760
35964
  let device = false;
35761
35965
  let person;
@@ -35786,7 +35990,7 @@ async function loginCommand(argv, env, io) {
35786
35990
  };
35787
35991
  const parsed = parseLogin(argv);
35788
35992
  if (parsed.kind === "help") {
35789
- io.print(LOGIN_HELP);
35993
+ io.print(loginHelp());
35790
35994
  return OK;
35791
35995
  }
35792
35996
  const tokenFiles = tokenFilesSet(env);
@@ -38487,9 +38691,9 @@ async function whoamiCommand(context) {
38487
38691
  } else {
38488
38692
  acting = `Session ${session} runs under the shared token: ${unowned}`;
38489
38693
  }
38490
- const writable = readOnly ? "" : project !== null ? ` It may write project ${project} and no other.` : writesAsService ? " It names no one project, so it may write wherever a token that names no project may." : "";
38694
+ const projectSentence = readOnly ? "" : project !== null ? ` Its token names project ${project}.` : writesAsService ? " It names no one project, so it may write wherever a token that names no project may." : "";
38491
38695
  return {
38492
- text: acting + elsewhere + writable,
38696
+ text: acting + elsewhere + projectSentence,
38493
38697
  details: { session, owner, service, project, project_scope: projectScope }
38494
38698
  };
38495
38699
  }
@@ -38826,6 +39030,394 @@ async function executeDispatchTool(input) {
38826
39030
  return command.origin === "none" ? command.run(session) : command.run(await commandContext(session));
38827
39031
  }
38828
39032
 
39033
+ // ../envoy-client/src/dispatch-proxy.ts
39034
+ import { lstatSync, rmSync as rmSync3 } from "fs";
39035
+ import {
39036
+ createServer
39037
+ } from "http";
39038
+ import { constants as constants4 } from "os";
39039
+ var CANNOT_START = 2;
39040
+ var COMMAND_NOT_FOUND = 127;
39041
+ var COMMAND_CANNOT_RUN = 126;
39042
+ var FORWARDED = ["SIGTERM", "SIGINT", "SIGHUP"];
39043
+ var TARGET_REFUSED = { status: 400, code: "PROXY_TARGET_REFUSED" };
39044
+ var METHOD_REFUSED = { status: 405, code: "PROXY_METHOD_REFUSED" };
39045
+ var TRADE_REFUSED = { status: 502, code: "PROXY_TRADE_REFUSED" };
39046
+ var DISPATCH_UNREACHABLE = { status: 502, code: "PROXY_DISPATCH_UNREACHABLE" };
39047
+ var SENDS = "The proxy sends a GET whose path starts with /api/, and a POST to /api/v1/issues/<key>/comments that carries an Idempotency-Key header, and nothing else.";
39048
+ var HOP_BY_HOP = new Set([
39049
+ "connection",
39050
+ "keep-alive",
39051
+ "proxy-connection",
39052
+ "proxy-authenticate",
39053
+ "proxy-authorization",
39054
+ "te",
39055
+ "trailer",
39056
+ "transfer-encoding",
39057
+ "upgrade"
39058
+ ]);
39059
+ var NOT_COPIED = new Set([
39060
+ ...HOP_BY_HOP,
39061
+ "host",
39062
+ "expect",
39063
+ "authorization",
39064
+ "dpop",
39065
+ "accept-encoding",
39066
+ "content-length"
39067
+ ]);
39068
+ var COMMENT_PATH = /^\/api\/v1\/issues\/[^/]+\/comments$/;
39069
+
39070
+ class Tally {
39071
+ requests = 0;
39072
+ tokens = new Set;
39073
+ renewed = 0;
39074
+ line() {
39075
+ return proxyExitLine(this.requests, this.tokens.size, this.renewed);
39076
+ }
39077
+ }
39078
+ function socketPathTaken(socket) {
39079
+ try {
39080
+ lstatSync(socket);
39081
+ } catch (error) {
39082
+ if (hasErrnoCode(error, "ENOENT"))
39083
+ return;
39084
+ return `dispatch proxy: the socket path ${socket} cannot be read: ${messageFor(error)}`;
39085
+ }
39086
+ return `dispatch proxy: the socket path ${socket} exists. The proxy makes its socket new and refuses a path that exists, a socket a killed proxy left behind included. Give it a path in a new directory (mktemp -d).`;
39087
+ }
39088
+ async function runDispatchProxy(run) {
39089
+ const say = (line) => run.stderr(`${line}
39090
+ `);
39091
+ const tally = new Tally;
39092
+ const beforeStart = new AbortController;
39093
+ let caught;
39094
+ let child;
39095
+ const handlers = FORWARDED.map((signal) => {
39096
+ const handler = () => {
39097
+ if (child === undefined) {
39098
+ caught ??= signal;
39099
+ beforeStart.abort(new Error(`${signal} arrived before the command started`));
39100
+ return;
39101
+ }
39102
+ try {
39103
+ child.kill(signal);
39104
+ } catch {}
39105
+ };
39106
+ process.on(signal, handler);
39107
+ return [signal, handler];
39108
+ });
39109
+ const endedBySignal = (signal) => {
39110
+ say(`dispatch proxy: ${signal} arrived before the command started, so it runs no command.`);
39111
+ return 128 + constants4.signals[signal];
39112
+ };
39113
+ const server = proxyServer(run, tally);
39114
+ let made = false;
39115
+ try {
39116
+ const taken = socketPathTaken(run.socket);
39117
+ if (taken !== undefined) {
39118
+ say(taken);
39119
+ return CANNOT_START;
39120
+ }
39121
+ try {
39122
+ const first = await brokerTokenFor(run.env, run.sessionId)(AbortSignal.any([AbortSignal.timeout(DISPATCH_TOOL_DEADLINE_MS), beforeStart.signal]), true);
39123
+ tally.tokens.add(first.token.accessToken);
39124
+ } catch (error) {
39125
+ if (caught !== undefined)
39126
+ return endedBySignal(caught);
39127
+ say(`dispatch proxy: the secrets broker gave session ${run.sessionId} no Dispatch token, so the proxy starts no command: ${messageFor(error)}`);
39128
+ return CANNOT_START;
39129
+ }
39130
+ if (caught !== undefined)
39131
+ return endedBySignal(caught);
39132
+ try {
39133
+ await listen(server, run.socket);
39134
+ made = true;
39135
+ } catch (error) {
39136
+ say(`dispatch proxy: it cannot listen on ${run.socket}: ${messageFor(error)}`);
39137
+ return CANNOT_START;
39138
+ }
39139
+ server.on("error", (error) => say(`dispatch proxy: its socket failed: ${messageFor(error)}`));
39140
+ if (caught !== undefined)
39141
+ return endedBySignal(caught);
39142
+ let started;
39143
+ try {
39144
+ started = Bun.spawn([...run.command], {
39145
+ cwd: run.cwd,
39146
+ env: { ...run.commandEnv, DISPATCH_PROXY_SOCKET: run.socket },
39147
+ stdin: "inherit",
39148
+ stdout: "inherit",
39149
+ stderr: "inherit"
39150
+ });
39151
+ } catch (error) {
39152
+ say(`dispatch proxy: ${run.command[0]} could not be run: ${messageFor(error)}`);
39153
+ return hasErrnoCode(error, "ENOENT") ? COMMAND_NOT_FOUND : COMMAND_CANNOT_RUN;
39154
+ }
39155
+ child = started;
39156
+ const exited = await started.exited;
39157
+ const signal = started.signalCode;
39158
+ return signal === null ? started.exitCode ?? exited : 128 + constants4.signals[signal];
39159
+ } finally {
39160
+ for (const [signal, handler] of handlers)
39161
+ process.off(signal, handler);
39162
+ if (made) {
39163
+ server.close();
39164
+ server.closeAllConnections();
39165
+ rmSync3(run.socket, { force: true });
39166
+ }
39167
+ say(tally.line());
39168
+ }
39169
+ }
39170
+ async function listen(server, socket) {
39171
+ const { promise, resolve, reject } = Promise.withResolvers();
39172
+ server.once("error", reject);
39173
+ const kept = process.umask(127);
39174
+ try {
39175
+ server.listen(socket, () => resolve());
39176
+ await promise;
39177
+ } finally {
39178
+ process.umask(kept);
39179
+ server.off("error", reject);
39180
+ }
39181
+ }
39182
+ function proxyServer(run, tally) {
39183
+ const dispatch = new URL(run.config.url);
39184
+ dispatch.hash = "";
39185
+ const base = withoutTrailingSlashes(dispatch.pathname);
39186
+ const server = createServer((request, response) => {
39187
+ serve(request, response, run, dispatch, base, tally).catch((error) => {
39188
+ if (!response.headersSent) {
39189
+ answerRefusal(response, DISPATCH_UNREACHABLE, messageFor(error));
39190
+ return;
39191
+ }
39192
+ if (response.socket)
39193
+ response.socket.destroy();
39194
+ else
39195
+ response.destroy();
39196
+ });
39197
+ });
39198
+ server.on("connect", (_request, socket) => {
39199
+ refuseOnSocket(socket, `The proxy opens no tunnel (CONNECT). ${SENDS} Read a route with a GET under /api/, or with dispatch api.`);
39200
+ });
39201
+ server.on("upgrade", (_request, socket) => {
39202
+ refuseOnSocket(socket, `The proxy upgrades no connection (a WebSocket, for one). ${SENDS} Read the route with a plain GET, or with dispatch api.`);
39203
+ });
39204
+ server.on("clientError", (_error, socket) => {
39205
+ refuseOnSocket(socket, `The proxy cannot read this request as one it sends, the asterisk form (OPTIONS *) among them. ${SENDS} Read a route with a GET under /api/, or with dispatch api.`);
39206
+ });
39207
+ return server;
39208
+ }
39209
+ function refuseOnSocket(socket, error) {
39210
+ if (!socket.writable) {
39211
+ socket.destroy();
39212
+ return;
39213
+ }
39214
+ const body = JSON.stringify({ code: METHOD_REFUSED.code, error });
39215
+ socket.end([
39216
+ "HTTP/1.1 405 Method Not Allowed",
39217
+ "Content-Type: application/json",
39218
+ `Content-Length: ${Buffer.byteLength(body)}`,
39219
+ "Connection: close",
39220
+ "",
39221
+ body
39222
+ ].join(`\r
39223
+ `));
39224
+ }
39225
+ function answerRefusal(response, refusal, error) {
39226
+ const body = JSON.stringify({ code: refusal.code, error });
39227
+ response.writeHead(refusal.status, {
39228
+ "Content-Type": "application/json",
39229
+ "Content-Length": Buffer.byteLength(body)
39230
+ });
39231
+ response.end(body);
39232
+ }
39233
+ function namesAHost(target) {
39234
+ return /^[A-Za-z][A-Za-z0-9+.-]*:/.test(target) || target.startsWith("//");
39235
+ }
39236
+ function resolvesElsewhere(path) {
39237
+ if (path.includes("\\"))
39238
+ return true;
39239
+ return path.split("/").some((segment) => {
39240
+ const plain = segment.replace(/%2e/gi, ".");
39241
+ return plain === "." || plain === "..";
39242
+ });
39243
+ }
39244
+ var FRAGMENT_OR_CONTROL = /[#\u007f]|[^\u0020-\uffff]/;
39245
+ function elsewhereRefusal(target, path) {
39246
+ if (path.startsWith("/") && !resolvesElsewhere(path) && !FRAGMENT_OR_CONTROL.test(target)) {
39247
+ return;
39248
+ }
39249
+ return `${SENDS} The target ${JSON.stringify(target)} reaches another route than the one it names (a dot segment, a backslash, a # or a control character). Name the route's own path, or read it with dispatch api.`;
39250
+ }
39251
+ function methodRefusal(method, path, key) {
39252
+ const quoted = JSON.stringify(path);
39253
+ if (method === "GET") {
39254
+ return path.startsWith("/api/") ? undefined : `${SENDS} ${quoted} is outside /api/. Read a route of /api/v1 with dispatch api --path <path>.`;
39255
+ }
39256
+ if (method === "POST" && COMMENT_PATH.test(path)) {
39257
+ return (key ?? "").trim() !== "" ? undefined : `${SENDS} This comment POST carries no Idempotency-Key header. Send it with one, so a resend posts the comment once, or post the comment with dispatch comment.`;
39258
+ }
39259
+ if (DISPATCH_API_METHODS.includes(method)) {
39260
+ const row = writeRoute(method, path);
39261
+ if (row !== undefined) {
39262
+ return `${SENDS} ${method} ${quoted} is another write. Send it with dispatch ${row.commands[0]}. AskGate reviews that call if it gates the command.`;
39263
+ }
39264
+ if (!API_ROUTE_PATTERN.test(path)) {
39265
+ return `${SENDS} ${method} ${quoted} is another write, outside /api/v1, and no dispatch command sends it.`;
39266
+ }
39267
+ return `${SENDS} ${method} ${quoted} is another write, and no named dispatch command sends it. Send it with dispatch api --method ${method} --path <path>. In a session whose AskGate reviews Dispatch writes, that command sends only GET, so it refuses this write.`;
39268
+ }
39269
+ return `${SENDS} ${method} is no method it sends. Read the route with a GET, or with dispatch api.`;
39270
+ }
39271
+ var ENCODED_SEPARATOR = /%(?:2f|5c)/i;
39272
+ function outboundRefusal(url, dispatch, base) {
39273
+ if (url.origin === dispatch.origin && url.pathname.startsWith(`${base}/api/`) && !url.href.includes("#") && !ENCODED_SEPARATOR.test(url.pathname)) {
39274
+ return;
39275
+ }
39276
+ return `${SENDS} The URL it would send for ${JSON.stringify(url.pathname.slice(base.length))} is outside /api/ of the Dispatch server, has a fragment, or holds a percent-encoded / or \\ (%2F or %5C, in either case), which Dispatch's server can decode into another route. Name the route's own path, or read it with dispatch api.`;
39277
+ }
39278
+ function connectionNamed(value) {
39279
+ return new Set((value ?? "").split(",").map((name) => name.trim().toLowerCase()).filter((name) => name !== ""));
39280
+ }
39281
+ function forwardedHeaders(incoming) {
39282
+ const named = connectionNamed(incoming.connection);
39283
+ const headers = {};
39284
+ for (const [name, value] of Object.entries(incoming)) {
39285
+ if (value === undefined || NOT_COPIED.has(name) || named.has(name))
39286
+ continue;
39287
+ headers[name] = Array.isArray(value) ? value.join(", ") : value;
39288
+ }
39289
+ headers["accept-encoding"] = "identity";
39290
+ return headers;
39291
+ }
39292
+ function answeredHeaders(headers) {
39293
+ const named = connectionNamed(headers.get("connection"));
39294
+ const transferCoded = headers.has("transfer-encoding");
39295
+ const kept = {};
39296
+ headers.forEach((value, name) => {
39297
+ if (HOP_BY_HOP.has(name) || named.has(name) || name === "set-cookie")
39298
+ return;
39299
+ if (name === "content-length" && transferCoded)
39300
+ return;
39301
+ kept[name] = value;
39302
+ });
39303
+ const cookies = headers.getSetCookie();
39304
+ if (cookies.length > 0)
39305
+ kept["set-cookie"] = cookies;
39306
+ return kept;
39307
+ }
39308
+ async function wholeBody(request) {
39309
+ const chunks = [];
39310
+ for await (const chunk of request) {
39311
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
39312
+ }
39313
+ const body = new Uint8Array(chunks.reduce((length, chunk) => length + chunk.length, 0));
39314
+ let at = 0;
39315
+ for (const chunk of chunks) {
39316
+ body.set(chunk, at);
39317
+ at += chunk.length;
39318
+ }
39319
+ return body;
39320
+ }
39321
+
39322
+ class TradeRefused extends Error {
39323
+ }
39324
+ async function serve(request, response, run, dispatch, base, tally) {
39325
+ const target = request.url ?? "";
39326
+ const method = request.method ?? "";
39327
+ if (namesAHost(target)) {
39328
+ answerRefusal(response, TARGET_REFUSED, `The proxy sends each request to the Dispatch server ${run.config.url} alone, so a target that names a host, ${JSON.stringify(target)}, is refused. Write the path and the query alone.`);
39329
+ return;
39330
+ }
39331
+ const at = target.indexOf("?");
39332
+ const path = at === -1 ? target : target.slice(0, at);
39333
+ const outbound = new URL(dispatch);
39334
+ outbound.pathname = `${base}${path}`;
39335
+ outbound.search = at === -1 ? "" : target.slice(at);
39336
+ const header = request.headers["idempotency-key"];
39337
+ const key = Array.isArray(header) ? header.join(", ") : header;
39338
+ const refusal = elsewhereRefusal(target, path) ?? methodRefusal(method, outbound.pathname.slice(base.length), key) ?? outboundRefusal(outbound, dispatch, base);
39339
+ if (refusal !== undefined) {
39340
+ answerRefusal(response, METHOD_REFUSED, refusal);
39341
+ return;
39342
+ }
39343
+ const body = method === "GET" ? undefined : await wholeBody(request);
39344
+ const url = outbound.href;
39345
+ const headers = forwardedHeaders(request.headers);
39346
+ const upstream = new AbortController;
39347
+ response.once("close", () => {
39348
+ if (!response.writableFinished)
39349
+ upstream.abort();
39350
+ });
39351
+ const send = async () => {
39352
+ let presented;
39353
+ try {
39354
+ presented = await run.config.credential.headers(method, url, undefined, AbortSignal.any([AbortSignal.timeout(DISPATCH_TOOL_DEADLINE_MS), upstream.signal]));
39355
+ } catch (error) {
39356
+ throw new TradeRefused(messageFor(error));
39357
+ }
39358
+ const token = (presented.Authorization ?? "").replace(/^DPoP /, "");
39359
+ const fresh = !tally.tokens.has(token);
39360
+ tally.tokens.add(token);
39361
+ const answer = await fetch(url, {
39362
+ method,
39363
+ headers: { ...headers, ...presented },
39364
+ ...body === undefined ? {} : { body },
39365
+ redirect: "manual",
39366
+ decompress: false,
39367
+ signal: upstream.signal
39368
+ });
39369
+ tally.requests += 1;
39370
+ return { presented, answer, fresh };
39371
+ };
39372
+ let sent;
39373
+ try {
39374
+ sent = await send();
39375
+ if (await tokenNotLive(sent.answer)) {
39376
+ run.config.credential.stale?.(undefined, sent.presented);
39377
+ await sent.answer.body?.cancel();
39378
+ sent = await send();
39379
+ if (sent.fresh)
39380
+ tally.renewed += 1;
39381
+ }
39382
+ } catch (error) {
39383
+ if (upstream.signal.aborted)
39384
+ return;
39385
+ if (error instanceof TradeRefused) {
39386
+ answerRefusal(response, TRADE_REFUSED, error.message);
39387
+ return;
39388
+ }
39389
+ answerRefusal(response, DISPATCH_UNREACHABLE, `Dispatch at ${run.config.url} did not answer: ${messageFor(error)}`);
39390
+ return;
39391
+ }
39392
+ await giveBack(sent.answer, response);
39393
+ }
39394
+ async function giveBack(answer, response) {
39395
+ response.writeHead(answer.status, answeredHeaders(answer.headers));
39396
+ if (answer.body === null) {
39397
+ response.end();
39398
+ return;
39399
+ }
39400
+ response.flushHeaders();
39401
+ for await (const chunk of answer.body) {
39402
+ if (response.destroyed)
39403
+ return;
39404
+ if (!response.write(chunk))
39405
+ await drained(response);
39406
+ }
39407
+ response.end();
39408
+ }
39409
+ function drained(response) {
39410
+ const { promise, resolve } = Promise.withResolvers();
39411
+ const done = () => {
39412
+ response.off("drain", done);
39413
+ response.off("close", done);
39414
+ resolve();
39415
+ };
39416
+ response.on("drain", done);
39417
+ response.on("close", done);
39418
+ return promise;
39419
+ }
39420
+
38829
39421
  // ../envoy-client/src/dispatch-session-state.ts
38830
39422
  import { createHash as createHash3 } from "crypto";
38831
39423
  import {
@@ -38837,7 +39429,7 @@ import {
38837
39429
  readdirSync as readdirSync2,
38838
39430
  readFileSync as readFileSync5,
38839
39431
  readSync as readSync2,
38840
- rmSync as rmSync3,
39432
+ rmSync as rmSync4,
38841
39433
  statSync as statSync2,
38842
39434
  writeFileSync as writeFileSync3
38843
39435
  } from "fs";
@@ -38962,7 +39554,7 @@ function pruneSessions(root, now) {
38962
39554
  try {
38963
39555
  const idle = now - statSync2(dir).mtimeMs > IDLE_SESSION_MS;
38964
39556
  if (idle && askgateState(dir, now).kind === "off" && !recordNamesStore(dir)) {
38965
- rmSync3(dir, { recursive: true, force: true });
39557
+ rmSync4(dir, { recursive: true, force: true });
38966
39558
  }
38967
39559
  } catch (error) {
38968
39560
  if (!hasErrnoCode(error, "ENOENT"))
@@ -39727,6 +40319,65 @@ function commandHost(env, nearest) {
39727
40319
  return env.DISPATCH_HOST;
39728
40320
  return env.CLAUDE_CODE_CHILD_SESSION === "1" ? "claude" : undefined;
39729
40321
  }
40322
+ async function runProxyCommand(rest, env, rawEnv, io, hostName) {
40323
+ const say = (text) => io.stderr(`${text}
40324
+ `);
40325
+ const parsed = parseProxyArgv(rest, io.cwd);
40326
+ if (parsed.kind === "help") {
40327
+ io.stdout(proxyHelp());
40328
+ return OK;
40329
+ }
40330
+ if (parsed.kind === "refused") {
40331
+ say(`dispatch proxy: ${parsed.problem} Run dispatch proxy --help.`);
40332
+ return USAGE;
40333
+ }
40334
+ const { dryRun, socket, command } = parsed;
40335
+ const cannotStart = (text) => {
40336
+ say(text);
40337
+ if (!dryRun)
40338
+ say(proxyExitLine(0, 0, 0));
40339
+ return USAGE;
40340
+ };
40341
+ const hosted = hostSessionDirectory(hostName(), env);
40342
+ if ("problem" in hosted)
40343
+ return cannotStart(hosted.problem);
40344
+ const { sessionId, file } = hosted;
40345
+ if ((env.DISPATCH_TOKEN_BROKER ?? "").trim() !== "1") {
40346
+ return cannotStart("dispatch proxy: DISPATCH_TOKEN_BROKER is not 1, so this session holds no broker token for the proxy to serve with. The proxy runs only where the deployment trades this session's Dispatch credential at the secrets broker, and never with a bearer.");
40347
+ }
40348
+ const resolved = await hostedDispatch(file, env, { cwd: io.cwd, session: sessionId });
40349
+ for (const line of resolved.warnings)
40350
+ say(line);
40351
+ if ("problem" in resolved)
40352
+ return cannotStart(resolved.problem);
40353
+ const { config } = resolved;
40354
+ if (config.credential.scheme !== "DPoP") {
40355
+ return cannotStart("dispatch proxy: this session's Dispatch credential is not a DPoP-bound broker token, and the proxy serves only with one.");
40356
+ }
40357
+ if (dryRun) {
40358
+ const taken = socketPathTaken(socket);
40359
+ if (taken !== undefined)
40360
+ return cannotStart(taken);
40361
+ io.stdout([`Dispatch server: ${config.url}`, `Session: ${sessionId}`, `Socket: ${socket}`, ""].join(`
40362
+ `));
40363
+ return OK;
40364
+ }
40365
+ const commandEnv = {};
40366
+ for (const [name, value] of Object.entries(rawEnv)) {
40367
+ if (value !== undefined)
40368
+ commandEnv[name] = value;
40369
+ }
40370
+ return await runDispatchProxy({
40371
+ socket,
40372
+ command,
40373
+ env,
40374
+ commandEnv,
40375
+ cwd: io.cwd,
40376
+ config,
40377
+ sessionId,
40378
+ stderr: (text) => io.stderr(text)
40379
+ });
40380
+ }
39730
40381
  async function runDispatchCli(argv, rawEnv, io) {
39731
40382
  const held = [];
39732
40383
  const print = (text) => {
@@ -39751,7 +40402,7 @@ async function runDispatchCli(argv, rawEnv, io) {
39751
40402
  if (value !== undefined && value !== "")
39752
40403
  env[name] = value;
39753
40404
  }
39754
- if (argv[0] === "login") {
40405
+ if (argv[0] === LOGIN_COMMAND) {
39755
40406
  return await loginCommand(argv.slice(1), env, {
39756
40407
  print,
39757
40408
  fetchImpl: io.fetchImpl,
@@ -39782,6 +40433,9 @@ async function runDispatchCli(argv, rawEnv, io) {
39782
40433
  ledgerRefusal(text, tool, askgate);
39783
40434
  return code;
39784
40435
  };
40436
+ if (argv[0] === PROXY_COMMAND) {
40437
+ return await runProxyCommand(argv.slice(1), env, rawEnv, io, ledgerHost);
40438
+ }
39785
40439
  let parsed;
39786
40440
  try {
39787
40441
  parsed = parseCommand(argv, io);
@@ -39858,16 +40512,10 @@ async function runDispatchCli(argv, rawEnv, io) {
39858
40512
  return REFUSED;
39859
40513
  }
39860
40514
  }
39861
- const hosted = hostSession(ledgerHost(), env);
40515
+ const hosted = hostSessionDirectory(ledgerHost(), env);
39862
40516
  if ("problem" in hosted)
39863
40517
  return refuse(hosted.problem, USAGE, parsed.tool);
39864
- const { host, sessionId, file } = hosted;
39865
- let dir;
39866
- try {
39867
- dir = sessionDirectory(env, sessionId);
39868
- } catch (error) {
39869
- return refuse(messageFor(error), USAGE, parsed.tool);
39870
- }
40518
+ const { host, sessionId, file, dir } = hosted;
39871
40519
  if (parsed.dryRun && !dryRunAsksDispatch(parsed.tool, parsed.args)) {
39872
40520
  const resolved = await sessionDispatchSettings(file, env, {
39873
40521
  cwd: io.cwd,
@@ -39970,7 +40618,7 @@ ${result.text}`);
39970
40618
  for (const file of fileOperands(argv)) {
39971
40619
  let bytes;
39972
40620
  try {
39973
- const fd = openSync4(operandPath(io.cwd, file), constants4.O_RDONLY | constants4.O_NONBLOCK);
40621
+ const fd = openSync4(operandPath(io.cwd, file), constants5.O_RDONLY | constants5.O_NONBLOCK);
39974
40622
  try {
39975
40623
  if (fstatSync3(fd).isFile())
39976
40624
  bytes = readFileSync7(fd);
@@ -40080,7 +40728,7 @@ ${result.text}`);
40080
40728
  entry = { tool, details: result.details };
40081
40729
  code = result.refused === true ? REFUSED : OK;
40082
40730
  } catch (error) {
40083
- text = (parentStatusConflictLines(error, tool, args, env.LEGION_ISSUE) ?? [messageFor(error)]).join(`
40731
+ text = (parentStatusConflictLines(error, tool, args) ?? [messageFor(error)]).join(`
40084
40732
  `);
40085
40733
  if (error instanceof DispatchWriteLandedError) {
40086
40734
  entry = { tool, details: { landed_without_answer: error.code } };