@sjawhar/claude-envoy 6.5.1 → 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";
@@ -15712,7 +15712,7 @@ var dispatchToolSpecs = [
15712
15712
  {
15713
15713
  name: "dispatch_project_update",
15714
15714
  example: { project: "CORE", proven_sessions: "on" },
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>. 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.",
15716
15716
  arguments: (z) => ({
15717
15717
  project: z.string().describe("Project key whose setting to change, such as CORE."),
15718
15718
  proven_sessions: z.enum(["on", "off"]).describe("on turns the setting on; off turns it off and needs the person scope.")
@@ -15765,7 +15765,7 @@ var dispatchToolSpecs = [
15765
15765
  {
15766
15766
  name: "dispatch_whoami",
15767
15767
  example: {},
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 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.",
15769
15769
  arguments: () => ({}),
15770
15770
  strict: true
15771
15771
  },
@@ -15779,7 +15779,7 @@ var dispatchToolSpecs = [
15779
15779
  {
15780
15780
  name: "dispatch_api",
15781
15781
  example: { path: "/api/v1/issues/DSP-1/events?limit=200" },
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): 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.",
15783
15783
  arguments: (z) => ({
15784
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.'),
15785
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(),
@@ -20733,7 +20733,186 @@ function fileTextBytes(text) {
20733
20733
  return encoder2.encode(text);
20734
20734
  }
20735
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
+
20736
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
+ ];
20737
20916
  var PREFIXED_FLAGS = [
20738
20917
  {
20739
20918
  tool: "dispatch_comment",
@@ -21005,7 +21184,10 @@ function parseCommand(argv, io) {
21005
21184
  return { kind: "help" };
21006
21185
  const tool = toolForCommand(command);
21007
21186
  if (tool === undefined) {
21008
- const commands = [...toolsByCommand.keys()].join(", ");
21187
+ const commands = [
21188
+ ...toolsByCommand.keys(),
21189
+ ...COMMANDS_OUTSIDE_THE_SPECS.map(({ name }) => name)
21190
+ ].join(", ");
21009
21191
  return {
21010
21192
  kind: "refused",
21011
21193
  problems: [`unknown command ${quoteWord(command)}; the commands are: ${commands}`]
@@ -21282,17 +21464,21 @@ function commandHelp(tool) {
21282
21464
  `);
21283
21465
  }
21284
21466
  function commandsHelp() {
21285
- 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));
21286
21475
  return [
21287
21476
  "Usage: dispatch <command> [flags]",
21288
- ...dispatchToolSpecs.map((spec) => {
21289
- const sentence = /^.*?[.!?](?=\s|$)/s.exec(spec.description)?.[0] ?? spec.description;
21290
- return ` ${commandName(spec.name).padEnd(width)} ${sentence}`;
21291
- }),
21477
+ ...rows.map(({ name, sentence }) => ` ${name.padEnd(width)} ${sentence}`),
21292
21478
  "",
21293
- "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.",
21294
21480
  "",
21295
- "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.",
21296
21482
  ""
21297
21483
  ].join(`
21298
21484
  `);
@@ -26073,12 +26259,10 @@ var WRITE_ROUTES = [
26073
26259
  commands: ["architecture-sync"]
26074
26260
  }
26075
26261
  ];
26262
+ var WRITE_ROUTE_SEGMENTS = WRITE_ROUTES.map((row) => ({ row, segments: row.pattern.split("/") }));
26076
26263
  function writeRoute(method, path) {
26077
26264
  const segments = path.split("/");
26078
- return WRITE_ROUTES.find((row) => {
26079
- const pattern = row.pattern.split("/");
26080
- return row.method === method && pattern.length === segments.length && pattern.every((part, at) => part.startsWith("{") ? segments[at] !== "" : part === segments[at]);
26081
- });
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;
26082
26266
  }
26083
26267
 
26084
26268
  class ApiGateRefusal extends Error {
@@ -26158,7 +26342,7 @@ function refusalWithCode(error, ...clauses) {
26158
26342
  const told = joined !== "" && /[.!?]$/.test(error.message) ? `${error.message} ${suffix.charAt(0).toUpperCase()}${suffix.slice(1)}` : `${error.message}${joined}`;
26159
26343
  return new DispatchServiceError(error.code, error.status, `${error.code}: ${told}`, error);
26160
26344
  }
26161
- function parentStatusConflictLines(error, tool, args, legionIssue) {
26345
+ function parentStatusConflictLines(error, tool, args) {
26162
26346
  if (!dispatchAnswered(error, 409) || error.code !== "PARENT_STATUS_CONFLICT")
26163
26347
  return;
26164
26348
  const issues = error.issues ?? [];
@@ -26169,28 +26353,15 @@ function parentStatusConflictLines(error, tool, args, legionIssue) {
26169
26353
  return [
26170
26354
  messageFor(error),
26171
26355
  ...issues.map((issue) => `${issue.key} [${issue.status}] ${issue.title}`),
26172
- ...nextSteps(tool, args, parents, children, legionIssue)
26356
+ ...nextSteps(tool, args, parents, children)
26173
26357
  ];
26174
26358
  }
26175
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.";
26176
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.";
26177
- function otherProjectSentence(named, keys) {
26178
- const project = named === undefined ? undefined : issueProject(named);
26179
- if (project === undefined)
26180
- return "";
26181
- const others = keys.filter((key) => {
26182
- const other = issueProject(key);
26183
- return other !== undefined && other !== project;
26184
- });
26185
- if (others.length === 0)
26186
- return "";
26187
- const one = others.length === 1;
26188
- 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.`;
26189
- }
26190
26361
  function includeParentCall(key) {
26191
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`;
26192
26363
  }
26193
- function nextSteps(tool, args, parents, children, legionIssue) {
26364
+ function nextSteps(tool, args, parents, children) {
26194
26365
  if (tool === "dispatch_issue") {
26195
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.`);
26196
26367
  }
@@ -26198,9 +26369,7 @@ function nextSteps(tool, args, parents, children, legionIssue) {
26198
26369
  const written = issueUpdate ? args : {};
26199
26370
  const fields = Object.keys(written).filter((field) => field !== "issue" && written[field] !== undefined);
26200
26371
  const issue = optionalString(written, "issue");
26201
- const named = issueUpdate ? issue ?? legionIssue : undefined;
26202
26372
  const childHolds = children.length > 0;
26203
- const childScope = otherProjectSentence(named, children);
26204
26373
  const status = optionalString(written, "status");
26205
26374
  const parent = optionalString(written, "parent");
26206
26375
  const alone = `--status${status === "done" ? " and --reason" : ""} alone`;
@@ -26213,7 +26382,7 @@ function nextSteps(tool, args, parents, children, legionIssue) {
26213
26382
  const afterStatus = childHolds ? ", after the status change," : "";
26214
26383
  return [
26215
26384
  ...childHolds ? [
26216
- `${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}.`
26217
26386
  ] : [],
26218
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}.`)
26219
26388
  ];
@@ -26221,8 +26390,8 @@ function nextSteps(tool, args, parents, children, legionIssue) {
26221
26390
  const others = ISSUE_UPDATE_PATCH_FIELDS.some((field) => written[field] !== undefined);
26222
26391
  const apart = (subject) => others ? ` ${subject} with ${alone}, so send the call's other changes in a call of their own.` : "";
26223
26392
  return [
26224
- ...childHolds ? [`${CHILD_FLAGS}${apart("Each goes")}${childScope}`] : [],
26225
- ...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")}`] : []
26226
26395
  ];
26227
26396
  }
26228
26397
  function dispatchAnswered(error, status) {
@@ -29991,6 +30160,16 @@ function hostSession(hostName, env) {
29991
30160
  const file = (env.DISPATCH_HOST === undefined ? null : handedConfigFile(env)) ?? sessionConfigFile(host, env);
29992
30161
  return { host, sessionId, file };
29993
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
+ }
29994
30173
  async function hostedDispatch(file, env, options) {
29995
30174
  if (file.path === null)
29996
30175
  return { problem: `dispatch: ${file.error}`, warnings: [] };
@@ -35781,23 +35960,6 @@ async function resultsCommand(context) {
35781
35960
 
35782
35961
  // ../envoy-client/src/dispatch-commands/login.ts
35783
35962
  import { hostname as hostname4 } from "os";
35784
- var LOGIN_HELP = [
35785
- "Usage: dispatch login --device [--person <address>]",
35786
- "",
35787
- "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.",
35788
- "",
35789
- "Flags:",
35790
- " --device",
35791
- " Log in with the broker's device grant: the only way there is, and required.",
35792
- " --person <address>",
35793
- ` The person who approves the login, by the address they sign in to Dispatch with; else ${PERSON_VAR}.`,
35794
- "",
35795
- `It reads ${BROKER_URL_VAR}, the broker, and needs no Dispatch host or session.`,
35796
- "",
35797
- `Example: ${DEVICE_LOGIN_COMMAND} --person ada@example.com`,
35798
- ""
35799
- ].join(`
35800
- `);
35801
35963
  function parseLogin(argv) {
35802
35964
  let device = false;
35803
35965
  let person;
@@ -35828,7 +35990,7 @@ async function loginCommand(argv, env, io) {
35828
35990
  };
35829
35991
  const parsed = parseLogin(argv);
35830
35992
  if (parsed.kind === "help") {
35831
- io.print(LOGIN_HELP);
35993
+ io.print(loginHelp());
35832
35994
  return OK;
35833
35995
  }
35834
35996
  const tokenFiles = tokenFilesSet(env);
@@ -38529,9 +38691,9 @@ async function whoamiCommand(context) {
38529
38691
  } else {
38530
38692
  acting = `Session ${session} runs under the shared token: ${unowned}`;
38531
38693
  }
38532
- 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." : "";
38533
38695
  return {
38534
- text: acting + elsewhere + writable,
38696
+ text: acting + elsewhere + projectSentence,
38535
38697
  details: { session, owner, service, project, project_scope: projectScope }
38536
38698
  };
38537
38699
  }
@@ -38868,6 +39030,394 @@ async function executeDispatchTool(input) {
38868
39030
  return command.origin === "none" ? command.run(session) : command.run(await commandContext(session));
38869
39031
  }
38870
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
+
38871
39421
  // ../envoy-client/src/dispatch-session-state.ts
38872
39422
  import { createHash as createHash3 } from "crypto";
38873
39423
  import {
@@ -38879,7 +39429,7 @@ import {
38879
39429
  readdirSync as readdirSync2,
38880
39430
  readFileSync as readFileSync5,
38881
39431
  readSync as readSync2,
38882
- rmSync as rmSync3,
39432
+ rmSync as rmSync4,
38883
39433
  statSync as statSync2,
38884
39434
  writeFileSync as writeFileSync3
38885
39435
  } from "fs";
@@ -39004,7 +39554,7 @@ function pruneSessions(root, now) {
39004
39554
  try {
39005
39555
  const idle = now - statSync2(dir).mtimeMs > IDLE_SESSION_MS;
39006
39556
  if (idle && askgateState(dir, now).kind === "off" && !recordNamesStore(dir)) {
39007
- rmSync3(dir, { recursive: true, force: true });
39557
+ rmSync4(dir, { recursive: true, force: true });
39008
39558
  }
39009
39559
  } catch (error) {
39010
39560
  if (!hasErrnoCode(error, "ENOENT"))
@@ -39769,6 +40319,65 @@ function commandHost(env, nearest) {
39769
40319
  return env.DISPATCH_HOST;
39770
40320
  return env.CLAUDE_CODE_CHILD_SESSION === "1" ? "claude" : undefined;
39771
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
+ }
39772
40381
  async function runDispatchCli(argv, rawEnv, io) {
39773
40382
  const held = [];
39774
40383
  const print = (text) => {
@@ -39793,7 +40402,7 @@ async function runDispatchCli(argv, rawEnv, io) {
39793
40402
  if (value !== undefined && value !== "")
39794
40403
  env[name] = value;
39795
40404
  }
39796
- if (argv[0] === "login") {
40405
+ if (argv[0] === LOGIN_COMMAND) {
39797
40406
  return await loginCommand(argv.slice(1), env, {
39798
40407
  print,
39799
40408
  fetchImpl: io.fetchImpl,
@@ -39824,6 +40433,9 @@ async function runDispatchCli(argv, rawEnv, io) {
39824
40433
  ledgerRefusal(text, tool, askgate);
39825
40434
  return code;
39826
40435
  };
40436
+ if (argv[0] === PROXY_COMMAND) {
40437
+ return await runProxyCommand(argv.slice(1), env, rawEnv, io, ledgerHost);
40438
+ }
39827
40439
  let parsed;
39828
40440
  try {
39829
40441
  parsed = parseCommand(argv, io);
@@ -39900,16 +40512,10 @@ async function runDispatchCli(argv, rawEnv, io) {
39900
40512
  return REFUSED;
39901
40513
  }
39902
40514
  }
39903
- const hosted = hostSession(ledgerHost(), env);
40515
+ const hosted = hostSessionDirectory(ledgerHost(), env);
39904
40516
  if ("problem" in hosted)
39905
40517
  return refuse(hosted.problem, USAGE, parsed.tool);
39906
- const { host, sessionId, file } = hosted;
39907
- let dir;
39908
- try {
39909
- dir = sessionDirectory(env, sessionId);
39910
- } catch (error) {
39911
- return refuse(messageFor(error), USAGE, parsed.tool);
39912
- }
40518
+ const { host, sessionId, file, dir } = hosted;
39913
40519
  if (parsed.dryRun && !dryRunAsksDispatch(parsed.tool, parsed.args)) {
39914
40520
  const resolved = await sessionDispatchSettings(file, env, {
39915
40521
  cwd: io.cwd,
@@ -40012,7 +40618,7 @@ ${result.text}`);
40012
40618
  for (const file of fileOperands(argv)) {
40013
40619
  let bytes;
40014
40620
  try {
40015
- 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);
40016
40622
  try {
40017
40623
  if (fstatSync3(fd).isFile())
40018
40624
  bytes = readFileSync7(fd);
@@ -40122,7 +40728,7 @@ ${result.text}`);
40122
40728
  entry = { tool, details: result.details };
40123
40729
  code = result.refused === true ? REFUSED : OK;
40124
40730
  } catch (error) {
40125
- text = (parentStatusConflictLines(error, tool, args, env.LEGION_ISSUE) ?? [messageFor(error)]).join(`
40731
+ text = (parentStatusConflictLines(error, tool, args) ?? [messageFor(error)]).join(`
40126
40732
  `);
40127
40733
  if (error instanceof DispatchWriteLandedError) {
40128
40734
  entry = { tool, details: { landed_without_answer: error.code } };