@byokit/herdr 0.1.0-next.dbe7142

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.
Files changed (50) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/LICENSE +202 -0
  3. package/README.md +18 -0
  4. package/dist/agents.d.ts +7 -0
  5. package/dist/agents.js +141 -0
  6. package/dist/approvals.d.ts +24 -0
  7. package/dist/approvals.js +81 -0
  8. package/dist/cli.d.ts +10 -0
  9. package/dist/cli.js +89 -0
  10. package/dist/close.d.ts +4 -0
  11. package/dist/close.js +85 -0
  12. package/dist/constants.d.ts +2 -0
  13. package/dist/constants.js +5 -0
  14. package/dist/device.d.ts +40 -0
  15. package/dist/device.js +128 -0
  16. package/dist/generated/events.d.ts +371 -0
  17. package/dist/generated/events.js +3 -0
  18. package/dist/generated/methods.d.ts +2299 -0
  19. package/dist/generated/methods.js +3 -0
  20. package/dist/generated/report.json +50 -0
  21. package/dist/index.d.ts +3 -0
  22. package/dist/index.js +4 -0
  23. package/dist/kit.d.ts +73 -0
  24. package/dist/kit.js +209 -0
  25. package/dist/link.d.ts +24 -0
  26. package/dist/link.js +324 -0
  27. package/dist/notices.d.ts +14 -0
  28. package/dist/notices.js +88 -0
  29. package/dist/socket.d.ts +2 -0
  30. package/dist/socket.js +137 -0
  31. package/dist/supervise.d.ts +17 -0
  32. package/dist/supervise.js +137 -0
  33. package/dist/terminal.d.ts +6 -0
  34. package/dist/terminal.js +105 -0
  35. package/dist/testing/contract.d.ts +9 -0
  36. package/dist/testing/contract.js +308 -0
  37. package/dist/testing/fake-herdr/bin.d.ts +5 -0
  38. package/dist/testing/fake-herdr/bin.js +210 -0
  39. package/dist/testing/fake-herdr/server.d.ts +21 -0
  40. package/dist/testing/fake-herdr/server.js +604 -0
  41. package/dist/testing/fake-herdr/world.d.ts +84 -0
  42. package/dist/testing/fake-herdr/world.js +85 -0
  43. package/dist/testing/index.d.ts +4 -0
  44. package/dist/testing/index.js +7 -0
  45. package/dist/types.d.ts +115 -0
  46. package/dist/types.js +3 -0
  47. package/dist/words.d.ts +10 -0
  48. package/dist/words.js +18 -0
  49. package/dist/words.json +19 -0
  50. package/package.json +60 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,17 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ - FIX docs drift (K10): README pins the v0.9.1 snapshot (protocol 22) instead of the H1
6
+ protocol placeholder; `agents.ts` agrees muxr sends `target_pane_id` to `pane.split`; the
7
+ fake bin's `api schema` reports the pinned identity with no placeholder text.
8
+
9
+ - `adopt` mode takes `env` and `path` like `own`, merged into the `cli()`/`terminal()` env (so `HOME`,
10
+ `HERDR_CLIENT_SOCKET_PATH`, `HERDR_SESSION` and a `#!/usr/bin/env node` bin work); `TerminalSession.pause()`/`resume()`
11
+ apply backpressure to the Herdr child instead of buffering frames in the host.
12
+ - FIX: the packed `dist/words.d.ts` keeps `with { type: 'json' }` on its `./words.json` import, so a strict NodeNext consumer with `skipLibCheck: false` no longer fails with TS1543.
13
+
14
+ - Scaffold (docs/runtime-kits.md §11.3 H1): frozen public types, kit facade, internal seams and words. Behavior
15
+ lands in H2–H8; `HERDR_PROTOCOL` is a placeholder until the schema snapshot (H2).
16
+ - Wire `HerdrKit.cli`/`terminal` to `runCli`/`openTerminal` with the supervisor env (6.5), export
17
+ `./testing`, and run `herdrContract` against `startFakeHerdr` in `test/contract.test.ts`.
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 [yyyy] [name of copyright owner]
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 ADDED
@@ -0,0 +1,18 @@
1
+ # @byokit/herdr
2
+
3
+ Drive the Herdr already on this computer — workspaces, tabs, panes, coding agents and blocked-approval answers —
4
+ from an app, or hand it to a phone over [`@byokit/link`](../link). Each agent inside Herdr keeps its own
5
+ subscription login; the kit never sees a credential.
6
+
7
+ Two ways in: `adopt` talks to the socket path the app passes (the person's own Herdr, nothing spawned, nothing
8
+ written), `own` runs the Herdr binary the app names in an app-owned state directory. Helpers cover the common
9
+ paths (start an agent, deliver a prompt with a receipt, watch blocked agents, exact closes); `call` and
10
+ `subscribe` are typed pass-throughs to the complete socket API, and `cli()` reaches the full CLI.
11
+
12
+ **Status:** pinned to Herdr v0.9.1 — the schema snapshot (`schema/herdr-api-0.9.1.json`,
13
+ protocol 22) generates the typed surface (`src/generated/`, `HERDR_PROTOCOL` in `src/constants.ts`).
14
+ See [docs/runtime-kits.md](../../docs/runtime-kits.md) §11.3 for the work packages.
15
+
16
+ Herdr itself is not an npm dependency; the app installs it (see herdr.dev) and passes `bin`. The kit reads no
17
+ environment variables, spawns processes with an explicit env only, and — like every byokit package — never
18
+ touches a person's other AI tools; its tests run against a fake Herdr.
@@ -0,0 +1,7 @@
1
+ import type { HerdrKit } from './kit.ts';
2
+ import type { HerdrSnapshot } from './types.ts';
3
+ export type Call = (method: string, params: Record<string, unknown>, timeoutMs?: number) => Promise<unknown>;
4
+ export declare function createAgents(ctx: {
5
+ call: Call;
6
+ snapshot(): HerdrSnapshot;
7
+ }): Pick<HerdrKit, 'startAgent' | 'prompt' | 'sendKeys' | 'wait' | 'read' | 'agentKinds' | 'installedAgentKinds'>;
package/dist/agents.js ADDED
@@ -0,0 +1,141 @@
1
+ // Agent helpers: placements, prompt receipts, waits and reads (docs/runtime-kits.md 6.4).
2
+ // Exact param spellings come from the generated v0.9.1 table (6.7); where muxr and the schema
3
+ // disagree the schema wins. `pane.split` takes `target_pane_id` (muxr agrees), and `agent.start`
4
+ // has no `env` param — a start's env belongs to the placement create/split call (src/generated/methods.ts).
5
+ import { accessSync, constants as fsConstants } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ const PROMPTABLE = ['idle', 'working', 'blocked', 'done'];
8
+ const DEFAULT_TIMEOUT_MS = 60_000;
9
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
10
+ const fail = (code, message) => Object.assign(new Error(message), { code });
11
+ function agentOf(snapshot, paneId) {
12
+ for (const w of snapshot.workspaces)
13
+ for (const t of w.tabs)
14
+ for (const p of t.panes) {
15
+ if (p.id === paneId)
16
+ return p.agent;
17
+ }
18
+ return undefined;
19
+ }
20
+ // `agent.start` requires a name matching /^[a-z][a-z0-9_-]{0,31}$/; derive one from the kind when absent.
21
+ function agentName(o) {
22
+ const slug = (o.name ?? o.kind).toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^[-_0-9]+/, '').slice(0, 32);
23
+ return /^[a-z]/.test(slug) ? slug : `a-${slug}`.slice(0, 32);
24
+ }
25
+ function rootPaneOf(result) {
26
+ const pane = isObj(result) ? result.root_pane : undefined;
27
+ return isObj(pane) && typeof pane.pane_id === 'string' ? pane.pane_id : undefined;
28
+ }
29
+ export function createAgents(ctx) {
30
+ const call = ctx.call;
31
+ // Every placement takes its pane id from the server's answer, never a prediction (6.4).
32
+ async function startAgent(o) {
33
+ const timeout = o.timeoutMs ?? DEFAULT_TIMEOUT_MS;
34
+ const env = o.env === undefined ? {} : { env: o.env };
35
+ let paneId;
36
+ if (o.worktree !== undefined) {
37
+ const made = await call('worktree.create', { cwd: o.cwd, branch: o.worktree.branch,
38
+ ...(o.worktree.base === undefined ? {} : { base: o.worktree.base }) });
39
+ const worktree = isObj(made?.worktree) ? made.worktree : undefined;
40
+ const checkout = typeof worktree?.checkout_path === 'string' ? worktree.checkout_path
41
+ : typeof worktree?.path === 'string' ? worktree.path : o.cwd;
42
+ // The pinned schema's worktree.create carries the fresh root pane; a server that leaves the
43
+ // new workspace empty gets its first tab opened in the checkout instead.
44
+ paneId = rootPaneOf(made) ?? rootPaneOf(await call('tab.create', {
45
+ workspace_id: made?.workspace?.workspace_id, cwd: checkout, focus: false, ...env,
46
+ }));
47
+ }
48
+ else if ('workspace' in o.place) {
49
+ paneId = rootPaneOf(await call('workspace.create', { cwd: o.cwd,
50
+ ...(o.place.label === undefined ? {} : { label: o.place.label }), focus: false, ...env }));
51
+ }
52
+ else if ('tab' in o.place) {
53
+ paneId = rootPaneOf(await call('tab.create', { workspace_id: o.place.workspaceId, cwd: o.cwd,
54
+ ...(o.place.label === undefined ? {} : { label: o.place.label }), focus: false, ...env }));
55
+ }
56
+ else if ('split' in o.place) {
57
+ const made = await call('pane.split', { target_pane_id: o.place.split,
58
+ direction: o.place.direction, focus: false, ...env });
59
+ paneId = typeof made?.pane?.pane_id === 'string' ? made.pane.pane_id : undefined;
60
+ }
61
+ else {
62
+ paneId = o.place.pane;
63
+ }
64
+ if (paneId === undefined)
65
+ throw new Error('herdr: the placement answered no pane id');
66
+ const name = agentName(o);
67
+ await call('agent.start', { pane_id: paneId, kind: o.kind, name,
68
+ ...(o.args === undefined ? {} : { args: o.args }), timeout_ms: timeout }, timeout + 5000);
69
+ return { paneId, name };
70
+ }
71
+ async function prompt(target, text, o) {
72
+ // The readiness gate reads the kit's own tree: a not-promptable agent is refused with no socket call.
73
+ const agent = agentOf(ctx.snapshot(), target.paneId);
74
+ if (agent === undefined || agent.launchPending === true || agent.interactiveReady === false
75
+ || !PROMPTABLE.includes(agent.status)) {
76
+ throw fail('agent-not-ready', 'That agent is not ready for a prompt yet.');
77
+ }
78
+ const wait = o?.wait === undefined ? undefined
79
+ : { timeout_ms: o.wait.timeoutMs, ...(o.wait.until === undefined ? {} : { until: o.wait.until }) };
80
+ let receipt;
81
+ try {
82
+ receipt = await call('agent.prompt', { target: target.paneId, text,
83
+ ...(wait === undefined ? {} : { wait }) });
84
+ }
85
+ catch (error) {
86
+ if (error?.code === 'agent_blocked') {
87
+ throw fail('agent-blocked', 'That agent is blocked and needs an answer before a new prompt.');
88
+ }
89
+ throw error;
90
+ }
91
+ const body = isObj(receipt) ? receipt : undefined;
92
+ const a = isObj(body?.agent) ? body.agent : undefined;
93
+ if (body?.type !== 'agent_prompted' || a === undefined
94
+ || typeof a.terminal_id !== 'string' || typeof a.agent_status !== 'string'
95
+ || typeof a.workspace_id !== 'string' || typeof a.tab_id !== 'string'
96
+ || typeof a.pane_id !== 'string' || typeof a.focused !== 'boolean'
97
+ || typeof a.revision !== 'number' || !Number.isSafeInteger(a.revision) || a.revision < 0
98
+ || a.pane_id !== target.paneId) {
99
+ throw new Error('Herdr did not queue the prompt.');
100
+ }
101
+ return { paneId: a.pane_id, terminalId: a.terminal_id, revision: a.revision, status: a.agent_status };
102
+ }
103
+ async function wait(target, o) {
104
+ const made = await call('agent.wait', { target: target.paneId,
105
+ ...(o.until === undefined ? {} : { until: o.until }), timeout_ms: o.timeoutMs });
106
+ // The fake answers `{ agent }`; the pinned schema wraps the status event in `event.data` — both unwrap.
107
+ return (made?.agent?.agent_status ?? made?.event?.data?.agent_status ?? 'unknown');
108
+ }
109
+ async function read(paneId, o) {
110
+ const made = await call('pane.read', { pane_id: paneId, source: o?.source ?? 'recent',
111
+ ...(o?.lines === undefined ? {} : { lines: o.lines }),
112
+ ...(o?.ansi === true ? { format: 'ansi' } : {}) });
113
+ const body = isObj(made?.read) ? made.read : undefined;
114
+ return { text: typeof body?.text === 'string' ? body.text : '', truncated: body?.truncated === true };
115
+ }
116
+ async function sendKeys(target, keys) {
117
+ await call('agent.send_keys', { target: target.paneId, keys });
118
+ }
119
+ async function agentKinds() {
120
+ const made = await call('server.agent_manifests', {});
121
+ const manifests = Array.isArray(made?.manifests) ? made.manifests : [];
122
+ return manifests.map((m) => (typeof m?.agent === 'string' ? m.agent : '')).filter((kind) => kind !== '');
123
+ }
124
+ function installedAgentKinds(kinds, o) {
125
+ const installed = [];
126
+ for (const kind of kinds) {
127
+ if (o.path.some((dir) => {
128
+ try {
129
+ accessSync(join(dir, kind), fsConstants.X_OK);
130
+ return true;
131
+ }
132
+ catch {
133
+ return false;
134
+ }
135
+ }))
136
+ installed.push(kind);
137
+ }
138
+ return installed;
139
+ }
140
+ return { startAgent, prompt, sendKeys, wait, read, agentKinds, installedAgentKinds };
141
+ }
@@ -0,0 +1,24 @@
1
+ import type { Call } from './agents.ts';
2
+ import type { BlockedAgent, HerdrSnapshot } from './types.ts';
3
+ type AgentRecord = NonNullable<HerdrSnapshot['workspaces'][number]['tabs'][number]['panes'][number]['agent']>;
4
+ export declare class Blocked {
5
+ private readonly call;
6
+ private readonly entries;
7
+ private readonly listeners;
8
+ private readonly reading;
9
+ private readonly wanted;
10
+ constructor(ctx: {
11
+ call: Call;
12
+ });
13
+ update(paneId: string, agent: AgentRecord | undefined, where: {
14
+ workspaceId: string;
15
+ tabId: string;
16
+ }): void;
17
+ private readPrompt;
18
+ list(): BlockedAgent[];
19
+ on(fn: (b: BlockedAgent, change: 'added' | 'resolved') => void): () => void;
20
+ answer(paneId: string, keys: string[], o: {
21
+ revision: number;
22
+ }): Promise<void>;
23
+ }
24
+ export {};
@@ -0,0 +1,81 @@
1
+ const fail = (code, message) => Object.assign(new Error(message), { code });
2
+ export class Blocked {
3
+ call;
4
+ entries = new Map();
5
+ listeners = new Set();
6
+ reading = new Set(); // detection reads in flight, one per pane
7
+ wanted = new Set(); // panes still blocked while their read is in flight
8
+ constructor(ctx) { this.call = ctx.call; }
9
+ update(paneId, agent, where) {
10
+ if (agent?.status !== 'blocked') {
11
+ this.wanted.delete(paneId);
12
+ const entry = this.entries.get(paneId);
13
+ if (entry !== undefined) {
14
+ this.entries.delete(paneId);
15
+ for (const fn of this.listeners)
16
+ fn(entry, 'resolved');
17
+ }
18
+ return;
19
+ }
20
+ const current = this.entries.get(paneId);
21
+ if (current !== undefined) {
22
+ // Still blocked: keep the question, follow the pane's revision.
23
+ if (agent.revision !== current.revision)
24
+ this.entries.set(paneId, { ...current, revision: agent.revision });
25
+ return;
26
+ }
27
+ if (this.reading.has(paneId)) {
28
+ this.wanted.add(paneId);
29
+ return;
30
+ }
31
+ this.wanted.add(paneId);
32
+ this.reading.add(paneId);
33
+ const pending = {
34
+ paneId, workspaceId: where.workspaceId, tabId: where.tabId,
35
+ ...(agent.kind === undefined ? {} : { kind: agent.kind }),
36
+ revision: agent.revision, prompt: '', since: Date.now(),
37
+ };
38
+ void this.readPrompt(pending);
39
+ }
40
+ // The entry only appears once its prompt text is known, so `list()` never shows a half-read question.
41
+ async readPrompt(pending) {
42
+ let prompt = '';
43
+ try {
44
+ const made = (await this.call('pane.read', { pane_id: pending.paneId, source: 'detection', lines: 40 }));
45
+ if (typeof made?.read?.text === 'string')
46
+ prompt = made.read.text;
47
+ }
48
+ catch { /* a failed read still lists the blocked agent, with the text it could get */ }
49
+ this.reading.delete(pending.paneId);
50
+ if (!this.wanted.delete(pending.paneId))
51
+ return; // the pane left `blocked` while the read ran
52
+ const entry = { ...pending, prompt };
53
+ this.entries.set(pending.paneId, entry);
54
+ for (const fn of this.listeners)
55
+ fn(entry, 'added');
56
+ }
57
+ list() { return [...this.entries.values()]; }
58
+ on(fn) {
59
+ this.listeners.add(fn);
60
+ return () => { this.listeners.delete(fn); };
61
+ }
62
+ async answer(paneId, keys, o) {
63
+ let status;
64
+ let current;
65
+ try {
66
+ const made = (await this.call('pane.get', { pane_id: paneId }));
67
+ status = made?.pane?.agent_status;
68
+ // The pinned schema carries the pane's revision on pane.get; a server without it falls back
69
+ // to the revision recorded when the question appeared.
70
+ if (typeof made?.pane?.revision === 'number')
71
+ current = made.pane.revision;
72
+ }
73
+ catch { /* gone or unreachable: the recorded revision decides below */ }
74
+ if (current === undefined)
75
+ current = this.entries.get(paneId)?.revision;
76
+ if (status !== 'blocked' || current === undefined || o.revision !== current) {
77
+ throw fail('approval-stale', 'That answer is out of date; the question has changed.');
78
+ }
79
+ await this.call('agent.send_keys', { target: paneId, keys });
80
+ }
81
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ export type CliResult = {
2
+ stdout: string;
3
+ stderr: string;
4
+ exitCode: number | null;
5
+ timedOut: boolean;
6
+ };
7
+ export declare const DEFAULT_CLI_TIMEOUT = 15000;
8
+ /** ENOENT and friends carry the kit's `missing/binary` code (6.3/6.5), message per the 6.3 error shape. */
9
+ export declare function missingBinary(bin: string, cause?: string): Error;
10
+ export declare function runCli(bin: string, env: Record<string, string>, args: string[], timeoutMs?: number): Promise<CliResult>;
package/dist/cli.js ADDED
@@ -0,0 +1,89 @@
1
+ // `herdr <args>` with the kit's own env, one argv entry per argument, no environment read
2
+ // (docs/runtime-kits.md 6.5, D13). The env comes from the supervisor (6.3) in `own` mode or is the
3
+ // fixed adopt env in 6.5; this module passes it through verbatim and never touches `process.env`.
4
+ import { spawn } from 'node:child_process';
5
+ // The doc's ceiling: an 8 MB cap per stream, timeouts clamped to 1 s–5 min (docs/runtime-kits.md §11.3 H4).
6
+ const MAX_BUFFER = 8 * 1024 * 1024;
7
+ const MIN_TIMEOUT = 1_000;
8
+ const MAX_TIMEOUT = 5 * 60_000;
9
+ export const DEFAULT_CLI_TIMEOUT = 15_000; // same default as a socket call (6.3)
10
+ /** ENOENT and friends carry the kit's `missing/binary` code (6.3/6.5), message per the 6.3 error shape. */
11
+ export function missingBinary(bin, cause = 'spawn failed') {
12
+ const e = new Error(`herdr: missing/binary: ${cause}: ${bin}`);
13
+ e.code = 'missing/binary';
14
+ return e;
15
+ }
16
+ /** argv goes one entry per execve argument (spaces and quotes survive); reject anything execve would mangle. */
17
+ function checkArgs(args) {
18
+ if (!Array.isArray(args) || args.length === 0)
19
+ throw new Error('herdr: args must be a non-empty array of strings');
20
+ for (const a of args) {
21
+ if (typeof a !== 'string')
22
+ throw new Error('herdr: every arg must be a string');
23
+ if (a.includes('\0'))
24
+ throw new Error('herdr: args must not contain NUL');
25
+ }
26
+ }
27
+ function clampTimeout(timeoutMs) {
28
+ return Math.min(Math.max(timeoutMs ?? DEFAULT_CLI_TIMEOUT, MIN_TIMEOUT), MAX_TIMEOUT);
29
+ }
30
+ export function runCli(bin, env, args, timeoutMs) {
31
+ if (typeof bin !== 'string' || bin.length === 0)
32
+ throw new Error('herdr: bin must be a non-empty string');
33
+ checkArgs(args);
34
+ const timeout = clampTimeout(timeoutMs);
35
+ return new Promise((resolve, reject) => {
36
+ const child = spawn(bin, args, { env, stdio: ['ignore', 'pipe', 'pipe'] });
37
+ const out = [];
38
+ const err = [];
39
+ let outLen = 0;
40
+ let errLen = 0;
41
+ let timedOut = false;
42
+ let settled = false;
43
+ const timer = setTimeout(() => {
44
+ timedOut = true;
45
+ child.kill();
46
+ settle({ stdout: Buffer.concat(out).toString('utf8'), stderr: Buffer.concat(err).toString('utf8'),
47
+ exitCode: null, timedOut: true });
48
+ }, timeout);
49
+ const settle = (r, e) => {
50
+ if (settled)
51
+ return;
52
+ settled = true;
53
+ clearTimeout(timer);
54
+ if (e !== undefined)
55
+ reject(e);
56
+ else
57
+ resolve(r);
58
+ };
59
+ child.on('error', (e) => {
60
+ settle(undefined, e.code === 'ENOENT' ? missingBinary(bin, 'no executable') : e);
61
+ });
62
+ child.stdout.on('data', (chunk) => {
63
+ if (settled)
64
+ return;
65
+ outLen += chunk.length;
66
+ if (outLen > MAX_BUFFER) {
67
+ child.kill();
68
+ settle(undefined, new Error('herdr: stdout exceeded the 8 MB buffer'));
69
+ return;
70
+ }
71
+ out.push(chunk);
72
+ });
73
+ child.stderr.on('data', (chunk) => {
74
+ if (settled)
75
+ return;
76
+ errLen += chunk.length;
77
+ if (errLen > MAX_BUFFER) {
78
+ child.kill();
79
+ settle(undefined, new Error('herdr: stderr exceeded the 8 MB buffer'));
80
+ return;
81
+ }
82
+ err.push(chunk);
83
+ });
84
+ child.on('close', (code) => {
85
+ settle({ stdout: Buffer.concat(out).toString('utf8'), stderr: Buffer.concat(err).toString('utf8'),
86
+ exitCode: code, timedOut });
87
+ });
88
+ });
89
+ }
@@ -0,0 +1,4 @@
1
+ import type { Call } from './agents.ts';
2
+ export declare function closePane(call: Call, paneId: string): Promise<void>;
3
+ export declare function closeTab(call: Call, tabId: string): Promise<void>;
4
+ export declare function closeWorkspace(call: Call, workspaceId: string): Promise<void>;