@sjawhar/claude-envoy 5.16.5 → 5.16.7

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.
@@ -0,0 +1,43 @@
1
+ /** A stream the hook ends before it exits: `end` calls back once the stream has taken every byte. */
2
+ export interface EndableStream {
3
+ end(callback: () => void): unknown
4
+ }
5
+
6
+ /**
7
+ * Ends the open-asks hook once what it wrote is out. Its work is done when `openAsks` returns, but
8
+ * a credential it asked the secrets broker for may still be trading in the background, under the
9
+ * broker client's own bounds (a 30 s attempt, `TRADE_ATTEMPT_MS`; a metadata server's 10 s; a
10
+ * pool's 20 s), and a process with a pending request or timer does not exit on its own: with a
11
+ * broker that never answers, the hook ran for 30 s, past the 20 s hooks.json gives it, and Claude
12
+ * Code would have killed it. Exiting cuts that trade, which writes nothing the next process reads,
13
+ * except on the device-login route: there the trade holds the login's lock and may yet save a
14
+ * refresh token the broker rotated, so a hook whose process holds that lock (`holdsLock`) is left
15
+ * to finish as before.
16
+ *
17
+ * The exit waits until each of `streams` (stdout and stderr) has taken every byte written to it:
18
+ * in Bun 1.4.4 an empty write's callback, `writableLength` and `writableNeedDrain` each let an exit
19
+ * drop the tail of a 300,000-byte write to a pipe (2 or 3 runs of 5), and `end` lost nothing (5 of
20
+ * 5). The lock is read after that, so a trade that takes it while they drain is left to finish too.
21
+ * Nothing the trade runs writes to `process.stderr` (its retry line goes through `console.warn`,
22
+ * which writes to the file descriptor and needs no open stream), so ending the streams first cannot
23
+ * fail it.
24
+ *
25
+ * The read of the lock and the exit are one synchronous step, with no await between them, so no
26
+ * other task of this process runs between the two: a read that waited (an async one) let this
27
+ * process's own trade take the lock and start a refresh in between, which the exit then cut
28
+ * (Legion's review 6014045405: 67 of 3,000 runs of its probe; none of 3,000 with a synchronous
29
+ * read). `holdsLock` must therefore answer synchronously.
30
+ */
31
+ export async function endOnceWritten(
32
+ streams: readonly EndableStream[],
33
+ holdsLock: () => boolean,
34
+ exit: (code: number) => void,
35
+ ): Promise<void> {
36
+ for (const stream of streams) {
37
+ const ended = Promise.withResolvers<void>()
38
+ stream.end(() => ended.resolve())
39
+ await ended.promise
40
+ }
41
+ if (holdsLock()) return
42
+ exit(0)
43
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Two of the open-asks hook's three waits, which it runs one after the other: jj's own user config
3
+ * chain for the pane's attribution overlay; then the resolution of Dispatch, which may run a `!`
4
+ * dispatch.token command for up to envoy-client's `COMMAND_TIMEOUT_MS` (10 s); then the Dispatch
5
+ * read of the session's open asks. Claude Code kills the hook at the `timeout` hooks.json gives
6
+ * `open-asks`, and the session then loses its exports and its summary, so the three, after Bun's
7
+ * start-up, must end inside it: tests/open-asks-hook.test.ts holds their sum and a start-up
8
+ * allowance below that timeout. A module of its own so that the test can import them:
9
+ * session-hook.ts runs the hook when it is loaded.
10
+ */
11
+
12
+ /** The bound on resolving jj's own user config chain for the overlay. Not
13
+ * `JJ_CONFIG_PATH_TIMEOUT_MS`, which is the Oh My Pi lane's bound inside the 30 s that harness
14
+ * gives its session-start handler. A jj that never answers costs the session the export and
15
+ * nothing else. */
16
+ export const JJ_BASE_CHAIN_TIMEOUT_MS = 3_000
17
+
18
+ /** The bound on the Dispatch read of the session's open asks. */
19
+ export const OPEN_ASKS_TIMEOUT_MS = 3_000
@@ -88,6 +88,7 @@
88
88
 
89
89
  import { appendFileSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
90
90
  import { join } from "node:path"
91
+ import { deviceLoginFile, loginLockHeldBy } from "@legion/cipher-client/device-login-file"
91
92
  import { scrubProcessStreams } from "@legion/contracts/held-secrets"
92
93
  import { urlForText } from "@legion/contracts/log-text"
93
94
  import { formatOpenAsksSummary, linkBaseOf } from "@legion/envoy-client/dispatch-execute"
@@ -119,13 +120,14 @@ import { claudeProjectDirectory, configuredValue } from "../src/claude-session"
119
120
  import { procStarted } from "../src/codex/codex-session-record"
120
121
  import { sessionHandoffFile, writeSessionHandoff } from "../src/session-identity"
121
122
  import { recordChosenTitle } from "../src/session-state"
123
+ import { endOnceWritten } from "./end-once-written"
122
124
  import { parseHookArguments } from "./hook-arguments"
125
+ import { JJ_BASE_CHAIN_TIMEOUT_MS, OPEN_ASKS_TIMEOUT_MS } from "./open-asks-bounds"
123
126
 
124
127
  // Every line this hook writes, the context Claude Code hands the model on stdout included, passes
125
128
  // the scrub of the secrets it holds (`@legion/contracts/held-secrets`).
126
129
  scrubProcessStreams()
127
130
 
128
- const OPEN_ASKS_TIMEOUT_MS = 3_000
129
131
  const OpenAsksInput = z.object({
130
132
  session_id: z.string().min(1),
131
133
  cwd: z.string().optional(),
@@ -250,12 +252,6 @@ const DISPATCH_HOST_LINE = "export DISPATCH_HOST=claude"
250
252
  /** What an overlay export line starts with: the one line of the env file this hook replaces
251
253
  * rather than adds to. */
252
254
  const JJ_CONFIG_EXPORT = "export JJ_CONFIG="
253
- /** The bound on resolving jj's own user config chain for the overlay, inside the 20 s hooks.json
254
- * gives this hook: 3 s of jj and then 3 s of the Dispatch read (`OPEN_ASKS_TIMEOUT_MS`) still
255
- * leave the session its summary. Not `JJ_CONFIG_PATH_TIMEOUT_MS`, which is the Oh My Pi lane's
256
- * bound inside the 30 s that harness gives its session-start handler. A jj that never answers
257
- * costs the session the export and nothing else. */
258
- const JJ_BASE_CHAIN_TIMEOUT_MS = 3_000
259
255
 
260
256
  /** `value` as a single-quoted shell word: Claude Code sources this file before every bash command
261
257
  * of the session, so a path or a config chain holding a space, a quote or a `$` must reach the
@@ -663,6 +659,22 @@ async function answersRefresh(session: string, cwd: string): Promise<never> {
663
659
  process.exit(0)
664
660
  }
665
661
 
662
+ /** Whether this process holds the machine's device-login lock: `<login>.lock`, beside the login at
663
+ * the path cipher-client keeps it (`deviceLoginFile`: `AGENT_SECRETS_DEVICE_LOGIN_FILE`, else
664
+ * `$HOME/.config/legion/device-login.json`), whose first word is its holder's pid. cipher-client
665
+ * reads it, synchronously (`loginLockHeldBy`, as `endOnceWritten` needs): a named pipe or a link
666
+ * there is read as no lock, at once, so it cannot hold the hook open. */
667
+ function holdsDeviceLoginLock(): boolean {
668
+ let login: string
669
+ try {
670
+ login = deviceLoginFile(process.env)
671
+ } catch {
672
+ // Neither the variable nor HOME names a place: this machine keeps no login, so holds no lock.
673
+ return false
674
+ }
675
+ return loginLockHeldBy(login, process.pid)
676
+ }
677
+
666
678
  if (mode === "answers-refresh") {
667
679
  const [session, cwd] = modeArguments
668
680
  if (session === undefined || cwd === undefined) {
@@ -678,5 +690,9 @@ if (mode !== "open-asks" && mode !== "dispatch-first" && mode !== "answers") {
678
690
  const text = await Bun.stdin.text()
679
691
  if (mode === "answers") await answers(text)
680
692
  const input: unknown = JSON.parse(text)
681
- if (mode === "open-asks") await openAsks(input)
682
- else dispatchFirst(input)
693
+ if (mode === "open-asks") {
694
+ await openAsks(input)
695
+ await endOnceWritten([process.stdout, process.stderr], holdsDeviceLoginLock, (code) =>
696
+ process.exit(code),
697
+ )
698
+ } else dispatchFirst(input)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sjawhar/claude-envoy",
3
- "version": "5.16.5",
3
+ "version": "5.16.7",
4
4
  "license": "Apache-2.0",
5
5
  "description": "Claude Code plugin for Legion's Envoy bus",
6
6
  "type": "module",
@@ -19,9 +19,10 @@ agent-secrets NAME... [--reason 'TEXT'] [--wait DURATION] [--ttl DURATION] -- <c
19
19
  - `--reason` is necessary wherever a person or the model judge decides: such a request that carries none is denied whole. A request every name of which is granted at once needs none. Write one sentence the approver can decide on, and name in it the issue you work on.
20
20
  - Each key says who decides a request for it: `agent-secrets secret show NAME` prints it on its `decides:` line, beside the `guidance:` a model judge decides by. Meet that guidance in `--reason`. The judge grants a request or refuses it for good (77); one it cannot decide goes to the key's person.
21
21
  - A session that must not block passes `--wait 0s` and reads the decision later with `agent-secrets status <request_id>`.
22
- The same command run again (the same names and `--ttl`) uses the live grant or joins the waiting request, and asks nobody again.
23
- - For a GitHub App secret, `--github-owner <account> --github-token` gives the command that one account's token, the string an `Authorization` header carries; `--github-repo` and `--github-read-only` narrow it further.
24
- Without `--github-token` the name holds the JSON object of installations, and GitHub answers it `401`.
22
+ The same command run again (the same names, `--ttl` and `--target`) uses the live grant or joins the waiting request, and asks nobody again.
23
+ - A GitHub App credential is a profile. `--target ACCOUNT`, or `--target ACCOUNT/REPOSITORY` for each repository of one account, narrows it in a run of that name alone.
24
+ A profile of value `token` puts one token in the name; any other holds the JSON object of installations, which GitHub answers `401`.
25
+ A line `the profile NAME left out …` names permissions the token lacks (calls needing them get `403`).
25
26
 
26
27
  ## The command reads the value, your shell does not
27
28
 
@@ -33,6 +34,8 @@ agent-secrets LEGION_SLACK_BOT_TOKEN --reason 'check that the Slack token works'
33
34
  sh -c 'printf "Authorization: Bearer %s" "$LEGION_SLACK_BOT_TOKEN" | curl -sS -H @- https://slack.com/api/auth.test'
34
35
  ```
35
36
 
37
+ In a pod, `gh` refuses `GH_TOKEN`, so call GitHub with `curl` that way: `agent-secrets GITHUB_READ --target ACCOUNT -- sh -c '…"$GITHUB_READ" | curl -sS -H @- https://api.github.com/…'`.
38
+
36
39
  Read the body, not the exit status alone: Slack and many HTTP APIs answer `200` with `"ok": false`.
37
40
  Send the body to `jq` straight from `curl` or through `printf '%s'`, never through `echo`, which can turn a `\n` inside a JSON string into a control character.
38
41
  Slack's read methods go through `curl` under this client. Every post to Slack is a `slack_post` call, which holds the reply to one thread, to 4,000 characters and to one send.
@@ -71,7 +74,6 @@ A deployment can keep a secret's value back. The name then holds `agent-secrets-
71
74
 
72
75
  - Make every call inside the `agent-secrets NAME -- <command>` run. A tool that caches a token across runs, or calls outside the run, stops working.
73
76
  - A proxy refusal names why it refused the call, and a retry does not fix it: change what the command sent as the refusal says, or report it with the command and its output. `407` means the grant ended: ask again. `503` means the broker could not read the grant: try the call again.
74
- - A GitHub narrowing and an airlocked name cannot share a run: ask for the GitHub App secret in a run of its own.
75
77
 
76
78
  ## What the exit status means
77
79
 
@@ -80,8 +82,8 @@ After a grant the client writes `agent-secrets: <names> from <source>` to stderr
80
82
  - **1**: a refusal or a failure that the message names.
81
83
  `UNKNOWN_SECRET` is final: do not ask again, and do not try a name of your own.
82
84
  `PENDING_VALUE` means its owner is storing the value now: ask again in a few minutes.
83
- `REQUEST_PENDING` names a waiting request of this session that shares a name with this one.
84
- - **2**: a usage error, such as no `AGENT_SECRETS_URL` or no `--`.
85
+ `REQUEST_PENDING` names a waiting request of this session for the same name, whatever its target: ask again once it is decided.
86
+ - **2**: a usage error: no `AGENT_SECRETS_URL`, no `--`, a `--target` refused, or a removed GitHub flag (it names its replacement); or a broker too old to confirm `--target`. Nothing ran.
85
87
  - **75**: the request is still undecided when `--wait` runs out, and nothing ran. The message gives the `agent-secrets status <request_id>` that reads it.
86
88
  - **77**: the request was denied; the message gives the broker's reason when it recorded one. Final: ask for none of it again, and try no name of your own. The exceptions: on a message that says `ask again with --reason`, ask again with `--reason`; on `requester-group-unread`, ask again later.
87
89
 
@@ -94,7 +96,7 @@ Request a secret only to use it for the work in front of you: every request is r
94
96
 
95
97
  1. Run the call through `agent-secrets`, with the secret your instructions name.
96
98
  2. A GitHub `404` under your session's own token is that token's reach, not your access: GitHub answers `404` for a repository a token cannot see.
97
- Ask for the GitHub App secret your instructions name, narrowed with `--github-owner`, `--github-repo`, `--github-read-only` and `--github-token`, and make the call again.
99
+ Ask for the GitHub profile your instructions name, with `--target` for the call's account or repositories, and call again.
98
100
  3. Report a service unreachable only with the command you ran and the output you saw.
99
101
  4. When no instruction names a secret for that service, report that, with the output of `agent-secrets identity --source` and the instructions you read. Request no name you guessed.
100
102