@kyleroche/relay 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Kyle Roche
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,25 @@
1
- # Temporary Holding Version
1
+ # @kyleroche/relay
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The `relay` command: your coding-agent subscriptions (Claude Code, Codex, Grok) working as one system. GitHub
4
+ issues are the task bus, runners on your own machines run the vendor CLIs under the machine's own login, a Postgres
5
+ database holds shared memory and an append-only event feed, and a small web app shows it all. Credentials never
6
+ leave the machine they were created on.
7
+
8
+ Needs Node 24 or newer. No checkout required:
9
+
10
+ ```bash
11
+ npx @kyleroche/relay doctor # what is installed, logged in, and reachable
12
+ npx @kyleroche/relay setup # hooks + memory MCP server into each CLI you have; prints the plan, --yes writes
13
+ cd ~/code/some-repo && npx @kyleroche/relay link
14
+ ```
15
+
16
+ `relay link` is the only per-repo step: it registers the repo, digests its files and writes the project summary
17
+ (Sonnet, a few cents), renders `relay.md` from that summary, and installs the owned sections, caller workflows and
18
+ labels. Re-running it is safe and makes no model calls unless files changed.
19
+
20
+ The package ships the CLI (`dist/relay.js`), the stdio memory server the CLIs talk to (`dist/relay-mcp.js`), the
21
+ dependency-free session hooks `relay setup` installs (`dist/hooks/`), the SQL migrations, and the caller workflow
22
+ templates. Locally it runs on an embedded Postgres (PGlite) under `~/.harness`; set `DATABASE_URL` for a server.
23
+
24
+ Source, architecture and the hosted web app: [github.com/kyleroche/relay](https://github.com/kyleroche/relay) and
25
+ [relay.kyro.house](https://relay.kyro.house). Apache-2.0.
@@ -0,0 +1,66 @@
1
+ # relay worker image (docs/WORKERS.md, "Isolation"): everything `relay work` needs, in one Linux VM.
2
+ #
3
+ # `relay work --isolation container --install` builds this with Apple's `container` CLI and creates the container
4
+ # `relay-work` from it, with a named volume at /home/relay. The vendor CLIs' logins, the site token, the clones and
5
+ # the model's shell all live in that volume; the Mac's home directory is never mounted. Everything the image
6
+ # installs goes under /usr/local, because the volume hides whatever the image put in /home/relay.
7
+ #
8
+ # Build arguments:
9
+ # RELAY_SPEC what `npm install -g` gets for relay when the build context holds no tarball
10
+ # (`@kyleroche/relay@<version>`); a checkout drops its `npm pack` tarball into the context instead
11
+ # FX_VERSION fx release (`vX.Y.Z`); `latest` reads https://releases.fx.sh/latest.txt
12
+ # CLAUDE_SPEC the Claude Code npm package spec
13
+ FROM docker.io/library/node:24-bookworm-slim
14
+
15
+ ARG RELAY_SPEC=@kyleroche/relay
16
+ ARG FX_VERSION=latest
17
+ ARG CLAUDE_SPEC=@anthropic-ai/claude-code
18
+ ARG DEBIAN_FRONTEND=noninteractive
19
+
20
+ # git, curl and CA certificates for the clone and the installers; bubblewrap, socat and ripgrep for Claude Code's own
21
+ # sandbox around the lane's Bash (nested inside the VM: the container is created with the runtime masks off so a
22
+ # user namespace can mount /proc); util-linux for `setpriv`; gh from GitHub's own apt repository.
23
+ RUN apt-get update \
24
+ && apt-get install -y --no-install-recommends ca-certificates curl git gnupg procps util-linux bubblewrap socat ripgrep less \
25
+ && install -d -m 0755 /usr/share/keyrings \
26
+ && curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg -o /usr/share/keyrings/githubcli-archive-keyring.gpg \
27
+ && chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg \
28
+ && echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" > /etc/apt/sources.list.d/github-cli.list \
29
+ && apt-get update \
30
+ && apt-get install -y --no-install-recommends gh \
31
+ && apt-get clean && rm -rf /var/lib/apt/lists/*
32
+
33
+ # fx: the release tarball for this architecture, verified against the .sha256 the CDN publishes beside it.
34
+ RUN set -eu; \
35
+ arch="$(uname -m)"; case "$arch" in aarch64|arm64) arch=aarch64;; x86_64|amd64) arch=x86_64;; *) echo "unsupported arch $arch" >&2; exit 1;; esac; \
36
+ v="$FX_VERSION"; if [ "$v" = latest ]; then v="$(curl -fsSL https://releases.fx.sh/latest.txt | tr -d '[:space:]')"; fi; \
37
+ cd /tmp; curl -fsSL "https://releases.fx.sh/$v/fx-linux-$arch.tar.gz" -o fx.tar.gz; \
38
+ curl -fsSL "https://releases.fx.sh/$v/fx-linux-$arch.tar.gz.sha256" -o fx.sha256; \
39
+ want="$(tr -d '[:space:]' < fx.sha256 | cut -c1-64)"; have="$(sha256sum fx.tar.gz | cut -c1-64)"; \
40
+ [ "$want" = "$have" ] || { echo "fx checksum mismatch: $want != $have" >&2; exit 1; }; \
41
+ tar -xzf fx.tar.gz; install -m 0755 fx /usr/local/bin/fx; rm -f fx fx.tar.gz fx.sha256; \
42
+ fx --version
43
+
44
+ # pnpm through corepack (the Node image ships it), Claude Code (its postinstall puts the native binary in place, so
45
+ # it is allowed by name), and relay: a tarball from the build context when a checkout built this image, the npm
46
+ # package otherwise.
47
+ COPY . /tmp/ctx/
48
+ RUN set -eu; \
49
+ corepack enable && corepack prepare pnpm@latest --activate; \
50
+ npm install -g --no-fund --no-audit --allow-scripts=@anthropic-ai/claude-code "$CLAUDE_SPEC"; \
51
+ tgz="$(ls /tmp/ctx/*.tgz 2>/dev/null | head -n1 || true)"; \
52
+ if [ -n "$tgz" ]; then npm install -g --no-fund --no-audit "$tgz"; else npm install -g --no-fund --no-audit "$RELAY_SPEC"; fi; \
53
+ npm cache clean --force; rm -rf /tmp/ctx; \
54
+ claude --version; relay --version
55
+
56
+ # The worker's user. The volume mounted at /home/relay arrives owned by root; relay-entry hands it over on first boot.
57
+ RUN userdel -r node 2>/dev/null || true; \
58
+ groupadd -g 1000 relay && useradd -m -u 1000 -g 1000 -s /bin/bash relay
59
+ COPY --chmod=0755 relay-entry /usr/local/bin/relay-entry
60
+
61
+ ENV RELAY_HOME=/home/relay/.harness \
62
+ RELAY_ISOLATION=container \
63
+ HOME=/home/relay
64
+ WORKDIR /home/relay
65
+ ENTRYPOINT ["/usr/local/bin/relay-entry"]
66
+ CMD ["relay", "work"]
@@ -0,0 +1,31 @@
1
+ #!/bin/sh
2
+ # Entry point of the relay worker image. The container starts as root only to hand the volume at /home/relay to the
3
+ # `relay` user (a fresh volume is an empty ext4 owned by root); then it drops to that user for whatever it was asked
4
+ # to run: `relay work` by default, `bash` for `relay work container shell`, `relay setup --site` at install.
5
+ #
6
+ # Login callback forwarders: `container create --publish 127.0.0.1:<port>:<port>` delivers the Mac browser's redirect
7
+ # to the container's eth0 address, but the login servers the CLIs start (`fx login codex` hands off to Codex's own
8
+ # listener on 1455; fx's own callback is 3000) bind the container's loopback only, so the redirect would be dropped.
9
+ # One socat per port listens on eth0 and forwards to 127.0.0.1, as the relay user, in the background; while no login
10
+ # runs the forwarder just waits (a connection then fails, as it would have anyway). RELAY_LOGIN_PORTS lists the ports
11
+ # (default: packages/core/src/work/container.ts LOGIN_CALLBACK_PORTS); empty turns the forwarders off.
12
+ set -eu
13
+ home=/home/relay
14
+ uid="$(id -u relay)"
15
+ gid="$(id -g relay)"
16
+ if [ "$(stat -c %u "$home")" != "$uid" ]; then chown "$uid:$gid" "$home"; fi
17
+ [ -d "$home/.harness" ] || install -d -o "$uid" -g "$gid" "$home/.harness"
18
+
19
+ ports="${RELAY_LOGIN_PORTS-3000 1455}"
20
+ if [ -n "$ports" ] && command -v socat >/dev/null 2>&1; then
21
+ # the image has no `ip`; hostname -I prints every address, the first is eth0's
22
+ addr="$(hostname -I 2>/dev/null | cut -d" " -f1)"
23
+ if [ -n "$addr" ]; then
24
+ for port in $ports; do
25
+ setpriv --reuid="$uid" --regid="$gid" --init-groups \
26
+ socat "TCP-LISTEN:$port,bind=$addr,reuseaddr,fork" "TCP:127.0.0.1:$port" >/dev/null 2>&1 &
27
+ done
28
+ fi
29
+ fi
30
+
31
+ exec setpriv --reuid="$uid" --regid="$gid" --init-groups env HOME="$home" USER=relay LOGNAME=relay "$@"
@@ -0,0 +1,105 @@
1
+ // Shared helpers for the relay hook scripts. Plain Node ESM with no dependencies, because a hook runs on every
2
+ // session start and prompt: it must answer fast and must never break the session. The heavy work (PGlite, the
3
+ // brief compiler) lives in the CLI, which these scripts spawn (dist/relay.js, or the repo's own tsx) only when the cache misses.
4
+ import { spawnSync, spawn } from "node:child_process";
5
+ import { createHash } from "node:crypto";
6
+ import { existsSync, mkdirSync, openSync, readFileSync } from "node:fs";
7
+ import { createRequire } from "node:module";
8
+ import { homedir } from "node:os";
9
+ import { dirname, join, resolve } from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+
12
+ export const HOOKS_DIR = dirname(fileURLToPath(import.meta.url));
13
+ /** In the published package the hooks sit at dist/hooks beside the bundled CLI, dist/relay.js. */
14
+ export const BUNDLED_CLI = resolve(HOOKS_DIR, "..", "relay.js");
15
+ /** In a checkout they sit at packages/cli/hooks and the CLI is TypeScript, run through the repo's tsx. */
16
+ export const RELAY_ROOT = resolve(HOOKS_DIR, "..", "..", "..");
17
+ export const CLI_MAIN = join(RELAY_ROOT, "packages", "cli", "src", "main.ts");
18
+ export const RELAY_HOME = process.env.RELAY_HOME ?? join(homedir(), ".harness");
19
+ export const BRIEF_TTL_MS = 10 * 60_000;
20
+
21
+ /** `--cli <name>` from argv; the CLI the hook was installed for. */
22
+ export function cliName() {
23
+ const i = process.argv.indexOf("--cli");
24
+ return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : "claude";
25
+ }
26
+
27
+ /** Read the hook payload from stdin (JSON, or nothing). Never blocks for more than a moment. */
28
+ export function readPayload() {
29
+ try {
30
+ const raw = readFileSync(0, "utf8");
31
+ return raw.trim() ? JSON.parse(raw) : {};
32
+ } catch {
33
+ return {};
34
+ }
35
+ }
36
+
37
+ /** Nearest ancestor of `cwd` holding .relay/rules.json, and the slug it names. Null when the repo is not linked. */
38
+ export function linkedProject(cwd) {
39
+ let dir = resolve(cwd || process.cwd());
40
+ for (;;) {
41
+ const p = join(dir, ".relay", "rules.json");
42
+ if (existsSync(p)) {
43
+ try {
44
+ const j = JSON.parse(readFileSync(p, "utf8"));
45
+ return j && typeof j.project === "string" ? { root: dir, project: j.project } : null;
46
+ } catch {
47
+ return null;
48
+ }
49
+ }
50
+ const up = dirname(dir);
51
+ if (up === dir) return null;
52
+ dir = up;
53
+ }
54
+ }
55
+
56
+ const sha256 = (s) => createHash("sha256").update(s).digest("hex");
57
+ const safe = (s) => s.replace(/[^A-Za-z0-9_.-]+/g, "_").slice(0, 60);
58
+
59
+ /** Same layout as packages/core/src/hooks/cache.ts: <RELAY_HOME>/cache/brief/<project>-<sha(key)[0:12]>.json */
60
+ export function briefCachePath(project, key) {
61
+ return join(RELAY_HOME, "cache", "brief", `${safe(project)}-${sha256(key).slice(0, 12)}.json`);
62
+ }
63
+
64
+ /** Same key as packages/cli/src/commands/brief.ts briefCacheKey(). */
65
+ export const briefCacheKey = (intent, maxTokens, model = "", lane = "") => `${intent}|${maxTokens}|${model}|${lane}`;
66
+
67
+ export function readCachedBrief(project, key) {
68
+ const p = briefCachePath(project, key);
69
+ if (!existsSync(p)) return undefined;
70
+ try {
71
+ const j = JSON.parse(readFileSync(p, "utf8"));
72
+ return Date.now() - j.ts > BRIEF_TTL_MS ? undefined : j;
73
+ } catch {
74
+ return undefined;
75
+ }
76
+ }
77
+
78
+ /** The command line that runs the relay CLI with this node: dist/relay.js in the package; the repo's tsx and packages/cli/src/main.ts in a checkout. */
79
+ export function relayArgv(args) {
80
+ if (existsSync(BUNDLED_CLI)) return [process.execPath, [BUNDLED_CLI, ...args]];
81
+ const tsx = createRequire(import.meta.url).resolve("tsx/cli");
82
+ return [process.execPath, [tsx, CLI_MAIN, ...args]];
83
+ }
84
+
85
+ /** Run the relay CLI synchronously; returns stdout ("" on any failure or timeout). */
86
+ export function runRelay(args, timeoutMs) {
87
+ const [bin, argv] = relayArgv(args);
88
+ const r = spawnSync(bin, argv, { encoding: "utf8", timeout: timeoutMs, env: { ...process.env, RELAY_HOOK: "1" }, maxBuffer: 4 * 1024 * 1024, stdio: ["ignore", "pipe", "pipe"] });
89
+ if (r.error || r.status !== 0) {
90
+ if (process.env.RELAY_HOOK_DEBUG) process.stderr.write(`[relay hook] ${r.error ? r.error.message : `exit ${r.status}`}: ${(r.stderr || "").slice(0, 500)}\n`);
91
+ return "";
92
+ }
93
+ return r.stdout || "";
94
+ }
95
+
96
+ /** Start the relay CLI detached, output appended to <RELAY_HOME>/cache/<logName>; the hook returns at once. */
97
+ export function spawnRelayDetached(args, logName) {
98
+ const dir = join(RELAY_HOME, "cache");
99
+ mkdirSync(dir, { recursive: true });
100
+ const out = openSync(join(dir, logName), "a");
101
+ const [bin, argv] = relayArgv(args);
102
+ const child = spawn(bin, argv, { detached: true, stdio: ["ignore", out, out], env: { ...process.env, RELAY_HOOK: "1" } });
103
+ child.unref();
104
+ return child.pid;
105
+ }
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ // SessionEnd (Claude Code, Codex) / Stop (Grok Build) hook: run `relay capture` on the session transcript, detached,
3
+ // so the session never waits on the Sonnet call. Output goes to <RELAY_HOME>/cache/capture.log. Per-turn Stop
4
+ // hooks are cheap because capture keeps a byte offset per transcript and only reads the new turns.
5
+ // Payload (stdin JSON) fields used: transcript_path (or rollout_path / session_path), session_id, cwd.
6
+ import { existsSync } from "node:fs";
7
+ import { cliName, linkedProject, readPayload, spawnRelayDetached } from "./_lib.mjs";
8
+
9
+ const payload = readPayload();
10
+ const link = linkedProject(payload.cwd || process.cwd());
11
+ if (!link) process.exit(0);
12
+ const transcript = payload.transcript_path ?? payload.rollout_path ?? payload.session_path ?? payload.transcript;
13
+ if (typeof transcript !== "string" || !existsSync(transcript)) process.exit(0);
14
+
15
+ const args = ["capture", "--hook", "--transcript", transcript, "--project", link.project, "--cwd", link.root, "--source", cliName()];
16
+ if (payload.session_id) args.push("--session", String(payload.session_id));
17
+ spawnRelayDetached(args, "capture.log");
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ // SessionStart hook (Claude Code, Codex, Grok Build): print the project's brief so it lands in the session's
3
+ // context. Budget: 2.5K tokens. Cached per project for ten minutes, so most starts never spawn the CLI.
4
+ // Silent when the cwd is not a linked repo. Payload (stdin JSON) fields used: cwd.
5
+ import { briefCacheKey, cliName, linkedProject, readCachedBrief, readPayload, runRelay } from "./_lib.mjs";
6
+
7
+ const INTENT = "session start";
8
+ const MAX_TOKENS = 2500;
9
+
10
+ const payload = readPayload();
11
+ const link = linkedProject(payload.cwd || process.cwd());
12
+ if (!link) process.exit(0);
13
+
14
+ const lane = cliName();
15
+ const cached = readCachedBrief(link.project, briefCacheKey(INTENT, MAX_TOKENS, "", lane));
16
+ const text = cached ? cached.text : runRelay(["brief", "--hook", "--project", link.project, "--cwd", link.root, "--max-tokens", String(MAX_TOKENS), "--lane", lane, "--", INTENT], 15_000);
17
+ if (text.trim()) process.stdout.write(`# relay brief for ${link.project}\n\n${text.trimEnd()}\n`);
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env node
2
+ // Claude Code status line (settings.json `statusLine.command`, installed by `relay setup`). Claude Code passes a JSON
3
+ // document on stdin on every refresh; for claude.ai Pro/Max logins it carries `rate_limits.five_hour` and
4
+ // `rate_limits.seven_day` as { used_percentage, resets_at } (unix seconds), the only documented source of the plan
5
+ // meters the web app's header shows. This script:
6
+ // 1. saves them to <RELAY_HOME>/meters/claude.json (atomic write, 0600; the directory 0700) when present;
7
+ // 2. prints the status line: the command that was there before `relay setup` (recorded in
8
+ // <RELAY_HOME>/statusline.prev.json) is run with the same stdin and its output passed through, so a user's own
9
+ // status line keeps working; otherwise a compact default: `<model> · <cwd> · 5h 42% · 7d 44%`.
10
+ // Nothing here can break a session: on any error it prints nothing and exits 0. Stays dependency-free and reads no
11
+ // other file than those two, because it runs on every refresh.
12
+ import { spawnSync } from "node:child_process";
13
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
14
+ import { homedir } from "node:os";
15
+ import { basename, join } from "node:path";
16
+
17
+ const RELAY_HOME = process.env.RELAY_HOME ?? join(homedir(), ".harness");
18
+ const METERS_DIR = join(RELAY_HOME, "meters");
19
+ const PREV_PATH = join(RELAY_HOME, "statusline.prev.json");
20
+
21
+ function main() {
22
+ let raw = "";
23
+ try {
24
+ raw = readFileSync(0, "utf8");
25
+ } catch {
26
+ return;
27
+ }
28
+ let payload;
29
+ try {
30
+ payload = JSON.parse(raw);
31
+ } catch {
32
+ return;
33
+ }
34
+ if (!payload || typeof payload !== "object") return;
35
+
36
+ const limits = payload.rate_limits;
37
+ let meters = null;
38
+ if (limits && typeof limits === "object") {
39
+ meters = { subscription: "max", five_hour: windowOf(limits.five_hour), seven_day: windowOf(limits.seven_day), captured_at: new Date().toISOString() };
40
+ try {
41
+ writeMeters(meters);
42
+ } catch {
43
+ /* a read-only home: the status line still prints */
44
+ }
45
+ }
46
+
47
+ const prev = previousCommand();
48
+ if (prev) {
49
+ const cwd = typeof payload.cwd === "string" && existsSync(payload.cwd) ? payload.cwd : undefined;
50
+ const r = spawnSync(prev, { shell: true, input: raw, encoding: "utf8", timeout: 5000, env: process.env, ...(cwd ? { cwd } : {}), stdio: ["pipe", "pipe", "ignore"] });
51
+ if (!r.error && typeof r.stdout === "string") process.stdout.write(r.stdout);
52
+ return;
53
+ }
54
+ const parts = [];
55
+ const model = payload.model && typeof payload.model.display_name === "string" ? payload.model.display_name : "";
56
+ if (model) parts.push(model);
57
+ const dir = (payload.workspace && typeof payload.workspace.current_dir === "string" && payload.workspace.current_dir) || (typeof payload.cwd === "string" ? payload.cwd : "");
58
+ if (dir) parts.push(basename(dir));
59
+ if (meters?.five_hour) parts.push(`5h ${meters.five_hour.used_percentage}%`);
60
+ if (meters?.seven_day) parts.push(`7d ${meters.seven_day.used_percentage}%`);
61
+ if (parts.length) process.stdout.write(parts.join(" · ") + "\n");
62
+ }
63
+
64
+ /** { used_percentage, resets_at } with the percentage clamped to 0..100, or null when the window is absent. */
65
+ function windowOf(w) {
66
+ if (!w || typeof w !== "object" || typeof w.used_percentage !== "number" || !Number.isFinite(w.used_percentage)) return null;
67
+ const resets = typeof w.resets_at === "number" && Number.isFinite(w.resets_at) ? w.resets_at : null;
68
+ return { used_percentage: Math.max(0, Math.min(100, Math.round(w.used_percentage))), resets_at: resets };
69
+ }
70
+
71
+ /** Write <METERS_DIR>/claude.json: temp file beside it, 0600, then rename, so a reader never sees half a file. */
72
+ function writeMeters(meters) {
73
+ mkdirSync(METERS_DIR, { recursive: true, mode: 0o700 });
74
+ const target = join(METERS_DIR, "claude.json");
75
+ const tmp = join(METERS_DIR, `.claude.${process.pid}.tmp`);
76
+ writeFileSync(tmp, JSON.stringify(meters) + "\n", { mode: 0o600 });
77
+ chmodSync(tmp, 0o600);
78
+ renameSync(tmp, target);
79
+ }
80
+
81
+ /** The status-line command `relay setup` replaced, if it recorded one. */
82
+ function previousCommand() {
83
+ if (!existsSync(PREV_PATH)) return undefined;
84
+ try {
85
+ const j = JSON.parse(readFileSync(PREV_PATH, "utf8"));
86
+ return j && typeof j.command === "string" && j.command.trim() ? j.command : undefined;
87
+ } catch {
88
+ return undefined;
89
+ }
90
+ }
91
+
92
+ try {
93
+ main();
94
+ } catch {
95
+ /* never break the session */
96
+ }
97
+ process.exitCode = 0;
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+ // UserPromptSubmit hook (Claude Code, Grok Build; Codex has no such hook): print the decisions and preferences
3
+ // that match the prompt so they are in context before the model answers. Budget: 1K tokens. Only runs in a linked
4
+ // repo, and only for prompts long enough to be about something (short acknowledgements and slash commands skip).
5
+ // Payload (stdin JSON) fields used: prompt, cwd.
6
+ import { cliName, linkedProject, readPayload, runRelay } from "./_lib.mjs";
7
+
8
+ const MAX_TOKENS = 1000;
9
+ const MIN_PROMPT_CHARS = 20;
10
+
11
+ const payload = readPayload();
12
+ const link = linkedProject(payload.cwd || process.cwd());
13
+ if (!link) process.exit(0);
14
+ const prompt = String(payload.prompt ?? payload.user_prompt ?? payload.input ?? "").trim();
15
+ if (prompt.length < MIN_PROMPT_CHARS || prompt.startsWith("/")) process.exit(0);
16
+
17
+ const text = runRelay(["recall", "--hook", "--project", link.project, "--cwd", link.root, "--max-tokens", String(MAX_TOKENS), "--lane", cliName(), "--", prompt.slice(0, 2000)], 10_000);
18
+ if (text.trim()) process.stdout.write(text);