@ai-devkit/daemon-client 0.0.0-stage → 0.1.1

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,321 @@
1
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
2
+ try {
3
+ var info = gen[key](arg);
4
+ var value = info.value;
5
+ } catch (error) {
6
+ reject(error);
7
+ return;
8
+ }
9
+ if (info.done) {
10
+ resolve(value);
11
+ } else {
12
+ Promise.resolve(value).then(_next, _throw);
13
+ }
14
+ }
15
+ function _async_to_generator(fn) {
16
+ return function() {
17
+ var self = this, args = arguments;
18
+ return new Promise(function(resolve, reject) {
19
+ var gen = fn.apply(self, args);
20
+ function _next(value) {
21
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
22
+ }
23
+ function _throw(err) {
24
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
25
+ }
26
+ _next(undefined);
27
+ });
28
+ };
29
+ }
30
+ function _ts_generator(thisArg, body) {
31
+ var f, y, t, _ = {
32
+ label: 0,
33
+ sent: function() {
34
+ if (t[0] & 1) throw t[1];
35
+ return t[1];
36
+ },
37
+ trys: [],
38
+ ops: []
39
+ }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
40
+ return d(g, "next", {
41
+ value: verb(0)
42
+ }), d(g, "throw", {
43
+ value: verb(1)
44
+ }), d(g, "return", {
45
+ value: verb(2)
46
+ }), typeof Symbol === "function" && d(g, Symbol.iterator, {
47
+ value: function() {
48
+ return this;
49
+ }
50
+ }), g;
51
+ function verb(n) {
52
+ return function(v) {
53
+ return step([
54
+ n,
55
+ v
56
+ ]);
57
+ };
58
+ }
59
+ function step(op) {
60
+ if (f) throw new TypeError("Generator is already executing.");
61
+ while(g && (g = 0, op[0] && (_ = 0)), _)try {
62
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
63
+ if (y = 0, t) op = [
64
+ op[0] & 2,
65
+ t.value
66
+ ];
67
+ switch(op[0]){
68
+ case 0:
69
+ case 1:
70
+ t = op;
71
+ break;
72
+ case 4:
73
+ _.label++;
74
+ return {
75
+ value: op[1],
76
+ done: false
77
+ };
78
+ case 5:
79
+ _.label++;
80
+ y = op[1];
81
+ op = [
82
+ 0
83
+ ];
84
+ continue;
85
+ case 7:
86
+ op = _.ops.pop();
87
+ _.trys.pop();
88
+ continue;
89
+ default:
90
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
91
+ _ = 0;
92
+ continue;
93
+ }
94
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
95
+ _.label = op[1];
96
+ break;
97
+ }
98
+ if (op[0] === 6 && _.label < t[1]) {
99
+ _.label = t[1];
100
+ t = op;
101
+ break;
102
+ }
103
+ if (t && _.label < t[2]) {
104
+ _.label = t[2];
105
+ _.ops.push(op);
106
+ break;
107
+ }
108
+ if (t[2]) _.ops.pop();
109
+ _.trys.pop();
110
+ continue;
111
+ }
112
+ op = body.call(thisArg, _);
113
+ } catch (e) {
114
+ op = [
115
+ 6,
116
+ e
117
+ ];
118
+ y = 0;
119
+ } finally{
120
+ f = t = 0;
121
+ }
122
+ if (op[0] & 5) throw op[1];
123
+ return {
124
+ value: op[0] ? op[1] : void 0,
125
+ done: true
126
+ };
127
+ }
128
+ }
129
+ import * as fs from "node:fs";
130
+ import * as path from "node:path";
131
+ import { spawn } from "node:child_process";
132
+ import { DaemonClient, daemonSocketPath } from "./client.js";
133
+ import { resolveDaemonBinary } from "./binary.js";
134
+ /**
135
+ * tmux-style implicit spawn: if the socket answers, return a client; if not,
136
+ * spawn the daemon (single-spawner guarded by an exclusive lockfile) and wait
137
+ * for readiness. Returns null when no binary exists or spawn fails — callers
138
+ * degrade to today's code paths.
139
+ */ export function ensureDaemon() {
140
+ return _async_to_generator(function() {
141
+ var opts, _opts_waitMs, waitMs, existing, bin, sockPath, dir, STALE_LOCK_MS, lockPath, acquired, logPath, logFd, child;
142
+ var _arguments = arguments;
143
+ return _ts_generator(this, function(_state) {
144
+ switch(_state.label){
145
+ case 0:
146
+ opts = _arguments.length > 0 && _arguments[0] !== void 0 ? _arguments[0] : {};
147
+ waitMs = (_opts_waitMs = opts.waitMs) !== null && _opts_waitMs !== void 0 ? _opts_waitMs : 3000;
148
+ // Test runs must never spawn a real daemon. Callers that want to exercise
149
+ // autostart do so by pointing DEVKITD_BIN at a real binary in an explicit
150
+ // integration test — the env below is checked there too via VITEST_SKIP.
151
+ if (process.env.AI_DEVKIT_NO_DAEMON) return [
152
+ 2,
153
+ null
154
+ ];
155
+ return [
156
+ 4,
157
+ DaemonClient.tryConnect()
158
+ ];
159
+ case 1:
160
+ existing = _state.sent();
161
+ if (existing) return [
162
+ 2,
163
+ existing
164
+ ];
165
+ if (process.env.VITEST && !process.env.DEVKITD_BIN && !process.env.AI_DEVKITD_BIN) return [
166
+ 2,
167
+ null
168
+ ];
169
+ bin = resolveDaemonBinary();
170
+ if (!bin) return [
171
+ 2,
172
+ null
173
+ ];
174
+ sockPath = daemonSocketPath();
175
+ dir = path.dirname(sockPath);
176
+ fs.mkdirSync(dir, {
177
+ recursive: true
178
+ });
179
+ // Single-spawner lockfile: O_EXCL create serializes concurrent starters, and
180
+ // the holder unlinks it when done. A stale lock (crashed spawner) is reclaimed
181
+ // after STALE_LOCK_MS so a dead starter can't wedge autostart forever.
182
+ STALE_LOCK_MS = 30000;
183
+ lockPath = "".concat(sockPath, ".spawn.lock");
184
+ acquired = acquireSpawnLock(lockPath, STALE_LOCK_MS);
185
+ if (!acquired) {
186
+ // Another process is spawning; just wait for the socket.
187
+ return [
188
+ 2,
189
+ waitForSocket(waitMs)
190
+ ];
191
+ }
192
+ try {
193
+ logPath = path.join(dir, "daemon.log");
194
+ capDaemonLog(logPath);
195
+ logFd = fs.openSync(logPath, "a");
196
+ child = spawn(bin, [
197
+ "serve"
198
+ ], {
199
+ detached: true,
200
+ stdio: [
201
+ "ignore",
202
+ logFd,
203
+ logFd
204
+ ]
205
+ });
206
+ child.unref();
207
+ fs.closeSync(logFd);
208
+ } catch (unused) {
209
+ try {
210
+ fs.unlinkSync(lockPath);
211
+ } catch (unused) {
212
+ /* already gone */ }
213
+ return [
214
+ 2,
215
+ null
216
+ ];
217
+ }
218
+ _state.label = 2;
219
+ case 2:
220
+ _state.trys.push([
221
+ 2,
222
+ ,
223
+ 4,
224
+ 5
225
+ ]);
226
+ return [
227
+ 4,
228
+ waitForSocket(waitMs)
229
+ ];
230
+ case 3:
231
+ return [
232
+ 2,
233
+ _state.sent()
234
+ ];
235
+ case 4:
236
+ try {
237
+ fs.unlinkSync(lockPath);
238
+ } catch (unused) {
239
+ /* already gone */ }
240
+ return [
241
+ 7
242
+ ];
243
+ case 5:
244
+ return [
245
+ 2
246
+ ];
247
+ }
248
+ });
249
+ }).apply(this, arguments);
250
+ }
251
+ /** daemon.log is append-only per spawn — rotate to .1 past 1 MiB. */ var MAX_LOG_BYTES = 1 << 20;
252
+ function capDaemonLog(logPath) {
253
+ try {
254
+ if (fs.statSync(logPath).size > MAX_LOG_BYTES) {
255
+ fs.renameSync(logPath, "".concat(logPath, ".1"));
256
+ }
257
+ } catch (unused) {
258
+ /* missing or unwritable — the open() caller surfaces real problems */ }
259
+ }
260
+ function acquireSpawnLock(lockPath, staleMs) {
261
+ try {
262
+ fs.closeSync(fs.openSync(lockPath, "wx", 384));
263
+ return true;
264
+ } catch (unused) {
265
+ // Lock held — reclaim it only if the holder plausibly died.
266
+ try {
267
+ var age = Date.now() - fs.statSync(lockPath).mtimeMs;
268
+ if (age > staleMs) {
269
+ fs.unlinkSync(lockPath);
270
+ fs.closeSync(fs.openSync(lockPath, "wx", 384));
271
+ return true;
272
+ }
273
+ } catch (unused) {
274
+ /* races with the holder are fine — losing means we wait */ }
275
+ return false;
276
+ }
277
+ }
278
+ function waitForSocket(waitMs) {
279
+ return _async_to_generator(function() {
280
+ var deadline, client;
281
+ return _ts_generator(this, function(_state) {
282
+ switch(_state.label){
283
+ case 0:
284
+ deadline = Date.now() + waitMs;
285
+ _state.label = 1;
286
+ case 1:
287
+ if (!(Date.now() < deadline)) return [
288
+ 3,
289
+ 4
290
+ ];
291
+ return [
292
+ 4,
293
+ DaemonClient.tryConnect()
294
+ ];
295
+ case 2:
296
+ client = _state.sent();
297
+ if (client) return [
298
+ 2,
299
+ client
300
+ ];
301
+ return [
302
+ 4,
303
+ new Promise(function(r) {
304
+ return setTimeout(r, 50);
305
+ })
306
+ ];
307
+ case 3:
308
+ _state.sent();
309
+ return [
310
+ 3,
311
+ 1
312
+ ];
313
+ case 4:
314
+ return [
315
+ 2,
316
+ null
317
+ ];
318
+ }
319
+ });
320
+ })();
321
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Locate the devkitd binary. Resolution order:
3
+ * 1. DEVKITD_BIN env override (AI_DEVKITD_BIN accepted as a deprecated alias)
4
+ * 2. Platform package `@ai-devkit/devkitd-<plat>-<arch>` (npm optional dep)
5
+ * 3. ~/.ai-devkit/bin/devkitd (manual install)
6
+ * 4. rust/target/{release,debug}/devkitd relative to the monorepo (dev)
7
+ * Returns null when nothing is found — callers must degrade gracefully.
8
+ */
9
+ export declare function resolveDaemonBinary(): string | null;
10
+ //# sourceMappingURL=binary.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"binary.d.ts","sourceRoot":"","sources":["../src/binary.ts"],"names":[],"mappings":"AAMA;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,IAAI,MAAM,GAAG,IAAI,CAmDnD"}
package/dist/binary.js ADDED
@@ -0,0 +1,67 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import * as os from "node:os";
4
+ import { createRequire } from "node:module";
5
+ import { fileURLToPath } from "node:url";
6
+ /**
7
+ * Locate the devkitd binary. Resolution order:
8
+ * 1. DEVKITD_BIN env override (AI_DEVKITD_BIN accepted as a deprecated alias)
9
+ * 2. Platform package `@ai-devkit/devkitd-<plat>-<arch>` (npm optional dep)
10
+ * 3. ~/.ai-devkit/bin/devkitd (manual install)
11
+ * 4. rust/target/{release,debug}/devkitd relative to the monorepo (dev)
12
+ * Returns null when nothing is found — callers must degrade gracefully.
13
+ */ export function resolveDaemonBinary() {
14
+ var _process_env_DEVKITD_BIN;
15
+ var env = (_process_env_DEVKITD_BIN = process.env.DEVKITD_BIN) !== null && _process_env_DEVKITD_BIN !== void 0 ? _process_env_DEVKITD_BIN : process.env.AI_DEVKITD_BIN;
16
+ if (env && fs.existsSync(env)) return env;
17
+ var plats = {
18
+ linux: "linux",
19
+ darwin: "darwin",
20
+ win32: "windows"
21
+ };
22
+ var archs = {
23
+ x64: "x64",
24
+ arm64: "arm64"
25
+ };
26
+ var plat = plats[process.platform];
27
+ var arch = archs[process.arch];
28
+ if (plat && arch) {
29
+ try {
30
+ var req = createRequire(import.meta.url);
31
+ var pkgJson = req.resolve("@ai-devkit/devkitd-".concat(plat, "-").concat(arch, "/package.json"));
32
+ var candidate = path.join(path.dirname(pkgJson), process.platform === "win32" ? "devkitd.exe" : "devkitd");
33
+ if (fs.existsSync(candidate)) return candidate;
34
+ } catch (unused) {
35
+ /* package not installed */ }
36
+ }
37
+ var home = path.join(os.homedir(), ".ai-devkit", "bin", "devkitd");
38
+ if (fs.existsSync(home)) return home;
39
+ // Dev checkout: walk up to the nearest rust/target/<profile>/devkitd and
40
+ // pick the freshest profile — a stale release build otherwise shadows a
41
+ // freshly-built debug binary forever. fileURLToPath so paths containing
42
+ // spaces or other escaped chars resolve correctly.
43
+ var dir = path.dirname(fileURLToPath(import.meta.url));
44
+ for(var i = 0; i < 8; i++){
45
+ var best = null;
46
+ for(var _i = 0, _iter = [
47
+ "release",
48
+ "debug"
49
+ ]; _i < _iter.length; _i++){
50
+ var profile = _iter[_i];
51
+ var candidate1 = path.join(dir, "rust", "target", profile, "devkitd");
52
+ try {
53
+ var mtime = fs.statSync(candidate1).mtimeMs;
54
+ if (!best || mtime > best.mtime) best = {
55
+ file: candidate1,
56
+ mtime: mtime
57
+ };
58
+ } catch (unused) {
59
+ /* absent */ }
60
+ }
61
+ if (best) return best.file;
62
+ var parent = path.dirname(dir);
63
+ if (parent === dir) break;
64
+ dir = parent;
65
+ }
66
+ return null;
67
+ }
@@ -0,0 +1,44 @@
1
+ import type { EnrichedAgent } from "./gen/EnrichedAgent.js";
2
+ import type { Event } from "./gen/Event.js";
3
+ /** Wire event pushed by the daemon — generated from devkit-core via ts-rs. */
4
+ export type DaemonEvent = Event;
5
+ export declare function daemonSocketPath(): string;
6
+ /**
7
+ * Line-delimited JSON-RPC client for devkitd. One request per line;
8
+ * events arrive as `{"event": {...}}` frames after `subscribe`.
9
+ */
10
+ export declare class DaemonClient {
11
+ private socketPath;
12
+ private requestTimeoutMs;
13
+ private socket;
14
+ private nextId;
15
+ private pending;
16
+ private buffer;
17
+ private onEvent;
18
+ /**
19
+ * Fires once when the socket dies after a successful connect (daemon
20
+ * restart, crash). Consoles use it to resubscribe instead of silently
21
+ * falling back to polling forever.
22
+ */
23
+ onDisconnect: (() => void) | null;
24
+ private constructor();
25
+ static connect(socketPath?: string, timeoutMs?: number, requestTimeoutMs?: number): Promise<DaemonClient>;
26
+ /** Null when the socket is absent/unreachable — callers fall back. */
27
+ static tryConnect(socketPath?: string): Promise<DaemonClient | null>;
28
+ request(method: string, params?: unknown): Promise<unknown>;
29
+ subscribe(handler: (e: DaemonEvent) => void, opts?: {
30
+ afterSeq?: number;
31
+ liveOnly?: boolean;
32
+ }): Promise<void>;
33
+ /**
34
+ * The daemon's fully attributed agent list — authoritative for every
35
+ * harness type the daemon serves. Throws on RPC error: callers fall back
36
+ * to local adapters for the whole call, not per-agent.
37
+ */
38
+ listAgents(): Promise<EnrichedAgent[]>;
39
+ private onData;
40
+ /** Reject every in-flight request and mark the socket dead. Idempotent. */
41
+ private onSocketDead;
42
+ close():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