@kodycodes/cli 3.11.0 → 3.12.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.
@@ -1,1217 +0,0 @@
1
- import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
- import {
3
- classifyFrameText,
4
- decodeEnvelopePayload,
5
- ecpContextKeyId,
6
- ecpDefaultGrant,
7
- ecpMaxConcurrentRunsCap,
8
- ecpPingFrame,
9
- ecpProtocolVersion,
10
- ecpRunHeader,
11
- ecpSignatureHeader,
12
- ed25519JwkThumbprint,
13
- formatEcpSignatureHeader,
14
- importEd25519PrivateKey,
15
- importEd25519PublicKey,
16
- publishedKeyJwk,
17
- signEcpHttpRequest,
18
- signFrame,
19
- verifyFrame,
20
- verifyServerKeySet
21
- } from "./chunk-L225BIT7.js";
22
- import {
23
- allowLocalPath,
24
- createLocalWorkerTracker,
25
- createPackageGraphCache,
26
- effectiveFs,
27
- emptyEffectiveFs,
28
- fsFeatures,
29
- localPolicyPath,
30
- readLocalPolicy,
31
- reapLeftoverWorkers,
32
- removeLocalPath
33
- } from "./chunk-CBFSRN34.js";
34
- import "./chunk-LD6ND6Z3.js";
35
- import {
36
- apiTokenFileStorePath
37
- } from "./chunk-AZ6UXLP6.js";
38
- import "./chunk-NHRYNRXG.js";
39
- import {
40
- secretServiceKeyringOptions
41
- } from "./chunk-D6XME4RY.js";
42
- import {
43
- keyringService
44
- } from "./chunk-VP2O3HLT.js";
45
- import "./chunk-UW6AWLXX.js";
46
-
47
- // src/execution-context/commands.ts
48
- import { readdirSync, readFileSync as readFileSync2, unwatchFile, watchFile } from "node:fs";
49
- import { cpus, platform, totalmem } from "node:os";
50
-
51
- // src/execution-context/client.ts
52
- var executionContextsPath = "/v1/execution-contexts";
53
- var reloginHint = "Run `kody login` again, then retry `kody context register`.";
54
- var ExecutionContextApiError = class extends Error {
55
- constructor(message, status, code) {
56
- super(message);
57
- this.status = status;
58
- this.code = code;
59
- }
60
- status;
61
- code;
62
- };
63
- function experimentOffError(apiUrl) {
64
- const origin = new URL(apiUrl).origin;
65
- return new ExecutionContextApiError(
66
- [
67
- "Execution contexts are an experiment that is off for this account.",
68
- `Turn them on at ${origin}/account/experiments, or ask your agent to call experimentSet with { "experiment": "execution-contexts", "enabled": true }.`,
69
- `Then run this command again. Guide: ${origin}/docs/execution-contexts`
70
- ].join("\n"),
71
- 403,
72
- "feature_disabled"
73
- );
74
- }
75
- function isExperimentOffError(error) {
76
- return error instanceof ExecutionContextApiError && error.code === "feature_disabled";
77
- }
78
- async function readError(response) {
79
- const text = await response.text();
80
- let code = null;
81
- let message = text || `HTTP ${response.status}`;
82
- try {
83
- const body = JSON.parse(text);
84
- if (typeof body.error === "string") {
85
- code = body.error;
86
- message = body.message ?? body.error;
87
- } else if (body.error) {
88
- code = body.error.code ?? null;
89
- message = body.error.message ?? message;
90
- }
91
- } catch {
92
- }
93
- return new ExecutionContextApiError(message, response.status, code);
94
- }
95
- async function signedFetch(input) {
96
- const body = input.body ?? "";
97
- const signature = await signEcpHttpRequest({
98
- ec: input.ecid,
99
- method: input.method,
100
- pathAndQuery: input.pathAndQuery,
101
- body,
102
- privateKey: input.privateKey
103
- });
104
- return (input.fetchFn ?? fetch)(new URL(input.pathAndQuery, input.apiUrl), {
105
- method: input.method,
106
- signal: input.signal,
107
- headers: {
108
- ...input.headers,
109
- [ecpSignatureHeader]: formatEcpSignatureHeader(signature),
110
- ...input.runId ? { [ecpRunHeader]: input.runId } : {}
111
- },
112
- ...input.method === "GET" || input.method === "HEAD" ? {} : { body: typeof body === "string" ? body : Buffer.from(body) }
113
- });
114
- }
115
- async function generateContextKey() {
116
- const pair = await crypto.subtle.generateKey({ name: "Ed25519" }, true, [
117
- "sign",
118
- "verify"
119
- ]);
120
- const privateJwk = await crypto.subtle.exportKey(
121
- "jwk",
122
- pair.privateKey
123
- );
124
- const publicKeyJwk = {
125
- kty: "OKP",
126
- crv: "Ed25519",
127
- x: String(privateJwk.x)
128
- };
129
- const privateKeyJwk = {
130
- ...publicKeyJwk,
131
- d: String(privateJwk.d)
132
- };
133
- return { publicKeyJwk, privateKeyJwk };
134
- }
135
- function importContextKey(privateJwk) {
136
- return importEd25519PrivateKey(privateJwk);
137
- }
138
- async function registerContext(input) {
139
- const fetchFn = input.fetchFn ?? fetch;
140
- const query = input.org ? `?org=${encodeURIComponent(input.org)}` : "";
141
- const auth = { authorization: `Bearer ${input.token}` };
142
- const challengeResponse = await fetchFn(
143
- new URL(
144
- `${executionContextsPath}/registration-challenge${query}`,
145
- input.apiUrl
146
- ),
147
- { method: "POST", headers: auth }
148
- );
149
- if (!challengeResponse.ok) throw await registrationError(challengeResponse);
150
- const { challenge } = await challengeResponse.json();
151
- const body = JSON.stringify({
152
- name: input.name,
153
- publicKeyJwk: input.publicKeyJwk,
154
- challenge,
155
- capabilities: input.capabilities,
156
- client: input.client
157
- });
158
- const response = await signedFetch({
159
- apiUrl: input.apiUrl,
160
- ecid: input.thumbprint,
161
- privateKey: input.privateKey,
162
- method: "POST",
163
- pathAndQuery: `${executionContextsPath}${query}`,
164
- body,
165
- headers: { ...auth, "content-type": "application/json" },
166
- fetchFn
167
- });
168
- if (!response.ok) throw await registrationError(response);
169
- return await response.json();
170
- }
171
- async function registrationError(response) {
172
- const error = await readError(response);
173
- if (error.code === "credential_scope" || error.message.includes("predates execution context permissions")) {
174
- return new ExecutionContextApiError(
175
- error.message.includes("kody login") ? error.message : `${error.message.trim()} ${reloginHint}`,
176
- error.status,
177
- error.code
178
- );
179
- }
180
- return error;
181
- }
182
- async function requestConnectTicket(input) {
183
- const response = await signedFetch({
184
- ...input,
185
- method: "POST",
186
- pathAndQuery: `${executionContextsPath}/connect-ticket`,
187
- body: "{}",
188
- headers: { "content-type": "application/json" }
189
- });
190
- if (!response.ok) throw await readError(response);
191
- return await response.json();
192
- }
193
- async function fetchServerKeys(input) {
194
- const response = await (input.fetchFn ?? fetch)(
195
- new URL(`${executionContextsPath}/server-keys`, input.apiUrl)
196
- );
197
- if (!response.ok) throw await readError(response);
198
- const set = await verifyServerKeySet({ document: await response.json() });
199
- if (!set) {
200
- throw new Error(
201
- "Kody server keys failed root signature verification. Refusing to connect."
202
- );
203
- }
204
- const now = input.now ?? Date.now();
205
- return set.keys.filter((key) => key.notAfter > now);
206
- }
207
- async function apiJson(input) {
208
- const url = new URL(input.path, input.apiUrl);
209
- if (input.org) url.searchParams.set("org", input.org);
210
- const response = await (input.fetchFn ?? fetch)(url, {
211
- method: input.method,
212
- headers: {
213
- authorization: `Bearer ${input.token}`,
214
- ...input.body === void 0 ? {} : { "content-type": "application/json" }
215
- },
216
- ...input.body === void 0 ? {} : { body: JSON.stringify(input.body) }
217
- });
218
- if (!response.ok) throw await readError(response);
219
- return await response.json();
220
- }
221
-
222
- // src/execution-context/daemon.ts
223
- function runScopedFetch(input) {
224
- const apiOrigin = new URL(input.apiUrl).origin;
225
- const base = input.fetchFn ?? fetch;
226
- return async (resource, init) => {
227
- const request = new Request(resource, init);
228
- const url = new URL(request.url);
229
- if (url.origin !== apiOrigin) return base(request);
230
- const body = new Uint8Array(await request.arrayBuffer());
231
- const headers = {};
232
- request.headers.forEach((value, name) => {
233
- if (name !== "authorization") headers[name] = value;
234
- });
235
- return signedFetch({
236
- apiUrl: input.apiUrl,
237
- ecid: input.ecid,
238
- privateKey: input.privateKey,
239
- method: request.method,
240
- pathAndQuery: `${url.pathname}${url.search}`,
241
- body,
242
- runId: input.runId,
243
- headers,
244
- fetchFn: base
245
- });
246
- };
247
- }
248
- function originOf(url) {
249
- try {
250
- return new URL(url).origin;
251
- } catch {
252
- return null;
253
- }
254
- }
255
- function runRequestRefusal(request, apiUrl, now = Date.now()) {
256
- const origin = originOf(request.apiUrl);
257
- if (!origin || origin !== originOf(apiUrl)) return "grant_mismatch";
258
- if (now > request.acceptBy) return "deadline_passed";
259
- return null;
260
- }
261
- function grantFsOf(grant) {
262
- const fs = grant?.fs;
263
- if (!Array.isArray(fs)) return [];
264
- return fs.filter(
265
- (entry) => typeof entry?.path === "string" && typeof entry?.mode === "string"
266
- );
267
- }
268
- var layerLabel = {
269
- server_grant: "server grant",
270
- local_policy: "local policy"
271
- };
272
- var welcomeTimeoutMs = 15e3;
273
- var welcomeTimeoutCloseCode = 4e3;
274
- var closeSettleMs = 5e3;
275
- var defaultPingMs = 3e4;
276
- var defaultPongTimeoutMs = 1e4;
277
- var heartbeatTimeoutCloseCode = 4001;
278
- var frameRejectedCloseCode = 4008;
279
- function heartbeatSetting(value, fallback) {
280
- return typeof value === "number" && Number.isFinite(value) && value >= 1e3 && value <= 3e5 ? value : fallback;
281
- }
282
- async function runDaemonConnection(input) {
283
- const Socket = input.WebSocketImpl ?? globalThis.WebSocket;
284
- if (!Socket) {
285
- throw new Error(
286
- "This Node.js has no global WebSocket. Use Node 22 or newer."
287
- );
288
- }
289
- const { ticket } = await requestConnectTicket(input);
290
- if (input.signal?.aborted) return { code: 1e3, reason: "shutdown" };
291
- const url = new URL(`${executionContextsPath}/connect`, input.apiUrl);
292
- url.protocol = url.protocol === "http:" ? "ws:" : "wss:";
293
- url.searchParams.set("ticket", ticket);
294
- const ws = new Socket(url.toString());
295
- let welcomed = false;
296
- let grantFs = [];
297
- let hostFs = emptyEffectiveFs;
298
- const effectiveFsNow = async () => {
299
- if (!input.fs) return emptyEffectiveFs;
300
- try {
301
- return await input.fs.effective(grantFs);
302
- } catch (error) {
303
- input.log(
304
- `Host folders are off: ${error instanceof Error ? error.message : String(error)}`
305
- );
306
- return emptyEffectiveFs;
307
- }
308
- };
309
- const capabilities = () => {
310
- const base = Array.isArray(input.capabilities.features) ? input.capabilities.features : [];
311
- return {
312
- ...input.capabilities,
313
- maxConcurrent,
314
- features: [
315
- ...base.filter((feature) => feature !== "fs"),
316
- ...fsFeatures(hostFs)
317
- ]
318
- };
319
- };
320
- const applyFs = async () => {
321
- if (!input.fs) return;
322
- hostFs = await effectiveFsNow();
323
- for (const mount of hostFs.mounts) {
324
- input.log(
325
- `Host folder ${mount.path} is available to runs (${mount.mode}).`
326
- );
327
- }
328
- for (const refusal of hostFs.refused) {
329
- input.log(
330
- `Host folder ${refusal.path} is not available: ${refusal.reason} (${layerLabel[refusal.layer]}).`
331
- );
332
- }
333
- };
334
- const refreshFs = async (before = JSON.stringify(capabilities())) => {
335
- await applyFs();
336
- const next = capabilities();
337
- if (welcomed && JSON.stringify(next) !== before) {
338
- await send("capabilities.update", { capabilities: next });
339
- }
340
- };
341
- const unsubscribeFs = input.fs?.onChange?.(() => {
342
- if (welcomed) void refreshFs().catch(() => {
343
- });
344
- });
345
- const serverKeys = new Map(input.serverKeys.map((key) => [key.kid, key]));
346
- let sid = "";
347
- let inSeq = 0;
348
- let outSeq = 0;
349
- const runs = /* @__PURE__ */ new Map();
350
- let maxConcurrent = input.maxConcurrent;
351
- const applyLimits = (grant) => {
352
- const limit = grant?.limits?.maxConcurrent;
353
- const previous = maxConcurrent;
354
- maxConcurrent = typeof limit === "number" && limit >= 1 ? Math.min(input.maxConcurrent, Math.floor(limit)) : input.maxConcurrent;
355
- return maxConcurrent !== previous;
356
- };
357
- let outbound = Promise.resolve();
358
- let outboundFailed = false;
359
- const send = (t, body, re) => {
360
- const sent = outbound.then(async () => {
361
- if (outboundFailed) throw new Error("This connection already failed.");
362
- outSeq += 1;
363
- const payload = {
364
- v: 1,
365
- t,
366
- ec: input.ecid,
367
- sid,
368
- seq: outSeq,
369
- ts: Date.now(),
370
- ...re === void 0 ? {} : { re },
371
- body
372
- };
373
- ws.send(
374
- await signFrame({
375
- privateKey: input.privateKey,
376
- kid: ecpContextKeyId,
377
- payload
378
- })
379
- );
380
- });
381
- outbound = sent.catch(() => {
382
- if (outboundFailed) return;
383
- outboundFailed = true;
384
- try {
385
- ws.close(4e3, "send failed");
386
- } catch {
387
- }
388
- });
389
- return sent;
390
- };
391
- let grantEgress = ecpDefaultGrant.egress;
392
- const applyGrant = (grant) => {
393
- const egress = grant?.egress;
394
- if (egress && typeof egress.mode === "string") grantEgress = egress;
395
- };
396
- let rearmHeartbeat = null;
397
- const status = () => ({
398
- running: runs.size,
399
- maxConcurrent,
400
- acceptingRuns: runs.size < maxConcurrent
401
- });
402
- const startRun = async (run) => {
403
- const startedAt = Date.now();
404
- const committedAt = run.committedAt ?? startedAt;
405
- let deadlineHit = false;
406
- const timer = setTimeout(
407
- () => {
408
- deadlineHit = true;
409
- run.abort.abort();
410
- },
411
- Math.max(0, run.request.deadline - Date.now())
412
- );
413
- let result;
414
- try {
415
- if (input.fs) hostFs = await effectiveFsNow();
416
- result = await input.execute({
417
- request: run.request,
418
- // A getter, so a grant.update or policy change narrows runs already in flight.
419
- ...input.fs ? { hostFs: () => hostFs } : {},
420
- signal: run.abort.signal,
421
- egress: grantEgress,
422
- fetchFn: runScopedFetch({
423
- apiUrl: input.apiUrl,
424
- ecid: input.ecid,
425
- runId: run.request.runId,
426
- privateKey: input.privateKey,
427
- ...input.fetchFn ? { fetchFn: input.fetchFn } : {}
428
- })
429
- });
430
- } catch (error) {
431
- result = {
432
- isError: true,
433
- content: [
434
- {
435
- type: "text",
436
- text: error instanceof Error ? error.message : String(error)
437
- }
438
- ]
439
- };
440
- } finally {
441
- clearTimeout(timer);
442
- }
443
- const endedAt = Date.now();
444
- const { timing: executorTiming, ...outcome } = result;
445
- const resultBytes = new TextEncoder().encode(
446
- JSON.stringify(outcome)
447
- ).byteLength;
448
- const timing = {
449
- queueMs: startedAt - committedAt,
450
- setupMs: executorTiming?.setupMs ?? 0,
451
- ...executorTiming?.packageGraphMs !== void 0 ? {
452
- packageGraphMs: executorTiming.packageGraphMs,
453
- packageGraphCached: executorTiming.packageGraphCached === true
454
- } : {},
455
- executeMs: executorTiming?.executeMs ?? endedAt - startedAt,
456
- daemonMs: endedAt - committedAt
457
- };
458
- runs.delete(run.request.runId);
459
- await send("run.result", {
460
- runId: run.request.runId,
461
- ...outcome,
462
- // The local deadline stopped it: a cancel, not a code error.
463
- ...deadlineHit && result.isError ? { cancelReason: "deadline" } : {},
464
- startedAt,
465
- endedAt,
466
- resultBytes,
467
- timing
468
- });
469
- await send("status", status());
470
- };
471
- const handle = async (frame) => {
472
- const body = frame.body;
473
- const runId = typeof body.runId === "string" ? body.runId : "";
474
- switch (frame.t) {
475
- case "welcome":
476
- clearTimeout(welcomeTimer);
477
- applyGrant(body.grant);
478
- applyLimits(body.grant);
479
- if (input.pingMs === void 0 && input.pongTimeoutMs === void 0) {
480
- rearmHeartbeat?.(
481
- heartbeatSetting(body.pingMs, defaultPingMs),
482
- heartbeatSetting(body.pongTimeoutMs, defaultPongTimeoutMs)
483
- );
484
- }
485
- grantFs = grantFsOf(body.grant);
486
- await applyFs();
487
- welcomed = true;
488
- await send("hello", {
489
- protocol: { min: ecpProtocolVersion, max: ecpProtocolVersion },
490
- client: input.client,
491
- capabilities: capabilities(),
492
- grantVersion: body.grantVersion,
493
- status: status(),
494
- // Kody ends committed runs this daemon no longer holds right away.
495
- heldRuns: [...runs.values()].filter((run) => run.committed).map((run) => run.request.runId),
496
- pendingResults: []
497
- });
498
- input.log("Connected. Waiting for runs.");
499
- return;
500
- case "run.request": {
501
- const request = body;
502
- if (runs.size >= maxConcurrent) {
503
- await send("run.reject", { runId, code: "busy" }, frame.seq);
504
- return;
505
- }
506
- const refusal = runRequestRefusal(request, input.apiUrl);
507
- if (refusal) {
508
- await send("run.reject", { runId, code: refusal }, frame.seq);
509
- return;
510
- }
511
- runs.set(runId, {
512
- request,
513
- abort: new AbortController(),
514
- committed: false
515
- });
516
- await send("run.accept", { runId }, frame.seq);
517
- return;
518
- }
519
- case "run.commit": {
520
- const run = runs.get(runId);
521
- if (!run || run.committed) return;
522
- run.committed = true;
523
- run.committedAt = Date.now();
524
- input.log(
525
- `Running ${runId} for ${run.request.requestedBy.handle ?? run.request.requestedBy.userId}.`
526
- );
527
- void startRun(run);
528
- return;
529
- }
530
- case "run.abort":
531
- case "run.cancel": {
532
- const run = runs.get(runId);
533
- run?.abort.abort();
534
- if (!run?.committed) runs.delete(runId);
535
- if (frame.t === "run.cancel")
536
- await send("run.cancel.ack", { runId }, frame.seq);
537
- return;
538
- }
539
- case "grant.update": {
540
- applyGrant(body.grant);
541
- grantFs = grantFsOf(body.grant);
542
- const before = JSON.stringify(capabilities());
543
- const limitsChanged = applyLimits(body.grant);
544
- await refreshFs(before);
545
- await send("grant.ack", { grantVersion: body.grantVersion }, frame.seq);
546
- if (limitsChanged) await send("status", status());
547
- return;
548
- }
549
- case "revoke":
550
- input.log(
551
- `This context was revoked (${String(body.reason ?? "revoked")}).`
552
- );
553
- ws.close(1e3, "revoked");
554
- return;
555
- case "error":
556
- input.log(`Kody: ${String(body.code)} ${String(body.message ?? "")}`);
557
- return;
558
- default:
559
- return;
560
- }
561
- };
562
- const timeoutMs = input.welcomeTimeoutMs ?? welcomeTimeoutMs;
563
- let welcomeTimer;
564
- return await new Promise((resolve) => {
565
- let lastInboundAt = Date.now();
566
- let ping;
567
- let pongTimer;
568
- const armHeartbeat = (pingMs, pongTimeoutMs) => {
569
- clearInterval(ping);
570
- ping = setInterval(() => {
571
- if (ws.readyState !== ws.OPEN || pongTimer) return;
572
- const sentAt = Date.now();
573
- ws.send(ecpPingFrame);
574
- pongTimer = setTimeout(() => {
575
- pongTimer = void 0;
576
- if (lastInboundAt >= sentAt) return;
577
- input.log(
578
- `Kody did not answer a ping within ${Math.round(pongTimeoutMs / 1e3)}s, so the connection is dead. Closing and reconnecting.`
579
- );
580
- closeAndSettle(heartbeatTimeoutCloseCode, "heartbeat timeout");
581
- }, pongTimeoutMs);
582
- }, pingMs);
583
- };
584
- rearmHeartbeat = armHeartbeat;
585
- armHeartbeat(
586
- input.pingMs ?? defaultPingMs,
587
- input.pongTimeoutMs ?? defaultPongTimeoutMs
588
- );
589
- let settled = false;
590
- let settleTimer;
591
- const finish = (code, reason) => {
592
- if (settled) return;
593
- settled = true;
594
- clearInterval(ping);
595
- clearTimeout(pongTimer);
596
- clearTimeout(welcomeTimer);
597
- clearTimeout(settleTimer);
598
- unsubscribeFs?.();
599
- input.signal?.removeEventListener("abort", shutdown);
600
- for (const run of runs.values()) run.abort.abort();
601
- resolve({ code, reason });
602
- };
603
- const closeAndSettle = (code, reason) => {
604
- try {
605
- ws.close(code, reason);
606
- } catch {
607
- }
608
- settleTimer ??= setTimeout(
609
- () => finish(code, reason),
610
- input.closeSettleMs ?? closeSettleMs
611
- );
612
- };
613
- welcomeTimer = setTimeout(() => {
614
- input.log(
615
- `Kody did not send a welcome frame within ${Math.round(timeoutMs / 1e3)}s, so this context cannot come online. Closing and retrying.`
616
- );
617
- closeAndSettle(welcomeTimeoutCloseCode, "welcome timeout");
618
- }, timeoutMs);
619
- const shutdown = () => closeAndSettle(1e3, "shutdown");
620
- if (input.signal?.aborted) shutdown();
621
- input.signal?.addEventListener("abort", shutdown, { once: true });
622
- const rejectFrame = (code) => {
623
- input.log(
624
- `Kody sent a frame that failed verification (${code}). Closing and reconnecting.`
625
- );
626
- closeAndSettle(frameRejectedCloseCode, code);
627
- };
628
- let inbound = Promise.resolve();
629
- ws.addEventListener("message", (event) => {
630
- lastInboundAt = Date.now();
631
- const text = typeof event.data === "string" ? event.data : "";
632
- inbound = inbound.then(() => onMessage(text)).catch((error) => input.log(`Frame error: ${String(error)}`));
633
- });
634
- const onMessage = async (text) => {
635
- if (settled || settleTimer) return;
636
- const classified = classifyFrameText(text);
637
- if (classified.kind !== "frame") return;
638
- const key = serverKeys.get(classified.envelope.k);
639
- if (!key) {
640
- rejectFrame("unknown_server_key");
641
- return;
642
- }
643
- if (!sid) {
644
- sid = peekSid(classified.envelope.p);
645
- }
646
- const verified = await verifyFrame({
647
- envelope: classified.envelope,
648
- publicKey: await importEd25519PublicKey(publishedKeyJwk(key)),
649
- expect: { ec: input.ecid, sid, lastSeq: inSeq },
650
- now: Date.now()
651
- });
652
- if (!verified.ok) {
653
- rejectFrame(verified.code);
654
- return;
655
- }
656
- inSeq = verified.frame.seq;
657
- await handle(verified.frame);
658
- };
659
- ws.addEventListener("close", (event) => finish(event.code, event.reason));
660
- });
661
- }
662
- function peekSid(p) {
663
- try {
664
- const decoded = decodeEnvelopePayload(p);
665
- return decoded?.t === "welcome" && typeof decoded.body?.sid === "string" ? decoded.body.sid : "";
666
- } catch {
667
- return "";
668
- }
669
- }
670
- async function runDaemon(input) {
671
- let attempt = 0;
672
- while (!input.signal?.aborted) {
673
- const startedAt = Date.now();
674
- try {
675
- const closed = await runDaemonConnection(input);
676
- if (closed.reason === "revoked") return;
677
- input.log(
678
- `Disconnected (${closed.code}${closed.reason ? ` ${closed.reason}` : ""}). Reconnecting.`
679
- );
680
- } catch (error) {
681
- if (input.signal?.aborted) return;
682
- if (isExperimentOffError(error)) throw experimentOffError(input.apiUrl);
683
- input.log(
684
- `Connect failed: ${error instanceof Error ? error.message : String(error)}`
685
- );
686
- }
687
- if (Date.now() - startedAt > 6e4) attempt = 0;
688
- attempt += 1;
689
- const delay = Math.min(6e4, 1e3 * 2 ** Math.min(attempt, 6));
690
- await abortableDelay(delay * (0.5 + Math.random() / 2), input.signal);
691
- }
692
- }
693
- function abortableDelay(ms, signal) {
694
- return new Promise((resolve) => {
695
- if (signal?.aborted) return resolve();
696
- const done = () => {
697
- clearTimeout(timer);
698
- signal?.removeEventListener("abort", done);
699
- resolve();
700
- };
701
- const timer = setTimeout(done, ms);
702
- signal?.addEventListener("abort", done, { once: true });
703
- });
704
- }
705
-
706
- // src/execution-context/keystore.ts
707
- import {
708
- createCipheriv,
709
- createDecipheriv,
710
- randomBytes,
711
- scryptSync
712
- } from "node:crypto";
713
- import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
714
- import { dirname, join } from "node:path";
715
- import { Entry } from "@napi-rs/keyring";
716
- var contextKeyPassphraseEnvVar = "KODY_CONTEXT_KEY_PASSPHRASE";
717
- function contextsDir(apiUrl) {
718
- return join(dirname(apiTokenFileStorePath(apiUrl)), "contexts");
719
- }
720
- function contextDir(apiUrl, ecid) {
721
- if (!/^ec_[A-Za-z0-9_-]+$/.test(ecid)) {
722
- throw new Error(`Not an execution context id: ${ecid}`);
723
- }
724
- return join(contextsDir(apiUrl), ecid);
725
- }
726
- function contextWorkersDir(apiUrl, ecid) {
727
- return join(contextDir(apiUrl, ecid), "workers");
728
- }
729
- function resolveWrappingKey(input) {
730
- const env = input.env ?? process.env;
731
- const passphrase = env[contextKeyPassphraseEnvVar];
732
- if (passphrase) {
733
- return {
734
- kind: "passphrase",
735
- key: (salt) => scryptSync(passphrase, salt ?? Buffer.alloc(16), 32, {
736
- N: 1 << 15,
737
- r: 8,
738
- p: 1,
739
- maxmem: 64 * 1024 * 1024
740
- })
741
- };
742
- }
743
- const account = `execution-context:${input.ecid}`;
744
- let entry;
745
- try {
746
- entry = input.keyringFactory ? input.keyringFactory(account) : new Entry(keyringService, account, secretServiceKeyringOptions);
747
- } catch {
748
- throw noWrappingKeyError();
749
- }
750
- return {
751
- kind: "keyring",
752
- key: () => {
753
- let stored = null;
754
- try {
755
- stored = entry.getPassword();
756
- } catch {
757
- stored = null;
758
- }
759
- if (stored) return Buffer.from(stored, "base64url");
760
- if (!input.create) {
761
- throw new Error(
762
- "The key for this execution context is missing from the OS keyring. Re-register the machine with `kody context register`."
763
- );
764
- }
765
- const fresh = randomBytes(32);
766
- try {
767
- entry.setPassword(fresh.toString("base64url"));
768
- } catch {
769
- throw noWrappingKeyError();
770
- }
771
- return fresh;
772
- }
773
- };
774
- }
775
- function noWrappingKeyError() {
776
- return new Error(
777
- `No OS keyring is available to protect this machine's execution context key. Set ${contextKeyPassphraseEnvVar} to a strong passphrase and retry.`
778
- );
779
- }
780
- function encryptPrivateKey(privateJwk, wrapping) {
781
- const salt = wrapping.kind === "passphrase" ? randomBytes(16) : null;
782
- const key = wrapping.key(salt);
783
- const iv = randomBytes(12);
784
- const cipher = createCipheriv("aes-256-gcm", key, iv);
785
- const data = Buffer.concat([
786
- cipher.update(JSON.stringify(privateJwk), "utf8"),
787
- cipher.final()
788
- ]);
789
- return {
790
- version: 1,
791
- wrap: wrapping.kind,
792
- ...salt ? { salt: salt.toString("base64url") } : {},
793
- iv: iv.toString("base64url"),
794
- tag: cipher.getAuthTag().toString("base64url"),
795
- data: data.toString("base64url")
796
- };
797
- }
798
- function decryptPrivateKey(file, wrapping) {
799
- if (file.wrap !== wrapping.kind) {
800
- throw new Error(
801
- file.wrap === "passphrase" ? `This context key is protected by a passphrase. Set ${contextKeyPassphraseEnvVar}.` : `This context key is protected by the OS keyring. Unset ${contextKeyPassphraseEnvVar}.`
802
- );
803
- }
804
- const key = wrapping.key(
805
- file.salt ? Buffer.from(file.salt, "base64url") : null
806
- );
807
- const decipher = createDecipheriv(
808
- "aes-256-gcm",
809
- key,
810
- Buffer.from(file.iv, "base64url")
811
- );
812
- decipher.setAuthTag(Buffer.from(file.tag, "base64url"));
813
- try {
814
- const plain = Buffer.concat([
815
- decipher.update(Buffer.from(file.data, "base64url")),
816
- decipher.final()
817
- ]);
818
- return JSON.parse(plain.toString("utf8"));
819
- } catch {
820
- throw new Error(
821
- "Could not decrypt the execution context key. The passphrase or keyring entry does not match."
822
- );
823
- }
824
- }
825
- function saveContext(input) {
826
- const dir = contextDir(input.context.apiUrl, input.context.ecid);
827
- mkdirSync(dir, { recursive: true, mode: 448 });
828
- const keyPath = join(dir, "key.enc");
829
- writeFileSync(
830
- keyPath,
831
- JSON.stringify(encryptPrivateKey(input.privateJwk, input.wrapping)),
832
- { mode: 384 }
833
- );
834
- chmodSync(keyPath, 384);
835
- writeFileSync(
836
- join(dir, "context.json"),
837
- `${JSON.stringify(input.context, null, 2)}
838
- `,
839
- { mode: 384 }
840
- );
841
- }
842
- function loadContext(input) {
843
- const dir = contextDir(input.apiUrl, input.ecid);
844
- const context = JSON.parse(
845
- readFileSync(join(dir, "context.json"), "utf8")
846
- );
847
- const file = JSON.parse(readFileSync(join(dir, "key.enc"), "utf8"));
848
- return { context, privateJwk: decryptPrivateKey(file, input.wrapping) };
849
- }
850
-
851
- // src/execution-context/commands.ts
852
- var defaultMaxConcurrentRuns = 2;
853
- function maxConcurrentRuns(value = process.env.KODY_CONTEXT_MAX_CONCURRENT) {
854
- if (value === void 0 || value === "") return defaultMaxConcurrentRuns;
855
- const parsed = Number(value);
856
- if (!Number.isInteger(parsed) || parsed < 1 || parsed > ecpMaxConcurrentRunsCap) {
857
- throw new Error(
858
- `--max-concurrent (or KODY_CONTEXT_MAX_CONCURRENT) must be a whole number from 1 to ${ecpMaxConcurrentRunsCap}; got ${value}.`
859
- );
860
- }
861
- return parsed;
862
- }
863
- function localCapabilities(maxConcurrent = defaultMaxConcurrentRuns) {
864
- return {
865
- runtime: "workerd",
866
- node: process.versions.node,
867
- os: platform(),
868
- cpuCount: cpus().length,
869
- memoryMb: Math.round(totalmem() / (1024 * 1024)),
870
- maxConcurrent,
871
- features: []
872
- };
873
- }
874
- function storedContextIds(apiUrl) {
875
- try {
876
- return readdirSync(contextsDir(apiUrl)).filter(
877
- (entry) => entry.startsWith("ec_")
878
- );
879
- } catch {
880
- return [];
881
- }
882
- }
883
- function out(input, value, text) {
884
- input.write(
885
- input.values.json ? `${JSON.stringify(value, null, 2)}
886
- ` : `${text}
887
- `
888
- );
889
- }
890
- async function runExecutionContextCommand(input) {
891
- try {
892
- return await runCommand(input);
893
- } catch (error) {
894
- if (isExperimentOffError(error)) throw experimentOffError(input.apiUrl);
895
- throw error;
896
- }
897
- }
898
- async function runCommand(input) {
899
- const [sub, ...rest] = input.positionals;
900
- const base = {
901
- apiUrl: input.apiUrl,
902
- ...input.org ? { org: input.org } : {},
903
- ...input.fetchFn ? { fetchFn: input.fetchFn } : {}
904
- };
905
- if (input.command === "context" && sub === "policy") {
906
- return await runPolicyCommand(input, rest);
907
- }
908
- if (input.command === "context" && sub === "register") {
909
- const name = input.values.name ?? rest[0];
910
- if (!name) throw new Error("Pass --name <name> for this machine.");
911
- const { publicKeyJwk, privateKeyJwk } = await generateContextKey();
912
- const privateKey = await importContextKey(privateKeyJwk);
913
- const thumbprint = await ed25519JwkThumbprint(publicKeyJwk);
914
- const registered = await registerContext({
915
- ...base,
916
- token: await input.token(),
917
- name,
918
- publicKeyJwk,
919
- privateKey,
920
- thumbprint,
921
- capabilities: localCapabilities(),
922
- client: { name: "kody-cli", version: input.clientVersion }
923
- });
924
- saveContext({
925
- context: {
926
- version: 1,
927
- ecid: registered.ecid,
928
- name: registered.name,
929
- apiUrl: input.apiUrl,
930
- orgSlug: registered.owner.orgSlug,
931
- publicKeyJwk
932
- },
933
- privateJwk: privateKeyJwk,
934
- wrapping: resolveWrappingKey({ ecid: registered.ecid, create: true })
935
- });
936
- const steps = (registered.nextSteps ?? []).map(
937
- (step) => ` ${step.text ?? ""}${step.cli ? `
938
- ${step.cli}` : ""}`
939
- ).join("\n");
940
- out(
941
- input,
942
- registered,
943
- [
944
- registered.notice ?? `Registered ${registered.name} (${registered.ecid}).`,
945
- steps ? `Next steps:
946
- ${steps}` : "",
947
- "Start it with: kody daemon"
948
- ].filter(Boolean).join("\n")
949
- );
950
- return 0;
951
- }
952
- if (input.command === "context" && (sub === "list" || sub === void 0)) {
953
- const body = await apiJson({
954
- ...base,
955
- token: await input.token(),
956
- method: "GET",
957
- path: "/v1/execution-contexts"
958
- });
959
- const contexts = body.contexts ?? [];
960
- out(
961
- input,
962
- body,
963
- contexts.length === 0 ? "No execution contexts yet. Register this machine with `kody context register --name <name>`." : contexts.map(
964
- (c) => `${c.name} (${c.id}) ${c.status}${c.usable ? "" : `, not usable: ${c.unusableReason}`}`
965
- ).join("\n")
966
- );
967
- return 0;
968
- }
969
- if (input.command === "context" && (sub === "revoke" || sub === "delete")) {
970
- const ref = rest[0];
971
- if (!ref) throw new Error(`Usage: kody context ${sub} <name|ec id>`);
972
- const id = encodeURIComponent(ref);
973
- const body = await apiJson({
974
- ...base,
975
- token: await input.token(),
976
- ...sub === "revoke" ? { method: "DELETE", path: `/v1/execution-contexts/${id}` } : { method: "POST", path: `/v1/execution-contexts/${id}/delete` }
977
- });
978
- out(
979
- input,
980
- body,
981
- sub === "revoke" ? `Revoked ${ref}. Delete it for good with: kody context delete ${ref}` : `Deleted ${ref}.`
982
- );
983
- return 0;
984
- }
985
- if (input.command === "chain") {
986
- const token = await input.token();
987
- const read = await apiJson({
988
- ...base,
989
- token,
990
- method: "GET",
991
- path: "/v1/execution-chain"
992
- });
993
- const current = chainOf(read);
994
- const contexts = async () => contextsById(
995
- await apiJson({
996
- ...base,
997
- token,
998
- method: "GET",
999
- path: "/v1/execution-contexts"
1000
- })
1001
- );
1002
- const contextMetadata = async () => {
1003
- if (input.values.json) return /* @__PURE__ */ new Map();
1004
- try {
1005
- return await contexts();
1006
- } catch {
1007
- return /* @__PURE__ */ new Map();
1008
- }
1009
- };
1010
- if (sub === "show" || sub === void 0) {
1011
- out(input, read, describeChain(current, await contextMetadata()));
1012
- return 0;
1013
- }
1014
- if (sub !== "add" && sub !== "remove") {
1015
- throw new Error("Usage: kody chain show | add <name> | remove <name>");
1016
- }
1017
- const ref = rest[0];
1018
- if (!ref) throw new Error(`Pass the context name: kody chain ${sub} <name>`);
1019
- const id = await resolveContextId({
1020
- ...base,
1021
- token,
1022
- ref
1023
- });
1024
- const entries = (current.entries ?? []).map(
1025
- (entry) => entry.kind === "cloud" ? { kind: "cloud" } : { kind: "context", id: entry.id }
1026
- ).filter((entry) => !(entry.kind === "context" && entry.id === id));
1027
- if (sub === "add") {
1028
- if (entries.length === 0) entries.push({ kind: "cloud" });
1029
- const cloudAt = entries.findIndex((entry) => entry.kind === "cloud");
1030
- entries.splice(cloudAt === -1 ? entries.length : cloudAt, 0, {
1031
- kind: "context",
1032
- id
1033
- });
1034
- }
1035
- const updated = await apiJson({
1036
- ...base,
1037
- token,
1038
- method: "PUT",
1039
- path: "/v1/execution-chain",
1040
- body: {
1041
- entries,
1042
- strict: !entries.some((entry) => entry.kind === "cloud"),
1043
- ifMatch: current.updatedAt ?? null
1044
- }
1045
- });
1046
- out(
1047
- input,
1048
- updated,
1049
- describeChain(chainOf(updated), await contextMetadata())
1050
- );
1051
- return 0;
1052
- }
1053
- if (input.command === "daemon") {
1054
- if (input.values.maxConcurrent === "") {
1055
- throw new Error("--max-concurrent needs a value.");
1056
- }
1057
- const maxConcurrent = maxConcurrentRuns(input.values.maxConcurrent);
1058
- const ids = input.values.context ? [input.values.context] : storedContextIds(input.apiUrl);
1059
- const ecid = ids[0];
1060
- if (!ecid) {
1061
- throw new Error(
1062
- "This machine has no registered execution context. Run `kody context register --name <name>` first."
1063
- );
1064
- }
1065
- const { context, privateJwk } = loadContext({
1066
- apiUrl: input.apiUrl,
1067
- ecid,
1068
- wrapping: resolveWrappingKey({ ecid, create: false })
1069
- });
1070
- const privateKey = await importContextKey(privateJwk);
1071
- const serverKeys = await fetchServerKeys({ apiUrl: input.apiUrl });
1072
- const { runContextRun } = await import("./run-executor-NNH65ODC.js");
1073
- const abort = new AbortController();
1074
- process.once("SIGINT", () => abort.abort());
1075
- process.once("SIGTERM", () => abort.abort());
1076
- input.write(
1077
- `Starting ${context.name} (${context.ecid}) against ${input.apiUrl}.
1078
- `
1079
- );
1080
- const workersDir = contextWorkersDir(input.apiUrl, context.ecid);
1081
- const reaped = reapLeftoverWorkers(workersDir);
1082
- if (reaped.length > 0) {
1083
- input.write(
1084
- `Stopped ${reaped.length} local worker(s) left running by an earlier daemon for this context.
1085
- `
1086
- );
1087
- }
1088
- const workerTracker = createLocalWorkerTracker(workersDir);
1089
- const packageGraphCache = createPackageGraphCache();
1090
- try {
1091
- await runDaemon({
1092
- apiUrl: input.apiUrl,
1093
- ecid: context.ecid,
1094
- privateKey,
1095
- serverKeys,
1096
- maxConcurrent,
1097
- client: { name: "kody-cli", version: input.clientVersion },
1098
- capabilities: localCapabilities(maxConcurrent),
1099
- execute: (run) => runContextRun({
1100
- ...run,
1101
- apiUrl: input.apiUrl,
1102
- workerTracker,
1103
- packageGraphCache
1104
- }),
1105
- fs: {
1106
- effective: async (grantFs) => await effectiveFs(grantFs, (await readLocalPolicy()).fs),
1107
- onChange: (listener) => {
1108
- const path = localPolicyPath();
1109
- watchFile(path, { interval: 2e3 }, listener);
1110
- return () => unwatchFile(path, listener);
1111
- }
1112
- },
1113
- log: (line) => input.write(`${line}
1114
- `),
1115
- signal: abort.signal
1116
- });
1117
- } finally {
1118
- workerTracker.killAll();
1119
- workerTracker.dispose();
1120
- }
1121
- return 0;
1122
- }
1123
- throw new Error(
1124
- "Usage: kody context register --name <name> [--org <slug>] | kody context list | kody context revoke <name> | kody context delete <name> | kody context policy [show | allow <path> [--mode ro|rw] | remove <path>] | kody chain show | add <name> | remove <name> | kody daemon [--context <ec id>] [--max-concurrent <n>]"
1125
- );
1126
- }
1127
- async function resolveContextId(input) {
1128
- if (input.ref.startsWith("ec_")) return input.ref;
1129
- const body = await apiJson({
1130
- ...input,
1131
- method: "GET",
1132
- path: "/v1/execution-contexts"
1133
- });
1134
- const match = (body.contexts ?? []).find((c) => c.name === input.ref);
1135
- if (!match)
1136
- throw new Error(`No execution context named ${input.ref} in this org.`);
1137
- return match.id;
1138
- }
1139
- function chainOf(body) {
1140
- return body.chain ?? {};
1141
- }
1142
- function contextsById(body) {
1143
- const contexts = body.contexts ?? [];
1144
- return new Map(contexts.map((context) => [context.id, context]));
1145
- }
1146
- function describeChain(chain, contexts = /* @__PURE__ */ new Map()) {
1147
- const entries = chain.entries ?? [];
1148
- const lines = entries.map((entry, index) => {
1149
- if (entry.kind === "cloud") return `${index + 1}. Kody cloud (always last)`;
1150
- const known = entry.id ? contexts.get(entry.id) : void 0;
1151
- const name = entry.name ?? known?.name;
1152
- const label = name ? `${name} (${entry.id})` : String(entry.id);
1153
- const offline = known?.status && known.status !== "online" ? ` [${known.status}]` : "";
1154
- const skipped = entry.usable === false ? ` (skipped: ${entry.unusableReason})` : "";
1155
- return `${index + 1}. ${label}${offline}${skipped}`;
1156
- });
1157
- if (chain.strict) lines.push("Strict: Kody cloud is not in this chain.");
1158
- return lines.join("\n") || "Empty chain.";
1159
- }
1160
- function readCodeFile(path) {
1161
- return readFileSync2(path, "utf8");
1162
- }
1163
- var policyUsage = "Usage: kody context policy [show] | kody context policy allow <path> [--mode ro|rw] | kody context policy remove <path>";
1164
- async function runPolicyCommand(input, [action, path, ...extra]) {
1165
- const file = localPolicyPath();
1166
- const describe = (rules) => rules.length === 0 ? `No host folders are allowed on this machine (${file}). Execution-context runs only see their virtual filesystem.` : [
1167
- `Host folders this machine allows (${file}):`,
1168
- ...rules.map((rule) => ` ${rule.mode} ${rule.path}`),
1169
- "A run can use a folder only if its context grant (grant.fs) also lists it; the narrower mode wins."
1170
- ].join("\n");
1171
- if (action === void 0 || action === "show") {
1172
- const policy = await readLocalPolicy(file);
1173
- out(input, { path: file, ...policy }, describe(policy.fs));
1174
- return 0;
1175
- }
1176
- if (!path || extra.length > 0) throw new Error(policyUsage);
1177
- if (action === "allow") {
1178
- const mode = input.values.mode ?? "ro";
1179
- if (mode !== "ro" && mode !== "rw") {
1180
- throw new Error("--mode must be ro (read-only) or rw (read-write).");
1181
- }
1182
- const { policy, added } = await allowLocalPath({
1183
- path,
1184
- mode,
1185
- policyPath: file
1186
- });
1187
- out(
1188
- input,
1189
- { path: file, ...policy },
1190
- `Allowed ${added.path} (${added.mode}). Running daemons pick this up within a few seconds.
1191
- ${describe(policy.fs)}`
1192
- );
1193
- return 0;
1194
- }
1195
- if (action === "remove") {
1196
- const { policy, removed } = await removeLocalPath({
1197
- path,
1198
- policyPath: file
1199
- });
1200
- out(
1201
- input,
1202
- { path: file, removed, ...policy },
1203
- `${removed ? `Removed ${path}.` : `${path} was not in the policy.`}
1204
- ${describe(policy.fs)}`
1205
- );
1206
- return 0;
1207
- }
1208
- throw new Error(policyUsage);
1209
- }
1210
- export {
1211
- defaultMaxConcurrentRuns,
1212
- localCapabilities,
1213
- maxConcurrentRuns,
1214
- readCodeFile,
1215
- runExecutionContextCommand
1216
- };
1217
- //# sourceMappingURL=commands-DOND3A3A.js.map