@agent-relay/core-bridge 0.0.0-stage → 18.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,185 @@
1
- # Temporary Holding Version
1
+ # @agent-relay/core-bridge
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
+ A Node client for the local Agent Relay core's bridge: JSON-RPC 2.0 over
4
+ newline-delimited JSON, on a Unix socket (macOS, Linux) or a named pipe
5
+ (Windows). It is the client the `agent-relay` CLI uses to find, greet and drive
6
+ the core that the Agent Relay desktop app or `agent-relay init` started.
7
+
8
+ ESM only, Node 22 or later, no runtime dependencies.
9
+
10
+ ```ts
11
+ import { connectCore, spawnTargets } from '@agent-relay/core-bridge';
12
+
13
+ await using client = await connectCore();
14
+ console.log(client.hello.daemon_version, client.hello.methods);
15
+ const status = await client.call('status.get');
16
+ ```
17
+
18
+ ## Connecting
19
+
20
+ - `connectCore(opts?)` resolves the socket, checks it (see Security), connects,
21
+ sends `hello` with this package's `BRIDGE_VERSION`, checks the greeting and
22
+ returns a `CoreClient`. It throws a typed error on any failure.
23
+ - `tryConnectCore(opts?)` is the same, but resolves `undefined` when no core is
24
+ running (`CoreNotRunningError`). Every other failure still throws, so a
25
+ refused or impostor socket never looks like "no core, start one".
26
+ - Options: `socket` (default `coreSocketPath(env, home)`), `env`, `home`,
27
+ `connectTimeoutMs` and `callTimeoutMs` (both default 15 000 ms), and `signal`
28
+ (aborts connecting; once connected, aborting closes the client).
29
+ - `coreSocketPath(env?, home?)` returns `$AGENT_RELAY_CORE_SOCKET` when set, or
30
+ `~/.agentworkforce/desktop/core.sock`. `pipeName(socket)` returns the Windows pipe the
31
+ core binds for that path.
32
+
33
+ ## CoreClient
34
+
35
+ - `hello`: the frozen greeting (`bridge_version`, `daemon_version`, `pid`,
36
+ `methods`, `topics`). Feature-detect with `hello.methods.includes(...)`.
37
+ - `call(method, params?, { timeoutMs?, signal? })`: one request; resolves with
38
+ `result`, rejects with a typed error. A timeout or abort abandons that call
39
+ only; the connection stays open and a late reply is ignored.
40
+ - `subscribe(topics)` / `unsubscribe(topics)`: topics are `status`, `activity`,
41
+ `shutdown`, `invalidated`, `notify` and `sign_in`.
42
+ - `onEvent(listener)` / `onClose(listener)`: return a function that removes the
43
+ listener.
44
+ - `closed`, `close()`, and `[Symbol.asyncDispose]()` for `await using`.
45
+
46
+ ### Events
47
+
48
+ A line with `method: "event"` and no `id` is delivered to `onEvent` listeners as
49
+ `{ topic, seq, data }`. Events arrive only for subscribed topics. Other
50
+ notifications and unparseable lines are ignored, so new server notifications do
51
+ not break this client. A listener that throws does not stop the read loop. A
52
+ `shutdown` event is followed by the core closing the connection, which fires
53
+ `onClose`.
54
+
55
+ ### Ordering
56
+
57
+ The core answers one connection's requests in order. `spawn.invoke` makes
58
+ network calls and can take a while, so a caller that also polls (for example
59
+ `spawn.status` or `status.get`) should open a second `connectCore` for the slow
60
+ calls. The package does not pool connections.
61
+
62
+ ## Size limits
63
+
64
+ These limits are new compared with the client that used to live in the CLI:
65
+
66
+ - **Replies: 16 MiB per line** (`MAX_REPLY_BYTES`, the core's own reply cap). A
67
+ buffered line over this size closes the connection: pending calls and the
68
+ `onClose` listeners receive `CoreReplyTooLargeError`. Open a new connection
69
+ afterwards. Before, the buffer grew without bound.
70
+ - **Requests: 1 MiB per line** (`MAX_REQUEST_BYTES`, the core's `MAX_FRAME_BYTES`),
71
+ measured in UTF-8 bytes of the serialized request. A larger request is
72
+ refused locally with `CoreRequestTooLargeError` and nothing is sent; the
73
+ connection stays usable. Before, the core answered `invalid_request` and
74
+ dropped the connection.
75
+
76
+ ## Errors
77
+
78
+ Every error extends `CoreBridgeError` and carries a `code`:
79
+
80
+ | Class | `code` | When |
81
+ | ---------------------------------------------------------------------- | ------------------------- | ------------------------------------------------------------------------------------------- |
82
+ | `CoreNotRunningError` | `core_not_running` | no socket file (not on Windows), nothing listening, or connect timed out |
83
+ | `CoreUntrustedError` (`reason`) | `core_untrusted` | the socket's directory or the socket fails the owner/mode checks |
84
+ | `NotACoreError` | `not_a_core` | the greeting is not a core's (no numeric `bridge_version`/`pid`, or another bridge version) |
85
+ | `BridgeVersionMismatchError` (`clientVersion`, `coreMessage`) | `bridge_version_mismatch` | the core refused this bridge version |
86
+ | `CoreBridgeError` | `handshake_failed` | `hello` failed for any other reason |
87
+ | `CoreRpcError` (`rpcCode`, `kind`, `retryable`, `planLimit`, `reason`) | `rpc_error` | any JSON-RPC error reply |
88
+ | `CoreTimeoutError` (`method`) | `timeout` | no reply in time |
89
+ | `CoreReplyTooLargeError` | `reply_too_large` | see Size limits |
90
+ | `CoreRequestTooLargeError` (`method`, `bytes`, `limit`) | `request_too_large` | see Size limits |
91
+ | `CoreClosedError` | `closed` | a call after close, or the connection closed or failed with calls pending |
92
+ | `CoreBridgeError` | `invalid_params` | a spawn helper refused its params locally |
93
+
94
+ `CoreRpcError.kind` is the core's `data.kind` (`ErrorKind`; unknown kinds are
95
+ passed through as strings). With kind `refused`, `CoreRpcError.reason` is the
96
+ core's `data.reason` when it gave one (`RefusalReason`: `service_unknown`,
97
+ `service_disabled`, `service_expired`, `workspace_mismatch`, `not_owner`,
98
+ `outside_scope`, `management_peer`; unknown reasons are passed through as
99
+ strings) and `undefined` otherwise. `CoreCallError` is a deprecated alias of
100
+ `CoreRpcError` and will be removed in a later release.
101
+
102
+ ## Native spawn controls
103
+
104
+ `spawnTargets`, `spawnInvoke`, `spawnStatus` and `spawnRelease` wrap
105
+ `spawn.targets`, `spawn.invoke`, `spawn.status` and `spawn.release` with types
106
+ copied from the core's contract. Each helper:
107
+
108
+ - throws `CoreRpcError` with kind `method_not_found` before sending anything
109
+ when `hello.methods` lacks the method;
110
+ - checks params with the core's rules (name segments `^[A-Za-z0-9_-]{1,200}$`,
111
+ idempotency keys at least 16 characters, a task that is non-empty and at most
112
+ 64 KiB, an absolute directory with no NUL) and throws `CoreBridgeError`
113
+ `invalid_params` naming the field, never its value;
114
+ - sends exactly the contract's keys, since the core refuses unknown fields;
115
+ - returns the invocation with `released` read strictly: `true` only when the
116
+ core reported the provider released the agent, `false` when absent (an
117
+ older core) or anything else. It is never derived from `status`, so a
118
+ `completed` release is not by itself a confirmed one. `isReleaseConfirmed`
119
+ makes that check on any reply.
120
+
121
+ Each helper accepts per-call timeout and cancellation options. `spawn.invoke`
122
+ and `spawn.release` take `actionTimeoutMs`, which defaults to six minutes
123
+ (`DEFAULT_SPAWN_ACTION_TIMEOUT_MS`) because verified startup and exact cleanup
124
+ can legitimately exceed the bridge client's 15-second call deadline; that
125
+ deadline still governs every other call.
126
+
127
+ The core stays authoritative. Rules a caller must know:
128
+
129
+ - A session caller passes `caller_name`, which must be an active local
130
+ registration of this core with a stored token. The core uses that
131
+ registration; no token crosses the bridge.
132
+ - A service caller binds its connection first and then passes no caller:
133
+
134
+ ```ts
135
+ const credential = await readCallerCredential('/path/to/caller.json');
136
+ await authenticate(client, credential); // spawn_callers.challenge + .authenticate
137
+ await spawnInvoke(client, { node_id, node_name, name, harness, task, directory, idempotency_key });
138
+ ```
139
+
140
+ `authenticate` answers a single-use challenge with
141
+ `HMAC-SHA256(SHA-256(secret), transcript)`. A connection binds once; three
142
+ failed attempts lock it (`auth_locked`), so open a new connection.
143
+
144
+ - No params carry a credential. A `caller_secret` key is refused locally
145
+ (`legacy_credential_refused`) before anything is sent, and by the core.
146
+ - `spawn.invoke` targets only this computer's own spawn node, which must be
147
+ live, have `handlers_live`, not be stale, and advertise `spawn:<harness>`.
148
+ - Persist idempotency keys (`newIdempotencyKey()` makes one) and reuse them on
149
+ retry.
150
+ - `spawn.status` fills in `agent_id`, `name` and `node_id` only for spawns made on
151
+ this core.
152
+
153
+ ## Versioning
154
+
155
+ `BRIDGE_VERSION` is the wire contract. The core changes it only when something
156
+ is removed, renamed or changes meaning; new methods, params, result fields,
157
+ topics and error kinds do not change it, so feature-detect with `hello.methods`.
158
+ The core speaks exactly one bridge version and this client never downgrades. The
159
+ package version moves in lockstep with the relay repository; a `BRIDGE_VERSION`
160
+ bump is a semver-major release of this package.
161
+
162
+ ## Security
163
+
164
+ - On macOS and Linux, before connecting: the socket's directory (and its
165
+ symlink, if any) must be owned by you and not group- or world-writable, and
166
+ the socket must be a socket owned by you with mode 0600. This stands in for
167
+ peer credentials, which Node cannot read. The core itself also drops any peer
168
+ whose uid differs from its own.
169
+ - Any failure other than "not running" throws, so callers never start a second
170
+ core next to a refused one.
171
+ - **Windows gap (accepted):** there are no file checks. The pipe's DACL admits
172
+ only the current user, refuses remote clients and holds the name exclusively,
173
+ but unlike the Rust clients this package cannot verify that the pipe's
174
+ _server_ runs as the current user without native code.
175
+ - No credential crosses this client: `authenticate` sends a caller id and an
176
+ HMAC, never the secret or its key, and `CallerCredential` prints as
177
+ `[redacted]`. It never logs params or replies (a spawn task can hold user
178
+ text).
179
+ - `readCallerCredential` refuses, on macOS and Linux, a `caller.json` that is a
180
+ symlink, not a regular file, not owned by you, has any group or other
181
+ permission bit, sits in a group- or world-writable directory that is not
182
+ sticky, or is over 64 KiB. **Windows gap:** Node cannot read access lists,
183
+ so on Windows it checks only that the path is absolute, not a link or
184
+ reparse point, a regular file and at most 64 KiB; it relies on the per-user
185
+ profile's access list that Agent Relay Desktop writes the file under.
package/dist/auth.d.ts ADDED
@@ -0,0 +1,147 @@
1
+ import { inspect } from 'node:util';
2
+ import type { CallOptions, CoreClient } from './client.js';
3
+ /** The transcript version byte, which is also the challenge `version`. */
4
+ export declare const CALLER_TRANSCRIPT_VERSION = 1;
5
+ /** The transcript's domain separation string. */
6
+ export declare const CALLER_TRANSCRIPT_DOMAIN = "agent-relay/service-caller/v1";
7
+ /** How long a challenge stays valid after it was issued, in milliseconds. */
8
+ export declare const CALLER_CHALLENGE_TTL_MS = 30000;
9
+ /** The `caller.json` `auth` value naming this transcript. */
10
+ export declare const CALLER_AUTH_SCHEME = "challenge-hmac-sha256/v1";
11
+ /** The `caller.json` schemas this reader accepts. */
12
+ export declare const CALLER_FILE_SCHEMAS: readonly ["agent-relay-service-caller/1", "agent-relay-service-caller/2"];
13
+ /** The largest `caller.json` this reader opens, in bytes. */
14
+ export declare const MAX_CALLER_FILE_BYTES: number;
15
+ /** The params of `spawn_callers.challenge`. */
16
+ export type CallerChallengeParams = {
17
+ /** The caller's registry id: `sc_` and 16 lowercase hex characters. */
18
+ caller_id: string;
19
+ };
20
+ /** The result of `spawn_callers.challenge`. */
21
+ export interface CallerChallenge {
22
+ /** Exactly 1: the transcript version byte. */
23
+ version: number;
24
+ /** `ch_` and 32 lowercase hex characters. */
25
+ challenge_id: string;
26
+ /** 32 random bytes in base64url without padding (43 characters). */
27
+ nonce: string;
28
+ /** Unix milliseconds on Desktop's clock. */
29
+ issued_at_ms: number;
30
+ /** `issued_at_ms + 30000`. */
31
+ expires_at_ms: number;
32
+ }
33
+ /** The params of `spawn_callers.authenticate`. */
34
+ export type CallerAuthenticateParams = {
35
+ /** The `challenge_id` of the challenge being answered. */
36
+ challenge_id: string;
37
+ /** The HMAC-SHA256 authenticator in base64url without padding (43 characters). */
38
+ authenticator: string;
39
+ };
40
+ /** The result of `spawn_callers.authenticate`: the connection is now bound. */
41
+ export interface CallerBound {
42
+ caller_id: string;
43
+ /** The caller's display name: 1 to 200 of `A-Z a-z 0-9 _ -`. */
44
+ caller_name: string;
45
+ /** The record's authority generation, from 1 to 2^53 - 1. */
46
+ authority_generation: number;
47
+ }
48
+ /** Every value the version 1 transcript covers. */
49
+ export interface CallerTranscriptInput {
50
+ challengeId: string;
51
+ /** The 32 raw nonce bytes. */
52
+ nonce: Uint8Array;
53
+ callerId: string;
54
+ siteUrl: string;
55
+ workspaceId: string;
56
+ userId: string;
57
+ issuedAtMs: number;
58
+ expiresAtMs: number;
59
+ }
60
+ /**
61
+ * Builds the exact version 1 transcript bytes: the version byte, then each
62
+ * field with a big-endian u16 length prefix.
63
+ * @param input - The challenge fields and the caller's own `caller.json` scope.
64
+ * @returns The transcript bytes the authenticator covers.
65
+ * @throws CoreBridgeError `invalid_params` when a value is outside its bound.
66
+ */
67
+ export declare function callerTranscript(input: CallerTranscriptInput): Buffer;
68
+ /**
69
+ * A caller's credential as read from `caller.json`. It holds the derived key,
70
+ * never the secret, and prints as `[redacted]`: it cannot be logged or
71
+ * serialised by accident.
72
+ */
73
+ export declare class CallerCredential {
74
+ #private;
75
+ /** The caller's registry id, which is sent as the challenge param. */
76
+ readonly callerId: string;
77
+ /** `workspace.site_url`, used only in the transcript. */
78
+ readonly siteUrl: string;
79
+ /** `workspace.workspace_id`, used only in the transcript. */
80
+ readonly workspaceId: string;
81
+ /** `account.user_id`, used only in the transcript. */
82
+ readonly userId: string;
83
+ private constructor();
84
+ /**
85
+ * Checks a parsed `caller.json` document and derives its key.
86
+ * @param document - The parsed `caller.json` contents.
87
+ * @returns The credential, holding `SHA-256(secret)` and not the secret.
88
+ * @throws CoreBridgeError `caller_file_invalid` when the document does not
89
+ * have the `caller.json` shape. The message never contains the secret.
90
+ */
91
+ static fromDocument(document: unknown): CallerCredential;
92
+ /**
93
+ * Computes the authenticator for one challenge.
94
+ * @param challenge - The challenge exactly as `spawn_callers.challenge` returned it.
95
+ * @returns The HMAC-SHA256 authenticator in base64url without padding.
96
+ * @throws CoreBridgeError `invalid_reply` when the challenge is malformed.
97
+ */
98
+ authenticatorFor(challenge: CallerChallenge): string;
99
+ /**
100
+ * Keeps the key out of JSON.
101
+ * @returns A placeholder.
102
+ */
103
+ toJSON(): string;
104
+ /**
105
+ * Keeps the key out of string conversion.
106
+ * @returns A placeholder.
107
+ */
108
+ toString(): string;
109
+ /**
110
+ * Keeps the key out of `console.log` and `util.inspect`.
111
+ * @returns A placeholder.
112
+ */
113
+ [inspect.custom](): string;
114
+ }
115
+ /**
116
+ * Binds a bridge connection to a service caller: one challenge and one
117
+ * authenticate. After it returns, `spawn.invoke`, `spawn.status` and
118
+ * `spawn.release` on this connection act as the caller and name no caller.
119
+ * Failures are the core's typed errors (`CoreRpcError`), for example
120
+ * `auth_failed`, `auth_locked`, `already_bound` or `challenge_outstanding`.
121
+ * @param client - A greeted connection that has not been bound yet.
122
+ * @param credential - The credential read from `caller.json`.
123
+ * @param options - Optional timeout and cancellation controls for each of
124
+ * the two calls; the default is the client's call timeout (15 seconds).
125
+ * @returns The bound caller.
126
+ */
127
+ export declare function authenticate(client: CoreClient, credential: CallerCredential, options?: CallOptions): Promise<CallerBound>;
128
+ /**
129
+ * Reads `caller.json` securely and returns its credential.
130
+ *
131
+ * On macOS and Linux the file must be a regular file (not a symlink), owned
132
+ * by this user, with no group or other permission bits (0600 or stricter),
133
+ * in a directory that is not group- or world-writable unless it is sticky;
134
+ * it is opened with `O_NOFOLLOW`.
135
+ *
136
+ * On Windows the path must be absolute, the file must not be a symlink or
137
+ * reparse point (its real path must be itself), and it must be a regular
138
+ * file. Node has no API to read a Windows access list, so the reader cannot
139
+ * verify the file's DACL or owner; it relies on the per-user profile's
140
+ * access list that Desktop writes the file under.
141
+ * @param file - The absolute path of `caller.json`.
142
+ * @returns The credential, holding the derived key and not the secret.
143
+ * @throws CoreBridgeError `caller_file_unsafe` when the file fails a check
144
+ * above, `caller_file_invalid` when its contents are malformed.
145
+ */
146
+ export declare function readCallerCredential(file: string): Promise<CallerCredential>;
147
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAwBA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,OAAO,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAG3D,0EAA0E;AAC1E,eAAO,MAAM,yBAAyB,IAAI,CAAC;AAC3C,iDAAiD;AACjD,eAAO,MAAM,wBAAwB,kCAAkC,CAAC;AACxE,6EAA6E;AAC7E,eAAO,MAAM,uBAAuB,QAAS,CAAC;AAC9C,6DAA6D;AAC7D,eAAO,MAAM,kBAAkB,6BA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