@kodycodes/cli 3.14.0 → 3.15.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.
@@ -0,0 +1,948 @@
1
+ import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
+
3
+ // ../shared/src/base64.ts
4
+ function bytesToBase64(bytes) {
5
+ let binary = "";
6
+ for (const byte of bytes) {
7
+ binary += String.fromCharCode(byte);
8
+ }
9
+ return btoa(binary);
10
+ }
11
+ function base64ToBytes(value) {
12
+ const binary = atob(value);
13
+ return Uint8Array.from(binary, (char) => char.charCodeAt(0));
14
+ }
15
+ function bytesToBase64Url(bytes) {
16
+ return bytesToBase64(bytes).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
17
+ }
18
+ function base64UrlToBytes(value) {
19
+ const normalized = value.replaceAll("-", "+").replaceAll("_", "/");
20
+ const padded = normalized.padEnd(
21
+ normalized.length + (4 - normalized.length % 4) % 4,
22
+ "="
23
+ );
24
+ return base64ToBytes(padded);
25
+ }
26
+
27
+ // ../shared/src/execution-context-protocol/envelope.ts
28
+ var ecpFrameSignaturePrefix = "kody-ecp/1\n";
29
+ var ecpKeySetSignaturePrefix = "kody-ecp-keys/1\n";
30
+ var ecpHttpSignaturePrefix = "kody-ecp-http/1\n";
31
+ var ecpContextKeyId = "ctx";
32
+ var ecpPingFrame = '{"t":"ping"}';
33
+ var encoder = new TextEncoder();
34
+ var decoder = new TextDecoder();
35
+ function isRecord(value) {
36
+ return typeof value === "object" && value !== null && !Array.isArray(value);
37
+ }
38
+ var base64UrlPattern = /^[A-Za-z0-9_-]+$/;
39
+ function normalizeEd25519PublicJwk(value) {
40
+ if (!isRecord(value)) return null;
41
+ if (value.kty !== "OKP" || value.crv !== "Ed25519") return null;
42
+ if (typeof value.x !== "string" || !base64UrlPattern.test(value.x)) {
43
+ return null;
44
+ }
45
+ if (base64UrlToBytes(value.x).byteLength !== 32) return null;
46
+ return { kty: "OKP", crv: "Ed25519", x: value.x };
47
+ }
48
+ async function ed25519JwkThumbprint(jwk) {
49
+ const canonical = `{"crv":"Ed25519","kty":"OKP","x":"${jwk.x}"}`;
50
+ const digest = await crypto.subtle.digest(
51
+ "SHA-256",
52
+ encoder.encode(canonical)
53
+ );
54
+ return bytesToBase64Url(new Uint8Array(digest));
55
+ }
56
+ async function importEd25519PublicKey(jwk) {
57
+ return await crypto.subtle.importKey(
58
+ "jwk",
59
+ { kty: jwk.kty, crv: jwk.crv, x: jwk.x },
60
+ { name: "Ed25519" },
61
+ false,
62
+ ["verify"]
63
+ );
64
+ }
65
+ async function importEd25519PrivateKey(jwk) {
66
+ return await crypto.subtle.importKey(
67
+ "jwk",
68
+ { kty: jwk.kty, crv: jwk.crv, x: jwk.x, d: jwk.d },
69
+ { name: "Ed25519" },
70
+ false,
71
+ ["sign"]
72
+ );
73
+ }
74
+ async function signDetached(input) {
75
+ const signature = await crypto.subtle.sign(
76
+ { name: "Ed25519" },
77
+ input.privateKey,
78
+ encoder.encode(input.prefix + input.message)
79
+ );
80
+ return bytesToBase64Url(new Uint8Array(signature));
81
+ }
82
+ async function verifyDetached(input) {
83
+ if (!base64UrlPattern.test(input.signature)) return false;
84
+ const signature = base64UrlToBytes(input.signature);
85
+ if (signature.byteLength !== 64) return false;
86
+ try {
87
+ return await crypto.subtle.verify(
88
+ { name: "Ed25519" },
89
+ input.publicKey,
90
+ signature,
91
+ encoder.encode(input.prefix + input.message)
92
+ );
93
+ } catch {
94
+ return false;
95
+ }
96
+ }
97
+ function encodeEnvelopePayload(payload) {
98
+ return bytesToBase64Url(encoder.encode(JSON.stringify(payload)));
99
+ }
100
+ function decodeEnvelopePayload(p) {
101
+ if (!base64UrlPattern.test(p)) return null;
102
+ try {
103
+ return JSON.parse(decoder.decode(base64UrlToBytes(p)));
104
+ } catch {
105
+ return null;
106
+ }
107
+ }
108
+ function parseEnvelope(value) {
109
+ if (!isRecord(value)) return null;
110
+ const { p, s, k } = value;
111
+ if (typeof p !== "string" || typeof s !== "string" || typeof k !== "string") {
112
+ return null;
113
+ }
114
+ if (!p || !s || !k) return null;
115
+ return { p, s, k };
116
+ }
117
+ async function signEnvelope(input) {
118
+ const p = encodeEnvelopePayload(input.payload);
119
+ const s = await signDetached({
120
+ prefix: input.prefix,
121
+ message: p,
122
+ privateKey: input.privateKey
123
+ });
124
+ return { p, s, k: input.kid };
125
+ }
126
+ async function verifyEnvelope(input) {
127
+ const ok = await verifyDetached({
128
+ prefix: input.prefix,
129
+ message: input.envelope.p,
130
+ signature: input.envelope.s,
131
+ publicKey: input.publicKey
132
+ });
133
+ if (!ok) return null;
134
+ return decodeEnvelopePayload(input.envelope.p);
135
+ }
136
+
137
+ // ../shared/src/execution-context-protocol/replay.ts
138
+ var ecpFrameClockSkewMs = 6e4;
139
+ function checkNextSeq(lastSeen, received) {
140
+ return Number.isSafeInteger(received) && received === lastSeen + 1 ? "ok" : "replay";
141
+ }
142
+ function checkFrameClock(ts, now) {
143
+ return Number.isFinite(ts) && Math.abs(now - ts) <= ecpFrameClockSkewMs ? "ok" : "clock_skew";
144
+ }
145
+
146
+ // ../shared/src/execution-context-protocol/frames.ts
147
+ var ecpProtocolVersion = 1;
148
+ var ecpFrameFormatVersion = 1;
149
+ var ecpMaxFrameBytes = 6 * 1024 * 1024;
150
+ var ecpMaxConcurrentRunsCap = 8;
151
+ var ecpDefaultGrant = {
152
+ fs: [],
153
+ egress: { mode: "public" },
154
+ runtime: { mode: "all" },
155
+ limits: { timeoutMs: 9e4, memoryMb: 512, maxConcurrent: 2 },
156
+ payload: {
157
+ maxRequestBytes: 5 * 1024 * 1024,
158
+ maxResultBytes: 100 * 1024,
159
+ resultContentTypes: ["application/json", "text/plain"]
160
+ },
161
+ commands: { enabled: false }
162
+ };
163
+ var ecpGrantMaximums = {
164
+ timeoutMs: 15 * 6e4,
165
+ memoryMb: 8192,
166
+ maxConcurrent: ecpMaxConcurrentRunsCap,
167
+ maxRequestBytes: 5 * 1024 * 1024,
168
+ maxResultBytes: 1024 * 1024
169
+ };
170
+ function isRecord2(value) {
171
+ return typeof value === "object" && value !== null && !Array.isArray(value);
172
+ }
173
+ function parseFramePayload(value) {
174
+ if (!isRecord2(value)) return null;
175
+ const { v, t, ec, sid, seq, ts, re, body } = value;
176
+ if (typeof v !== "number" || typeof t !== "string" || !t) return null;
177
+ if (typeof ec !== "string" || typeof sid !== "string") return null;
178
+ if (typeof seq !== "number" || !Number.isSafeInteger(seq)) return null;
179
+ if (typeof ts !== "number" || !Number.isFinite(ts)) return null;
180
+ if (re !== void 0 && (typeof re !== "number" || !Number.isSafeInteger(re)))
181
+ return null;
182
+ if (!isRecord2(body)) return null;
183
+ return {
184
+ v,
185
+ t,
186
+ ec,
187
+ sid,
188
+ seq,
189
+ ts,
190
+ ...re === void 0 ? {} : { re },
191
+ body
192
+ };
193
+ }
194
+ function classifyFrameText(text) {
195
+ if (text.length > ecpMaxFrameBytes) {
196
+ return { kind: "invalid", code: "frame_too_large" };
197
+ }
198
+ if (text === ecpPingFrame) return { kind: "ping" };
199
+ let parsed;
200
+ try {
201
+ parsed = JSON.parse(text);
202
+ } catch {
203
+ return { kind: "invalid", code: "bad_signature" };
204
+ }
205
+ const envelope = parseEnvelope(parsed);
206
+ if (!envelope) return { kind: "invalid", code: "bad_signature" };
207
+ return { kind: "frame", envelope };
208
+ }
209
+ async function signFrame(input) {
210
+ const envelope = await signEnvelope({
211
+ prefix: ecpFrameSignaturePrefix,
212
+ payload: input.payload,
213
+ privateKey: input.privateKey,
214
+ kid: input.kid
215
+ });
216
+ return JSON.stringify(envelope);
217
+ }
218
+ async function verifyFrame(input) {
219
+ if (input.expect.kid !== void 0 && input.envelope.k !== input.expect.kid) {
220
+ return { ok: false, code: "bad_signature" };
221
+ }
222
+ const decoded = await verifyEnvelope({
223
+ prefix: ecpFrameSignaturePrefix,
224
+ envelope: input.envelope,
225
+ publicKey: input.publicKey
226
+ });
227
+ const frame = parseFramePayload(decoded);
228
+ if (!frame || frame.v !== ecpFrameFormatVersion) {
229
+ return { ok: false, code: "bad_signature" };
230
+ }
231
+ if (frame.ec !== input.expect.ec || frame.sid !== input.expect.sid) {
232
+ return { ok: false, code: "bad_signature" };
233
+ }
234
+ if (checkNextSeq(input.expect.lastSeq, frame.seq) !== "ok") {
235
+ return { ok: false, code: "replay" };
236
+ }
237
+ if (checkFrameClock(frame.ts, input.now) !== "ok") {
238
+ return { ok: false, code: "clock_skew" };
239
+ }
240
+ return { ok: true, frame };
241
+ }
242
+
243
+ // ../shared/src/execution-context-protocol/http-signature.ts
244
+ var ecpSignatureHeader = "Kody-ECP-Signature";
245
+ var ecpRunHeader = "Kody-ECP-Run";
246
+ var encoder2 = new TextEncoder();
247
+ async function sha256Base64Url(body) {
248
+ const bytes = typeof body === "string" ? encoder2.encode(body) : new Uint8Array(body);
249
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
250
+ return bytesToBase64Url(new Uint8Array(digest));
251
+ }
252
+ async function ecpHttpSignatureInput(input) {
253
+ return [
254
+ input.method.toUpperCase(),
255
+ input.pathAndQuery,
256
+ String(input.ts),
257
+ input.nonce,
258
+ await sha256Base64Url(input.body)
259
+ ].join("\n");
260
+ }
261
+ function randomEcpNonce() {
262
+ const bytes = new Uint8Array(16);
263
+ crypto.getRandomValues(bytes);
264
+ return bytesToBase64Url(bytes);
265
+ }
266
+ function formatEcpSignatureHeader(signature) {
267
+ return `ec=${signature.ec}, ts=${signature.ts}, n=${signature.n}, s=${signature.s}`;
268
+ }
269
+ async function signEcpHttpRequest(input) {
270
+ const ts = input.now ?? Date.now();
271
+ const n = input.nonce ?? randomEcpNonce();
272
+ const message = await ecpHttpSignatureInput({ ...input, ts, nonce: n });
273
+ const s = await signDetached({
274
+ prefix: ecpHttpSignaturePrefix,
275
+ message,
276
+ privateKey: input.privateKey
277
+ });
278
+ return { ec: input.ec, ts, n, s };
279
+ }
280
+
281
+ // ../shared/src/execution-context-protocol/server-keys.ts
282
+ var ecpRootPublicKeys = [
283
+ { kid: "root-1", x: "snJD_ruDIz9ejTdYyRuDT38rlmScNQyXSYpeUCxOBRQ" },
284
+ { kid: "root-2", x: "8TMMLGTn67-wjqM4tU7hUcKtvEgENM2cE4DFjLdBz-w" }
285
+ ];
286
+ function isRecord3(value) {
287
+ return typeof value === "object" && value !== null && !Array.isArray(value);
288
+ }
289
+ function parsePublishedKey(value) {
290
+ if (!isRecord3(value)) return null;
291
+ const { kid, x, notAfter } = value;
292
+ if (typeof kid !== "string" || !kid) return null;
293
+ if (typeof notAfter !== "number" || !Number.isFinite(notAfter)) return null;
294
+ const jwk = normalizeEd25519PublicJwk({ kty: "OKP", crv: "Ed25519", x });
295
+ if (!jwk) return null;
296
+ return { kid, x: jwk.x, notAfter };
297
+ }
298
+ function parseKeySetPayload(value) {
299
+ if (!isRecord3(value) || value.v !== 1) return null;
300
+ if (!Array.isArray(value.keys) || typeof value.issuedAt !== "number") {
301
+ return null;
302
+ }
303
+ const keys = [];
304
+ for (const entry of value.keys) {
305
+ const key = parsePublishedKey(entry);
306
+ if (!key) return null;
307
+ keys.push(key);
308
+ }
309
+ return { v: 1, keys, issuedAt: value.issuedAt };
310
+ }
311
+ async function verifyServerKeySet(input) {
312
+ const envelope = parseEnvelope(input.document);
313
+ if (!envelope) return null;
314
+ const root = (input.roots ?? ecpRootPublicKeys).find(
315
+ (candidate) => candidate.kid === envelope.k
316
+ );
317
+ if (!root) return null;
318
+ const rootJwk = normalizeEd25519PublicJwk({
319
+ kty: "OKP",
320
+ crv: "Ed25519",
321
+ x: root.x
322
+ });
323
+ if (!rootJwk) return null;
324
+ const ok = await verifyDetached({
325
+ prefix: ecpKeySetSignaturePrefix,
326
+ message: envelope.p,
327
+ signature: envelope.s,
328
+ publicKey: await importEd25519PublicKey(rootJwk)
329
+ });
330
+ if (!ok) return null;
331
+ return parseKeySetPayload(decodeEnvelopePayload(envelope.p));
332
+ }
333
+ function publishedKeyJwk(key) {
334
+ return { kty: "OKP", crv: "Ed25519", x: key.x };
335
+ }
336
+
337
+ // src/execution-context/host-commands.ts
338
+ import { spawn } from "node:child_process";
339
+ import { randomBytes } from "node:crypto";
340
+ import { stat } from "node:fs/promises";
341
+ import { homedir } from "node:os";
342
+ import { isAbsolute } from "node:path";
343
+ var HostCommandError = class extends Error {
344
+ constructor(code, message) {
345
+ super(`${message} (${code})`);
346
+ this.code = code;
347
+ this.name = "HostCommandError";
348
+ }
349
+ code;
350
+ };
351
+ var hostCommandLimits = {
352
+ foregroundDefaultTimeoutMs: 6e4,
353
+ foregroundMaxTimeoutMs: 15 * 6e4,
354
+ backgroundDefaultTimeoutMs: 2 * 60 * 6e4,
355
+ backgroundMaxTimeoutMs: 24 * 60 * 6e4,
356
+ defaultOutputBytes: 256 * 1024,
357
+ maxOutputBytes: 4 * 1024 * 1024,
358
+ backgroundBufferBytes: 4 * 1024 * 1024,
359
+ maxOutputReadBytes: 1024 * 1024,
360
+ maxBackgroundJobs: 16,
361
+ keepFinishedJobsMs: 60 * 6e4,
362
+ maxCommandChars: 64 * 1024,
363
+ maxStdinBytes: 5 * 1024 * 1024
364
+ };
365
+ var OutputBuffer = class {
366
+ constructor(capacity) {
367
+ this.capacity = capacity;
368
+ }
369
+ capacity;
370
+ #chunks = [];
371
+ #size = 0;
372
+ /** Bytes ever written. */
373
+ total = 0;
374
+ get dropped() {
375
+ return this.total - this.#size;
376
+ }
377
+ write(chunk) {
378
+ this.total += chunk.length;
379
+ this.#chunks.push(chunk);
380
+ this.#size += chunk.length;
381
+ while (this.#size > this.capacity && this.#chunks.length > 0) {
382
+ const head = this.#chunks[0];
383
+ const over = this.#size - this.capacity;
384
+ if (head.length <= over) {
385
+ this.#chunks.shift();
386
+ this.#size -= head.length;
387
+ } else {
388
+ this.#chunks[0] = head.subarray(over);
389
+ this.#size -= over;
390
+ }
391
+ }
392
+ }
393
+ /** Bytes from absolute `offset` (clamped to what is still kept). */
394
+ read(offset, maxBytes) {
395
+ const all = Buffer.concat(this.#chunks);
396
+ let start = Math.max(offset, this.dropped);
397
+ while (start - this.dropped < all.length && start > offset && isUtf8Continuation(all[start - this.dropped]))
398
+ start++;
399
+ let end = Math.min(start - this.dropped + maxBytes, all.length);
400
+ if (end < all.length && isUtf8Continuation(all[end])) {
401
+ let back = end;
402
+ while (back > start - this.dropped && isUtf8Continuation(all[back]))
403
+ back--;
404
+ if (back > start - this.dropped) end = back;
405
+ else {
406
+ while (end < all.length && isUtf8Continuation(all[end])) end++;
407
+ }
408
+ }
409
+ const slice = all.subarray(start - this.dropped, end);
410
+ return {
411
+ text: slice.toString("utf8"),
412
+ from: start,
413
+ next: start + slice.length,
414
+ skipped: start - offset
415
+ };
416
+ }
417
+ text() {
418
+ return Buffer.concat(this.#chunks).toString("utf8");
419
+ }
420
+ };
421
+ function newCommandId() {
422
+ return `cmd_${randomBytes(9).toString("base64url")}`;
423
+ }
424
+ function clampInt(value, fallback, max, min = 1) {
425
+ if (value === void 0 || value === null) return fallback;
426
+ if (typeof value !== "number" || !Number.isFinite(value)) {
427
+ throw new HostCommandError(
428
+ "invalid_request",
429
+ `Expected a number, got ${typeof value}.`
430
+ );
431
+ }
432
+ return Math.min(Math.max(Math.floor(value), min), max);
433
+ }
434
+ function isUtf8Continuation(byte) {
435
+ return (byte & 192) === 128;
436
+ }
437
+ function shellFor(env) {
438
+ const shell = env.SHELL;
439
+ return shell && isAbsolute(shell) ? shell : "/bin/sh";
440
+ }
441
+ function killTree(child, signal) {
442
+ if (child.pid === void 0) return;
443
+ try {
444
+ process.kill(-child.pid, signal);
445
+ } catch {
446
+ try {
447
+ child.kill(signal);
448
+ } catch {
449
+ }
450
+ }
451
+ }
452
+ var HostCommands = class {
453
+ #jobs = /* @__PURE__ */ new Map();
454
+ #onFinished = null;
455
+ /** Finishes that could not be sent yet (no live connection); sent on the next reporter. */
456
+ #unreported = [];
457
+ #foreground = /* @__PURE__ */ new Map();
458
+ #pendingStarts = 0;
459
+ #localEnabled;
460
+ /** The server grant's commands flag (off from website/API/CLI). */
461
+ #grantEnabled = false;
462
+ #platform;
463
+ constructor(options = {}) {
464
+ this.#localEnabled = options.localEnabled === true;
465
+ this.#platform = options.platform ?? process.platform;
466
+ }
467
+ /** Both layers allow commands and the OS is supported. */
468
+ get enabled() {
469
+ return this.#platform !== "win32" && this.#localEnabled && this.#grantEnabled;
470
+ }
471
+ setLocalEnabled(enabled) {
472
+ this.#localEnabled = enabled;
473
+ if (!enabled) this.killAll("commands_off");
474
+ }
475
+ setGrantEnabled(enabled) {
476
+ this.#grantEnabled = enabled;
477
+ if (!enabled) this.killAll("commands_off");
478
+ }
479
+ /** Clears the reporter if it is still `report` (a newer connection may own it). */
480
+ clearReporter(report) {
481
+ if (this.#onFinished === report) this.#onFinished = null;
482
+ }
483
+ setReporter(report) {
484
+ this.#onFinished = report;
485
+ if (!report) return;
486
+ const queued = this.#unreported.splice(0);
487
+ for (const finished of queued) this.#report(finished);
488
+ }
489
+ /** Throws the denial a run sees when it may not run commands here. */
490
+ assertAvailable() {
491
+ if (this.#platform === "win32") {
492
+ throw new HostCommandError(
493
+ "execution_context_commands_unsupported",
494
+ "Host commands are not supported on Windows yet: the Kody runner supports macOS and Linux."
495
+ );
496
+ }
497
+ if (!this.#localEnabled) {
498
+ throw new HostCommandError(
499
+ "execution_context_commands_off",
500
+ "Host commands are off on this machine: its owner has not opted in. Turn them on on the machine with `kody context commands on` or the Kody desktop app (Machine > Allow commands)."
501
+ );
502
+ }
503
+ if (!this.#grantEnabled) {
504
+ throw new HostCommandError(
505
+ "execution_context_commands_off",
506
+ "Host commands were turned off for this machine (from the website, API or CLI). Its owner turns them back on on the machine with `kody context commands on` or the Kody desktop app."
507
+ );
508
+ }
509
+ }
510
+ /** Dispatches one `kody.command.<name>(args)` call from a run. */
511
+ async call(name, args, run) {
512
+ this.assertAvailable();
513
+ if (name === "status" || name === "output" || name === "kill" || name === "list") {
514
+ await run.authorize({ lifecycle: name });
515
+ this.assertAvailable();
516
+ }
517
+ switch (name) {
518
+ case "run":
519
+ return await this.run(args, run);
520
+ case "start":
521
+ return await this.start(args, run);
522
+ case "status":
523
+ return this.status(args, run);
524
+ case "output":
525
+ return this.output(args, run);
526
+ case "kill":
527
+ return this.kill(args, run);
528
+ case "list":
529
+ return this.list(run);
530
+ default:
531
+ throw new HostCommandError(
532
+ "invalid_request",
533
+ `Unknown kody.command.${name}. Use run, start, status, output, kill or list.`
534
+ );
535
+ }
536
+ }
537
+ async #prepare(input, background) {
538
+ const raw = typeof input === "string" ? { command: input } : input;
539
+ const spec = raw ?? {};
540
+ if (typeof spec !== "object" || Array.isArray(spec)) {
541
+ throw new HostCommandError(
542
+ "invalid_request",
543
+ "Pass { command } or { file, args }."
544
+ );
545
+ }
546
+ const hasCommand = typeof spec.command === "string" && spec.command.length > 0;
547
+ const hasFile = typeof spec.file === "string" && spec.file.length > 0;
548
+ if (hasCommand === hasFile) {
549
+ throw new HostCommandError(
550
+ "invalid_request",
551
+ "Pass exactly one of `command` (a shell command line) or `file` (an executable, with optional `args`)."
552
+ );
553
+ }
554
+ const args = spec.args ?? [];
555
+ if (!Array.isArray(args) || !args.every((arg) => typeof arg === "string")) {
556
+ throw new HostCommandError(
557
+ "invalid_request",
558
+ "`args` must be an array of strings."
559
+ );
560
+ }
561
+ if (hasCommand && spec.args !== void 0) {
562
+ throw new HostCommandError(
563
+ "invalid_request",
564
+ "`args` goes with `file`, not `command`."
565
+ );
566
+ }
567
+ const display = hasCommand ? spec.command : [spec.file, ...args].join(" ");
568
+ if (display.length > hostCommandLimits.maxCommandChars) {
569
+ throw new HostCommandError("invalid_request", "The command is too long.");
570
+ }
571
+ const cwd = spec.cwd ?? homedir();
572
+ if (typeof cwd !== "string" || !isAbsolute(cwd)) {
573
+ throw new HostCommandError(
574
+ "invalid_request",
575
+ "`cwd` must be an absolute path on the machine."
576
+ );
577
+ }
578
+ const cwdStat = await stat(cwd).catch(() => null);
579
+ if (!cwdStat?.isDirectory()) {
580
+ throw new HostCommandError(
581
+ "invalid_request",
582
+ `cwd ${cwd} is not a folder on this machine.`
583
+ );
584
+ }
585
+ const extraEnv = spec.env ?? {};
586
+ if (typeof extraEnv !== "object" || Array.isArray(extraEnv) || !Object.entries(extraEnv).every(
587
+ ([key, value]) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(key) && typeof value === "string"
588
+ )) {
589
+ throw new HostCommandError(
590
+ "invalid_request",
591
+ "`env` must map variable names to string values."
592
+ );
593
+ }
594
+ if (spec.stdin !== void 0 && typeof spec.stdin !== "string") {
595
+ throw new HostCommandError("invalid_request", "`stdin` must be a string.");
596
+ }
597
+ if ((spec.stdin?.length ?? 0) > hostCommandLimits.maxStdinBytes) {
598
+ throw new HostCommandError(
599
+ "invalid_request",
600
+ "`stdin` is larger than 5 MB."
601
+ );
602
+ }
603
+ const timeoutMs = background ? clampInt(
604
+ spec.timeoutMs,
605
+ hostCommandLimits.backgroundDefaultTimeoutMs,
606
+ hostCommandLimits.backgroundMaxTimeoutMs,
607
+ 1e3
608
+ ) : clampInt(
609
+ spec.timeoutMs,
610
+ hostCommandLimits.foregroundDefaultTimeoutMs,
611
+ hostCommandLimits.foregroundMaxTimeoutMs,
612
+ 100
613
+ );
614
+ const maxOutputBytes = clampInt(
615
+ spec.maxOutputBytes,
616
+ hostCommandLimits.defaultOutputBytes,
617
+ hostCommandLimits.maxOutputBytes,
618
+ 1024
619
+ );
620
+ const env = { ...process.env, ...extraEnv };
621
+ return {
622
+ display,
623
+ cwd,
624
+ env,
625
+ envKeys: Object.keys(extraEnv).sort(),
626
+ stdin: spec.stdin,
627
+ timeoutMs,
628
+ maxOutputBytes,
629
+ file: hasCommand ? shellFor(env) : spec.file,
630
+ argv: hasCommand ? ["-c", spec.command] : args
631
+ };
632
+ }
633
+ #spawn(prepared) {
634
+ const child = spawn(prepared.file, prepared.argv, {
635
+ cwd: prepared.cwd,
636
+ env: prepared.env,
637
+ detached: true,
638
+ stdio: [prepared.stdin === void 0 ? "ignore" : "pipe", "pipe", "pipe"]
639
+ });
640
+ if (prepared.stdin !== void 0 && child.stdin) {
641
+ child.stdin.on("error", () => {
642
+ });
643
+ child.stdin.end(prepared.stdin);
644
+ }
645
+ return child;
646
+ }
647
+ #report(finished) {
648
+ const requeue = () => {
649
+ if (this.#unreported.length < 256) this.#unreported.push(finished);
650
+ };
651
+ const report = this.#onFinished;
652
+ if (!report) return requeue();
653
+ try {
654
+ void Promise.resolve(report(finished)).catch(requeue);
655
+ } catch {
656
+ requeue();
657
+ }
658
+ }
659
+ async run(raw, run) {
660
+ const prepared = await this.#prepare(raw, false);
661
+ const commandId = newCommandId();
662
+ await run.authorize({
663
+ commandId,
664
+ command: prepared.display,
665
+ cwd: prepared.cwd,
666
+ envKeys: prepared.envKeys,
667
+ background: false
668
+ });
669
+ this.assertAvailable();
670
+ const startedAt = Date.now();
671
+ const stdout = new OutputBuffer(prepared.maxOutputBytes);
672
+ const stderr = new OutputBuffer(prepared.maxOutputBytes);
673
+ const ended = { reason: "exited" };
674
+ const child = this.#spawn(prepared);
675
+ this.#foreground.set(child, ended);
676
+ child.stdout?.on("data", (chunk) => stdout.write(chunk));
677
+ child.stderr?.on("data", (chunk) => stderr.write(chunk));
678
+ const timer = setTimeout(() => {
679
+ ended.reason = "timed_out";
680
+ killTree(child, "SIGKILL");
681
+ }, prepared.timeoutMs);
682
+ const onAbort = () => {
683
+ ended.reason = "cancelled";
684
+ killTree(child, "SIGKILL");
685
+ };
686
+ run.signal.addEventListener("abort", onAbort, { once: true });
687
+ if (run.signal.aborted) onAbort();
688
+ const outcome = await new Promise((resolve) => {
689
+ child.once(
690
+ "error",
691
+ (error) => resolve({ code: null, signal: null, error: error.message })
692
+ );
693
+ child.once("close", (code, signal) => resolve({ code, signal }));
694
+ });
695
+ clearTimeout(timer);
696
+ this.#foreground.delete(child);
697
+ run.signal.removeEventListener("abort", onAbort);
698
+ if (outcome.error) ended.reason = "spawn_failed";
699
+ const durationMs = Date.now() - startedAt;
700
+ this.#report({
701
+ commandId,
702
+ runId: run.runId,
703
+ command: prepared.display,
704
+ cwd: prepared.cwd,
705
+ exitCode: outcome.code,
706
+ signal: outcome.signal,
707
+ durationMs,
708
+ background: false,
709
+ reason: ended.reason
710
+ });
711
+ if (outcome.error) {
712
+ throw new HostCommandError(
713
+ "invalid_request",
714
+ `Could not start the command: ${outcome.error}`
715
+ );
716
+ }
717
+ return {
718
+ commandId,
719
+ exitCode: outcome.code,
720
+ signal: outcome.signal,
721
+ timedOut: ended.reason === "timed_out",
722
+ stdout: stdout.text(),
723
+ stderr: stderr.text(),
724
+ stdoutTruncated: stdout.dropped > 0,
725
+ stderrTruncated: stderr.dropped > 0,
726
+ durationMs
727
+ };
728
+ }
729
+ async start(raw, run) {
730
+ this.#sweep();
731
+ const running = [...this.#jobs.values()].filter(
732
+ (job2) => job2.state === "running"
733
+ );
734
+ if (running.length + this.#pendingStarts >= hostCommandLimits.maxBackgroundJobs) {
735
+ throw new HostCommandError(
736
+ "invalid_request",
737
+ `This machine already runs ${running.length + this.#pendingStarts} background commands. Kill one (kody.command.kill) first.`
738
+ );
739
+ }
740
+ this.#pendingStarts++;
741
+ let prepared;
742
+ let commandId;
743
+ let child;
744
+ try {
745
+ prepared = await this.#prepare(raw, true);
746
+ commandId = newCommandId();
747
+ await run.authorize({
748
+ commandId,
749
+ command: prepared.display,
750
+ cwd: prepared.cwd,
751
+ envKeys: prepared.envKeys,
752
+ background: true
753
+ });
754
+ this.assertAvailable();
755
+ child = this.#spawn(prepared);
756
+ } finally {
757
+ this.#pendingStarts--;
758
+ }
759
+ const job = {
760
+ id: commandId,
761
+ runId: run.runId,
762
+ ownerUserId: run.requesterUserId,
763
+ command: prepared.display,
764
+ cwd: prepared.cwd,
765
+ child,
766
+ pid: child.pid,
767
+ startedAt: Date.now(),
768
+ endedAt: null,
769
+ exitCode: null,
770
+ signal: null,
771
+ state: "running",
772
+ stdout: new OutputBuffer(hostCommandLimits.backgroundBufferBytes),
773
+ stderr: new OutputBuffer(hostCommandLimits.backgroundBufferBytes),
774
+ done: Promise.resolve(),
775
+ timer: null,
776
+ error: null
777
+ };
778
+ child.stdout?.on("data", (chunk) => job.stdout.write(chunk));
779
+ child.stderr?.on("data", (chunk) => job.stderr.write(chunk));
780
+ job.timer = setTimeout(() => {
781
+ if (job.state !== "running") return;
782
+ job.state = "timed_out";
783
+ killTree(child, "SIGKILL");
784
+ }, prepared.timeoutMs);
785
+ job.timer.unref?.();
786
+ job.done = new Promise((resolve) => {
787
+ const finish = (code, signal, error) => {
788
+ if (job.endedAt !== null) return resolve();
789
+ if (job.timer) clearTimeout(job.timer);
790
+ job.endedAt = Date.now();
791
+ job.exitCode = code;
792
+ job.signal = signal;
793
+ if (error) {
794
+ job.state = "failed";
795
+ job.error = error;
796
+ } else if (job.state === "running") {
797
+ job.state = "exited";
798
+ }
799
+ this.#report({
800
+ commandId,
801
+ runId: job.runId,
802
+ command: job.command,
803
+ cwd: job.cwd,
804
+ exitCode: code,
805
+ signal,
806
+ durationMs: job.endedAt - job.startedAt,
807
+ background: true,
808
+ reason: job.state === "failed" ? "spawn_failed" : job.state === "killed" ? job.error === "commands_off" ? "commands_off" : "killed" : job.state === "timed_out" ? "timed_out" : "exited"
809
+ });
810
+ resolve();
811
+ };
812
+ child.once("error", (error) => finish(null, null, error.message));
813
+ child.once("close", (code, signal) => finish(code, signal));
814
+ });
815
+ this.#jobs.set(commandId, job);
816
+ return {
817
+ commandId,
818
+ pid: job.pid ?? null,
819
+ startedAt: new Date(job.startedAt).toISOString(),
820
+ timeoutMs: prepared.timeoutMs
821
+ };
822
+ }
823
+ #job(raw, run) {
824
+ const id = typeof raw === "string" ? raw : raw?.commandId;
825
+ const job = typeof id === "string" ? this.#jobs.get(id) : void 0;
826
+ if (!job || job.ownerUserId !== run.requesterUserId) {
827
+ throw new HostCommandError(
828
+ "not_found",
829
+ `No background command ${String(id)} on this machine for you. kody.command.list() shows yours.`
830
+ );
831
+ }
832
+ return job;
833
+ }
834
+ #describe(job) {
835
+ return {
836
+ commandId: job.id,
837
+ command: job.command,
838
+ cwd: job.cwd,
839
+ state: job.state,
840
+ pid: job.pid ?? null,
841
+ exitCode: job.exitCode,
842
+ signal: job.signal,
843
+ startedAt: new Date(job.startedAt).toISOString(),
844
+ endedAt: job.endedAt === null ? null : new Date(job.endedAt).toISOString(),
845
+ durationMs: (job.endedAt ?? Date.now()) - job.startedAt,
846
+ stdoutBytes: job.stdout.total,
847
+ stderrBytes: job.stderr.total,
848
+ ...job.error && job.state === "failed" ? { error: job.error } : {}
849
+ };
850
+ }
851
+ status(raw, run) {
852
+ return this.#describe(this.#job(raw, run));
853
+ }
854
+ output(raw, run) {
855
+ const job = this.#job(raw, run);
856
+ const input = typeof raw === "object" && raw ? raw : {};
857
+ const maxBytes = clampInt(
858
+ input.maxBytes,
859
+ hostCommandLimits.defaultOutputBytes,
860
+ hostCommandLimits.maxOutputReadBytes
861
+ );
862
+ const stdout = job.stdout.read(
863
+ clampInt(input.stdoutOffset, 0, Number.MAX_SAFE_INTEGER, 0),
864
+ maxBytes
865
+ );
866
+ const stderr = job.stderr.read(
867
+ clampInt(input.stderrOffset, 0, Number.MAX_SAFE_INTEGER, 0),
868
+ maxBytes
869
+ );
870
+ return {
871
+ commandId: job.id,
872
+ state: job.state,
873
+ exitCode: job.exitCode,
874
+ stdout: stdout.text,
875
+ stderr: stderr.text,
876
+ stdoutOffset: stdout.next,
877
+ stderrOffset: stderr.next,
878
+ stdoutSkipped: stdout.skipped,
879
+ stderrSkipped: stderr.skipped,
880
+ done: job.state !== "running" && stdout.next >= job.stdout.total && stderr.next >= job.stderr.total
881
+ };
882
+ }
883
+ kill(raw, run) {
884
+ const job = this.#job(raw, run);
885
+ const requested = raw?.signal;
886
+ const signal = requested === "SIGINT" || requested === "SIGKILL" || requested === "SIGTERM" ? requested : "SIGTERM";
887
+ if (job.state === "running") {
888
+ job.state = "killed";
889
+ killTree(job.child, signal);
890
+ if (signal !== "SIGKILL") {
891
+ const escalate = setTimeout(() => killTree(job.child, "SIGKILL"), 5e3);
892
+ escalate.unref?.();
893
+ }
894
+ }
895
+ return this.#describe(job);
896
+ }
897
+ list(run) {
898
+ this.#sweep();
899
+ return {
900
+ commands: [...this.#jobs.values()].filter((job) => job.ownerUserId === run.requesterUserId).map((job) => this.#describe(job))
901
+ };
902
+ }
903
+ /** Commands were turned off (or the daemon stops): end every background job. */
904
+ killAll(reason) {
905
+ for (const [child, ended] of this.#foreground) {
906
+ ended.reason = reason === "commands_off" ? "commands_off" : "cancelled";
907
+ killTree(child, "SIGKILL");
908
+ }
909
+ for (const job of this.#jobs.values()) {
910
+ if (job.state !== "running") continue;
911
+ job.state = "killed";
912
+ job.error = reason === "commands_off" ? "commands_off" : null;
913
+ killTree(job.child, "SIGKILL");
914
+ }
915
+ }
916
+ async idle() {
917
+ await Promise.all([...this.#jobs.values()].map((job) => job.done));
918
+ }
919
+ #sweep() {
920
+ const cutoff = Date.now() - hostCommandLimits.keepFinishedJobsMs;
921
+ for (const [id, job] of this.#jobs) {
922
+ if (job.endedAt !== null && job.endedAt < cutoff) this.#jobs.delete(id);
923
+ }
924
+ }
925
+ };
926
+
927
+ export {
928
+ ecpContextKeyId,
929
+ ecpPingFrame,
930
+ ed25519JwkThumbprint,
931
+ importEd25519PublicKey,
932
+ importEd25519PrivateKey,
933
+ decodeEnvelopePayload,
934
+ ecpProtocolVersion,
935
+ ecpMaxConcurrentRunsCap,
936
+ ecpDefaultGrant,
937
+ classifyFrameText,
938
+ signFrame,
939
+ verifyFrame,
940
+ ecpSignatureHeader,
941
+ ecpRunHeader,
942
+ formatEcpSignatureHeader,
943
+ signEcpHttpRequest,
944
+ verifyServerKeySet,
945
+ publishedKeyJwk,
946
+ HostCommands
947
+ };
948
+ //# sourceMappingURL=chunk-IXFFZQGD.js.map