@kodycodes/cli 3.31.0 → 3.31.2

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 (67) hide show
  1. package/dist/api-token.d.ts +4 -5
  2. package/dist/{auth-WLRCNZ2R.js → auth-WAXXS43K.js} +6 -6
  3. package/dist/bin.js +9 -7
  4. package/dist/bin.js.map +1 -1
  5. package/dist/{chunk-TULCECSL.js → chunk-3G4MV7KG.js} +2 -2
  6. package/dist/{chunk-B5DE7Z4Z.js → chunk-BOEXYN2R.js} +3 -3
  7. package/dist/{chunk-7OVUYX6A.js → chunk-CQHQFF7B.js} +13 -4
  8. package/dist/chunk-CQHQFF7B.js.map +6 -0
  9. package/dist/{chunk-ERH37XEJ.js → chunk-DOTEM7EU.js} +3 -3
  10. package/dist/{chunk-RPUHFAMS.js → chunk-H7CJBJFA.js} +2 -2
  11. package/dist/{chunk-LTSHHKSM.js → chunk-I5GA5KSS.js} +4 -4
  12. package/dist/{chunk-QGABG53Q.js → chunk-MN5PENPF.js} +3 -3
  13. package/dist/{chunk-5W34SXJW.js → chunk-MW3RLRTO.js} +30 -2
  14. package/dist/{chunk-5W34SXJW.js.map → chunk-MW3RLRTO.js.map} +1 -1
  15. package/dist/{chunk-5TDORXTY.js → chunk-PMFY674W.js} +4 -4
  16. package/dist/{chunk-CMPRZW4Z.js → chunk-QPSCXWFD.js} +6 -6
  17. package/dist/{chunk-CMPRZW4Z.js.map → chunk-QPSCXWFD.js.map} +1 -1
  18. package/dist/{commands-FNEOMNRD.js → chunk-Z2NJN47S.js} +94 -2739
  19. package/dist/chunk-Z2NJN47S.js.map +6 -0
  20. package/dist/{chunk-ZZPTD4VW.js → chunk-ZFK4EJKZ.js} +96 -42
  21. package/dist/chunk-ZFK4EJKZ.js.map +6 -0
  22. package/dist/{chunk-DNNA7ZIR.js → chunk-ZSCFP2ST.js} +3 -3
  23. package/dist/cli-credential.d.ts +9 -0
  24. package/dist/cli.js +9 -7
  25. package/dist/commands-3CZ5DOQA.js +2788 -0
  26. package/dist/commands-3CZ5DOQA.js.map +6 -0
  27. package/dist/{dev-command-RDDJYUVX.js → dev-command-HLWRDQGM.js} +9 -9
  28. package/dist/{git-credential-TZIWXKU5.js → git-credential-VERDXSG2.js} +7 -7
  29. package/dist/{local-execute-7Z7DOD3W.js → local-execute-SNWFJZVF.js} +11 -11
  30. package/dist/{local-package-graph-JZTRUXX6.js → local-package-graph-QAKOKW2R.js} +5 -5
  31. package/dist/{local-package-run-3VU5X7NB.js → local-package-run-7YMW3JUC.js} +9 -9
  32. package/dist/{local-secrets-EYYWBNJR.js → local-secrets-VINTQOMK.js} +5 -5
  33. package/dist/{mock-dep-resolve-HSEGGULX.js → mock-dep-resolve-D65JLWMH.js} +4 -4
  34. package/dist/{mock-local-deps-JM7WEOC6.js → mock-local-deps-Q6GG4HKA.js} +6 -6
  35. package/dist/{open-api-client-XV523Z26.js → open-api-client-6BTG3NTF.js} +5 -5
  36. package/dist/package-local-runtime-source.d.ts +10 -3
  37. package/dist/publish-builder.js +8 -3
  38. package/dist/{remote-execute-FUMYJS2B.js → remote-execute-CUD3J4LA.js} +5 -5
  39. package/dist/{run-executor-NMZGN2MG.js → run-executor-J3MF4RCT.js} +2 -2
  40. package/dist/{setup-git-GW3PNDG4.js → setup-git-CZ7ECZNT.js} +6 -6
  41. package/dist/{whoami-LISXTMTO.js → whoami-NILYMYMX.js} +4 -4
  42. package/package.json +1 -1
  43. package/dist/chunk-7OVUYX6A.js.map +0 -6
  44. package/dist/chunk-ZZPTD4VW.js.map +0 -6
  45. package/dist/commands-FNEOMNRD.js.map +0 -6
  46. /package/dist/{auth-WLRCNZ2R.js.map → auth-WAXXS43K.js.map} +0 -0
  47. /package/dist/{chunk-TULCECSL.js.map → chunk-3G4MV7KG.js.map} +0 -0
  48. /package/dist/{chunk-B5DE7Z4Z.js.map → chunk-BOEXYN2R.js.map} +0 -0
  49. /package/dist/{chunk-ERH37XEJ.js.map → chunk-DOTEM7EU.js.map} +0 -0
  50. /package/dist/{chunk-RPUHFAMS.js.map → chunk-H7CJBJFA.js.map} +0 -0
  51. /package/dist/{chunk-LTSHHKSM.js.map → chunk-I5GA5KSS.js.map} +0 -0
  52. /package/dist/{chunk-QGABG53Q.js.map → chunk-MN5PENPF.js.map} +0 -0
  53. /package/dist/{chunk-5TDORXTY.js.map → chunk-PMFY674W.js.map} +0 -0
  54. /package/dist/{chunk-DNNA7ZIR.js.map → chunk-ZSCFP2ST.js.map} +0 -0
  55. /package/dist/{dev-command-RDDJYUVX.js.map → dev-command-HLWRDQGM.js.map} +0 -0
  56. /package/dist/{git-credential-TZIWXKU5.js.map → git-credential-VERDXSG2.js.map} +0 -0
  57. /package/dist/{local-execute-7Z7DOD3W.js.map → local-execute-SNWFJZVF.js.map} +0 -0
  58. /package/dist/{local-package-graph-JZTRUXX6.js.map → local-package-graph-QAKOKW2R.js.map} +0 -0
  59. /package/dist/{local-package-run-3VU5X7NB.js.map → local-package-run-7YMW3JUC.js.map} +0 -0
  60. /package/dist/{local-secrets-EYYWBNJR.js.map → local-secrets-VINTQOMK.js.map} +0 -0
  61. /package/dist/{mock-dep-resolve-HSEGGULX.js.map → mock-dep-resolve-D65JLWMH.js.map} +0 -0
  62. /package/dist/{mock-local-deps-JM7WEOC6.js.map → mock-local-deps-Q6GG4HKA.js.map} +0 -0
  63. /package/dist/{open-api-client-XV523Z26.js.map → open-api-client-6BTG3NTF.js.map} +0 -0
  64. /package/dist/{remote-execute-FUMYJS2B.js.map → remote-execute-CUD3J4LA.js.map} +0 -0
  65. /package/dist/{run-executor-NMZGN2MG.js.map → run-executor-J3MF4RCT.js.map} +0 -0
  66. /package/dist/{setup-git-GW3PNDG4.js.map → setup-git-CZ7ECZNT.js.map} +0 -0
  67. /package/dist/{whoami-LISXTMTO.js.map → whoami-NILYMYMX.js.map} +0 -0
@@ -0,0 +1,2788 @@
1
+ import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
2
+ import {
3
+ killWindowsTree,
4
+ windowsFileLaunch,
5
+ windowsShellLaunch
6
+ } from "./chunk-LQNGII7U.js";
7
+ import {
8
+ acquireRunnerLock,
9
+ apiJson,
10
+ autoUpdateSetting,
11
+ checkContextLogin,
12
+ checkForUpdate,
13
+ classifyFrameText,
14
+ contextWorkersDir,
15
+ decodeEnvelopePayload,
16
+ describeHolder,
17
+ disableOwnService,
18
+ ecpContextKeyId,
19
+ ecpDefaultGrant,
20
+ ecpHostOperatorOnlyFeature,
21
+ ecpMaxConcurrentRunsCap,
22
+ ecpPingFrame,
23
+ ecpProtocolVersion,
24
+ ed25519JwkThumbprint,
25
+ executionContextsPath,
26
+ experimentOffError,
27
+ fetchServerKeys,
28
+ fileWrappingKey,
29
+ generateContextKey,
30
+ importContextKey,
31
+ importEd25519PublicKey,
32
+ isExperimentOffError,
33
+ isPermanentContextRefusal,
34
+ isRemoteDaemonCommand,
35
+ isServiceManager,
36
+ launcherEnvVar,
37
+ loadContext,
38
+ localContextId,
39
+ lockPathFor,
40
+ newerInstalledVersion,
41
+ offerInstall,
42
+ offerUninstallAfterRevoke,
43
+ otherLocalDaemons,
44
+ publishedKeyJwk,
45
+ registerContext,
46
+ relaunchExitCode,
47
+ requestConnectTicket,
48
+ resolveWrappingKey,
49
+ rotateLog,
50
+ runAutoUpdateCommand,
51
+ runDaemonEnvCommand,
52
+ runDaemonServiceCommand,
53
+ runRemoteDaemonCommand,
54
+ runUpdate,
55
+ saveContext,
56
+ saveServiceEnvAssignments,
57
+ serviceEnvVar,
58
+ serviceManagerFor,
59
+ servicePaths,
60
+ setContextCommands,
61
+ signFrame,
62
+ signedFetch,
63
+ startDaemonUpdater,
64
+ startupRefusedExitCode,
65
+ stayStoppedExitCode,
66
+ storedContextIds,
67
+ superviseNewerVersion,
68
+ supervisedEnvVar,
69
+ terminalConfirm,
70
+ verifyFrame,
71
+ wrappingKeyForStoredContext,
72
+ writeJson
73
+ } from "./chunk-Z2NJN47S.js";
74
+ import {
75
+ allowLocalPath,
76
+ canonicalHostPath,
77
+ credentialDenylist,
78
+ effectiveFs,
79
+ emptyEffectiveFs,
80
+ fsFeatures,
81
+ isAbsolute,
82
+ isDeniedPath,
83
+ isWithin,
84
+ localPolicyPath,
85
+ plainPath,
86
+ readLocalCommandsEnabled,
87
+ readLocalPolicy,
88
+ removeLocalPath,
89
+ samePath,
90
+ setLocalAutoUpdateEnabled,
91
+ setLocalCommandsEnabled,
92
+ windowsCommandLine
93
+ } from "./chunk-ATZXCAZA.js";
94
+ import "./chunk-YFNQZPEP.js";
95
+ import "./chunk-RE7LNPRO.js";
96
+ import "./chunk-NKH2L5RA.js";
97
+ import "./chunk-YVWOK4LV.js";
98
+ import "./chunk-UW6AWLXX.js";
99
+
100
+ // src/execution-context/commands.ts
101
+ import {
102
+ appendFileSync,
103
+ existsSync,
104
+ readFileSync as readFileSync2,
105
+ rmSync as rmSync2,
106
+ unwatchFile,
107
+ watchFile
108
+ } from "node:fs";
109
+ import { cpus, platform, totalmem } from "node:os";
110
+
111
+ // src/execution-context/daemon.ts
112
+ function runScopedFetch(input) {
113
+ const apiOrigin = new URL(input.apiUrl).origin;
114
+ const base = input.fetchFn ?? fetch;
115
+ return async (resource, init) => {
116
+ const request = new Request(resource, init);
117
+ const url = new URL(request.url);
118
+ if (url.origin !== apiOrigin) return base(request);
119
+ const body = new Uint8Array(await request.arrayBuffer());
120
+ const headers = {};
121
+ request.headers.forEach((value, name) => {
122
+ if (name !== "authorization") headers[name] = value;
123
+ });
124
+ return signedFetch({
125
+ apiUrl: input.apiUrl,
126
+ ecid: input.ecid,
127
+ privateKey: input.privateKey,
128
+ method: request.method,
129
+ pathAndQuery: `${url.pathname}${url.search}`,
130
+ body,
131
+ runId: input.runId,
132
+ headers,
133
+ fetchFn: base
134
+ });
135
+ };
136
+ }
137
+ function originOf(url) {
138
+ try {
139
+ return new URL(url).origin;
140
+ } catch {
141
+ return null;
142
+ }
143
+ }
144
+ function runRequestRefusal(request, apiUrl, now = Date.now()) {
145
+ const origin = originOf(request.apiUrl);
146
+ if (!origin || origin !== originOf(apiUrl)) return "grant_mismatch";
147
+ if (now > request.acceptBy) return "deadline_passed";
148
+ return null;
149
+ }
150
+ var daemonControlFeature = "daemon-control";
151
+ var DaemonControlError = class extends Error {
152
+ constructor(code, message) {
153
+ super(message);
154
+ this.code = code;
155
+ this.name = "DaemonControlError";
156
+ }
157
+ code;
158
+ };
159
+ function pauseOf(value) {
160
+ const pause = value;
161
+ return pause && typeof pause.at === "string" ? {
162
+ at: pause.at,
163
+ by: typeof pause.by === "string" ? pause.by : null,
164
+ reason: typeof pause.reason === "string" ? pause.reason : null
165
+ } : null;
166
+ }
167
+ function grantFsOf(grant) {
168
+ const fs = grant?.fs;
169
+ if (!Array.isArray(fs)) return [];
170
+ return fs.filter(
171
+ (entry) => typeof entry?.path === "string" && typeof entry?.mode === "string"
172
+ );
173
+ }
174
+ var layerLabel = {
175
+ server_grant: "server grant",
176
+ credential_denylist: "credential denylist",
177
+ local_policy: "local policy"
178
+ };
179
+ var welcomeTimeoutMs = 15e3;
180
+ var welcomeTimeoutCloseCode = 4e3;
181
+ var closeSettleMs = 5e3;
182
+ var defaultPingMs = 3e4;
183
+ var defaultPongTimeoutMs = 1e4;
184
+ var heartbeatTimeoutCloseCode = 4001;
185
+ var frameRejectedCloseCode = 4008;
186
+ function heartbeatSetting(value, fallback) {
187
+ return typeof value === "number" && Number.isFinite(value) && value >= 1e3 && value <= 3e5 ? value : fallback;
188
+ }
189
+ async function runDaemonConnection(input) {
190
+ const Socket = input.WebSocketImpl ?? globalThis.WebSocket;
191
+ if (!Socket) {
192
+ throw new Error(
193
+ "This Node.js has no global WebSocket. Use Node 22 or newer."
194
+ );
195
+ }
196
+ const { ticket } = await requestConnectTicket(input);
197
+ if (input.signal?.aborted) return { code: 1e3, reason: "shutdown" };
198
+ const url = new URL(`${executionContextsPath}/connect`, input.apiUrl);
199
+ url.protocol = url.protocol === "http:" ? "ws:" : "wss:";
200
+ url.searchParams.set("ticket", ticket);
201
+ const ws = new Socket(url.toString());
202
+ let welcomed = false;
203
+ let grantFs = [];
204
+ let hostFs = emptyEffectiveFs;
205
+ const effectiveFsNow = async () => {
206
+ if (!input.fs) return emptyEffectiveFs;
207
+ try {
208
+ return await input.fs.effective(grantFs);
209
+ } catch (error) {
210
+ input.log(
211
+ `Host folders are off: ${error instanceof Error ? error.message : String(error)}`
212
+ );
213
+ return emptyEffectiveFs;
214
+ }
215
+ };
216
+ const capabilities = () => {
217
+ const base = Array.isArray(input.capabilities.features) ? input.capabilities.features : [];
218
+ return {
219
+ ...input.capabilities,
220
+ ...input.extraCapabilities?.(),
221
+ maxConcurrent,
222
+ features: [
223
+ ...base.filter(
224
+ (feature) => feature !== "fs" && feature !== ecpHostOperatorOnlyFeature
225
+ ),
226
+ ecpHostOperatorOnlyFeature,
227
+ ...input.control ? [daemonControlFeature] : [],
228
+ ...fsFeatures(hostFs)
229
+ ]
230
+ };
231
+ };
232
+ const applyFs = async () => {
233
+ if (!input.fs) return;
234
+ hostFs = await effectiveFsNow();
235
+ for (const mount of hostFs.mounts) {
236
+ input.log(
237
+ `Host folder ${mount.path} is available to runs (${mount.mode}).`
238
+ );
239
+ }
240
+ for (const refusal of hostFs.refused) {
241
+ input.log(
242
+ `Host folder ${refusal.path} is not available: ${refusal.reason} (${layerLabel[refusal.layer]}).`
243
+ );
244
+ }
245
+ };
246
+ const refreshFs = async (before = JSON.stringify(capabilities())) => {
247
+ await applyFs();
248
+ const next = capabilities();
249
+ if (welcomed && JSON.stringify(next) !== before) {
250
+ await send("capabilities.update", { capabilities: next });
251
+ }
252
+ };
253
+ const unsubscribeFs = input.fs?.onChange?.(() => {
254
+ if (welcomed) void refreshFs().catch(() => {
255
+ });
256
+ });
257
+ const serverKeys = new Map(input.serverKeys.map((key) => [key.kid, key]));
258
+ let sid = "";
259
+ let inSeq = 0;
260
+ let outSeq = 0;
261
+ const runs = /* @__PURE__ */ new Map();
262
+ let maxConcurrent = input.maxConcurrent;
263
+ const applyLimits = (grant) => {
264
+ const limit = grant?.limits?.maxConcurrent;
265
+ const previous = maxConcurrent;
266
+ maxConcurrent = typeof limit === "number" && limit >= 1 ? Math.min(input.maxConcurrent, Math.floor(limit)) : input.maxConcurrent;
267
+ return maxConcurrent !== previous;
268
+ };
269
+ let outbound = Promise.resolve();
270
+ let outboundFailed = false;
271
+ const send = (t, body, re) => {
272
+ const sent = outbound.then(async () => {
273
+ if (outboundFailed) throw new Error("This connection already failed.");
274
+ if (ws.readyState !== ws.OPEN)
275
+ throw new Error("This connection is not open.");
276
+ outSeq += 1;
277
+ const payload = {
278
+ v: 1,
279
+ t,
280
+ ec: input.ecid,
281
+ sid,
282
+ seq: outSeq,
283
+ ts: Date.now(),
284
+ ...re === void 0 ? {} : { re },
285
+ body
286
+ };
287
+ ws.send(
288
+ await signFrame({
289
+ privateKey: input.privateKey,
290
+ kid: ecpContextKeyId,
291
+ payload
292
+ })
293
+ );
294
+ });
295
+ outbound = sent.catch(() => {
296
+ if (outboundFailed) return;
297
+ outboundFailed = true;
298
+ try {
299
+ ws.close(4e3, "send failed");
300
+ } catch {
301
+ }
302
+ });
303
+ return sent;
304
+ };
305
+ let grantEgress = ecpDefaultGrant.egress;
306
+ const applyGrant = (grant) => {
307
+ const egress = grant?.egress;
308
+ if (egress && typeof egress.mode === "string") grantEgress = egress;
309
+ input.hostCommands?.setGrantEnabled(
310
+ grant?.commands?.enabled === true
311
+ );
312
+ };
313
+ const reporter = async (finished) => {
314
+ await send("command.finished", finished);
315
+ };
316
+ let connectionEnded = false;
317
+ let rearmHeartbeat = null;
318
+ const status = () => ({
319
+ running: runs.size,
320
+ maxConcurrent,
321
+ acceptingRuns: !input.drainSignal?.aborted && runs.size < maxConcurrent
322
+ });
323
+ let closeWhenDrained = () => {
324
+ };
325
+ const startRun = async (run) => {
326
+ const startedAt = Date.now();
327
+ const committedAt = run.committedAt ?? startedAt;
328
+ let deadlineHit = false;
329
+ const timer = setTimeout(
330
+ () => {
331
+ deadlineHit = true;
332
+ run.abort.abort();
333
+ },
334
+ Math.max(0, run.request.deadline - Date.now())
335
+ );
336
+ let result;
337
+ try {
338
+ if (input.fs) hostFs = await effectiveFsNow();
339
+ const operatorRun = run.request.sharedRun !== true;
340
+ result = await input.execute({
341
+ request: run.request,
342
+ // A getter, so a grant.update or policy change narrows runs already in flight.
343
+ ...input.fs && operatorRun ? { hostFs: () => hostFs } : {},
344
+ signal: run.abort.signal,
345
+ ...input.hostCommands && operatorRun ? { hostCommands: input.hostCommands } : {},
346
+ egress: grantEgress,
347
+ fetchFn: runScopedFetch({
348
+ apiUrl: input.apiUrl,
349
+ ecid: input.ecid,
350
+ runId: run.request.runId,
351
+ privateKey: input.privateKey,
352
+ ...input.fetchFn ? { fetchFn: input.fetchFn } : {}
353
+ })
354
+ });
355
+ } catch (error) {
356
+ result = {
357
+ isError: true,
358
+ content: [
359
+ {
360
+ type: "text",
361
+ text: error instanceof Error ? error.message : String(error)
362
+ }
363
+ ]
364
+ };
365
+ } finally {
366
+ clearTimeout(timer);
367
+ }
368
+ const endedAt = Date.now();
369
+ const { timing: executorTiming, ...outcome } = result;
370
+ const resultBytes = new TextEncoder().encode(
371
+ JSON.stringify(outcome)
372
+ ).byteLength;
373
+ const timing = {
374
+ queueMs: startedAt - committedAt,
375
+ setupMs: executorTiming?.setupMs ?? 0,
376
+ ...executorTiming?.packageGraphMs !== void 0 ? {
377
+ packageGraphMs: executorTiming.packageGraphMs,
378
+ packageGraphCached: executorTiming.packageGraphCached === true
379
+ } : {},
380
+ executeMs: executorTiming?.executeMs ?? endedAt - startedAt,
381
+ daemonMs: endedAt - committedAt
382
+ };
383
+ runs.delete(run.request.runId);
384
+ if (input.activity) input.activity.runs = runs.size;
385
+ await send("run.result", {
386
+ runId: run.request.runId,
387
+ ...outcome,
388
+ // The local deadline stopped it: a cancel, not a code error.
389
+ ...deadlineHit && result.isError ? { cancelReason: "deadline" } : {},
390
+ startedAt,
391
+ endedAt,
392
+ resultBytes,
393
+ timing
394
+ });
395
+ await send("status", status());
396
+ closeWhenDrained();
397
+ };
398
+ const handle = async (frame) => {
399
+ const body = frame.body;
400
+ const runId = typeof body.runId === "string" ? body.runId : "";
401
+ switch (frame.t) {
402
+ case "welcome":
403
+ clearTimeout(welcomeTimer);
404
+ applyGrant(body.grant);
405
+ applyLimits(body.grant);
406
+ if (input.pingMs === void 0 && input.pongTimeoutMs === void 0) {
407
+ rearmHeartbeat?.(
408
+ heartbeatSetting(body.pingMs, defaultPingMs),
409
+ heartbeatSetting(body.pongTimeoutMs, defaultPongTimeoutMs)
410
+ );
411
+ }
412
+ grantFs = grantFsOf(body.grant);
413
+ await applyFs();
414
+ input.onPaused?.(pauseOf(body.paused));
415
+ welcomed = true;
416
+ await send("hello", {
417
+ protocol: { min: ecpProtocolVersion, max: ecpProtocolVersion },
418
+ client: input.client,
419
+ capabilities: capabilities(),
420
+ grantVersion: body.grantVersion,
421
+ status: status(),
422
+ // Kody ends committed runs this daemon no longer holds right away.
423
+ heldRuns: [...runs.values()].filter((run) => run.committed).map((run) => run.request.runId),
424
+ pendingResults: []
425
+ });
426
+ if (!connectionEnded) input.hostCommands?.setReporter(reporter);
427
+ input.log("Connected. Waiting for runs.");
428
+ return;
429
+ case "run.request": {
430
+ const request = body;
431
+ if (input.drainSignal?.aborted || runs.size >= maxConcurrent) {
432
+ await send("run.reject", { runId, code: "busy" }, frame.seq);
433
+ return;
434
+ }
435
+ const refusal = runRequestRefusal(request, input.apiUrl);
436
+ if (refusal) {
437
+ await send("run.reject", { runId, code: refusal }, frame.seq);
438
+ return;
439
+ }
440
+ runs.set(runId, {
441
+ request,
442
+ abort: new AbortController(),
443
+ committed: false
444
+ });
445
+ if (input.activity) input.activity.runs = runs.size;
446
+ await send("run.accept", { runId }, frame.seq);
447
+ return;
448
+ }
449
+ case "run.commit": {
450
+ const run = runs.get(runId);
451
+ if (!run || run.committed) return;
452
+ run.committed = true;
453
+ run.committedAt = Date.now();
454
+ input.log(
455
+ `Running ${runId} for ${run.request.requestedBy.handle ?? run.request.requestedBy.userId}.`
456
+ );
457
+ void startRun(run);
458
+ return;
459
+ }
460
+ case "run.abort":
461
+ case "run.cancel": {
462
+ const run = runs.get(runId);
463
+ run?.abort.abort();
464
+ if (!run?.committed) runs.delete(runId);
465
+ if (input.activity) input.activity.runs = runs.size;
466
+ if (frame.t === "run.cancel")
467
+ await send("run.cancel.ack", { runId }, frame.seq);
468
+ return;
469
+ }
470
+ case "grant.update": {
471
+ applyGrant(body.grant);
472
+ grantFs = grantFsOf(body.grant);
473
+ const before = JSON.stringify(capabilities());
474
+ const limitsChanged = applyLimits(body.grant);
475
+ await refreshFs(before);
476
+ await send("grant.ack", { grantVersion: body.grantVersion }, frame.seq);
477
+ if (limitsChanged) await send("status", status());
478
+ return;
479
+ }
480
+ case "state.update":
481
+ input.onPaused?.(pauseOf(body.paused));
482
+ return;
483
+ case "control.request": {
484
+ const id = typeof body.id === "string" ? body.id : "";
485
+ const op = typeof body.op === "string" ? body.op : "";
486
+ const args = body.args && typeof body.args === "object" ? body.args : {};
487
+ const control = input.control;
488
+ const re = frame.seq;
489
+ void (async () => {
490
+ try {
491
+ if (!control) {
492
+ throw new DaemonControlError(
493
+ "daemon_outdated",
494
+ "This daemon does not take remote control requests."
495
+ );
496
+ }
497
+ const data = await control(op, args);
498
+ await send("control.result", { id, ok: true, data }, re);
499
+ } catch (error) {
500
+ await send(
501
+ "control.result",
502
+ {
503
+ id,
504
+ ok: false,
505
+ code: error instanceof DaemonControlError ? error.code : "daemon_control_failed",
506
+ message: error instanceof Error ? error.message : String(error)
507
+ },
508
+ re
509
+ ).catch(() => {
510
+ });
511
+ }
512
+ })();
513
+ return;
514
+ }
515
+ case "revoke":
516
+ input.log(
517
+ `This context was revoked (${String(body.reason ?? "revoked")}).`
518
+ );
519
+ ws.close(1e3, "revoked");
520
+ return;
521
+ case "error":
522
+ input.log(`Kody: ${String(body.code)} ${String(body.message ?? "")}`);
523
+ return;
524
+ default:
525
+ return;
526
+ }
527
+ };
528
+ const timeoutMs = input.welcomeTimeoutMs ?? welcomeTimeoutMs;
529
+ let welcomeTimer;
530
+ return await new Promise((resolve) => {
531
+ let lastInboundAt = Date.now();
532
+ let ping;
533
+ let pongTimer;
534
+ const armHeartbeat = (pingMs, pongTimeoutMs) => {
535
+ clearInterval(ping);
536
+ ping = setInterval(() => {
537
+ if (ws.readyState !== ws.OPEN || pongTimer) return;
538
+ const sentAt = Date.now();
539
+ ws.send(ecpPingFrame);
540
+ pongTimer = setTimeout(() => {
541
+ pongTimer = void 0;
542
+ if (lastInboundAt >= sentAt) return;
543
+ input.log(
544
+ `Kody did not answer a ping within ${Math.round(pongTimeoutMs / 1e3)}s, so the connection is dead. Closing and reconnecting.`
545
+ );
546
+ closeAndSettle(heartbeatTimeoutCloseCode, "heartbeat timeout");
547
+ }, pongTimeoutMs);
548
+ }, pingMs);
549
+ };
550
+ rearmHeartbeat = armHeartbeat;
551
+ armHeartbeat(
552
+ input.pingMs ?? defaultPingMs,
553
+ input.pongTimeoutMs ?? defaultPongTimeoutMs
554
+ );
555
+ let settled = false;
556
+ let settleTimer;
557
+ const finish = (code, reason) => {
558
+ if (settled) return;
559
+ settled = true;
560
+ connectionEnded = true;
561
+ input.hostCommands?.clearReporter(reporter);
562
+ clearInterval(ping);
563
+ clearTimeout(pongTimer);
564
+ clearTimeout(welcomeTimer);
565
+ clearTimeout(settleTimer);
566
+ clearInterval(holdTimer);
567
+ unsubscribeFs?.();
568
+ input.signal?.removeEventListener("abort", shutdown);
569
+ input.drainSignal?.removeEventListener("abort", drain);
570
+ for (const run of runs.values()) run.abort.abort();
571
+ resolve({ code, reason });
572
+ };
573
+ const closeAndSettle = (code, reason) => {
574
+ try {
575
+ ws.close(code, reason);
576
+ } catch {
577
+ }
578
+ settleTimer ??= setTimeout(
579
+ () => finish(code, reason),
580
+ input.closeSettleMs ?? closeSettleMs
581
+ );
582
+ };
583
+ welcomeTimer = setTimeout(() => {
584
+ input.log(
585
+ `Kody did not send a welcome frame within ${Math.round(timeoutMs / 1e3)}s, so this context cannot come online. Closing and retrying.`
586
+ );
587
+ closeAndSettle(welcomeTimeoutCloseCode, "welcome timeout");
588
+ }, timeoutMs);
589
+ const shutdown = () => closeAndSettle(1e3, "shutdown");
590
+ if (input.signal?.aborted) shutdown();
591
+ input.signal?.addEventListener("abort", shutdown, { once: true });
592
+ let holdTimer;
593
+ closeWhenDrained = () => {
594
+ if (!input.drainSignal?.aborted) return;
595
+ if ([...runs.values()].some((run) => run.committed)) return;
596
+ if (input.drainHold?.()) {
597
+ holdTimer ??= setInterval(
598
+ () => closeWhenDrained(),
599
+ input.drainHoldPollMs ?? 5e3
600
+ );
601
+ return;
602
+ }
603
+ closeAndSettle(1e3, "shutdown");
604
+ };
605
+ const drain = () => {
606
+ input.log(
607
+ runs.size > 0 ? `Stopping after ${runs.size} run(s) in flight finish. New runs go to the next context in the chain.` : "Stopping."
608
+ );
609
+ if (welcomed) void send("status", status()).catch(() => {
610
+ });
611
+ closeWhenDrained();
612
+ };
613
+ if (input.drainSignal?.aborted) drain();
614
+ else input.drainSignal?.addEventListener("abort", drain, { once: true });
615
+ const rejectFrame = (code) => {
616
+ input.log(
617
+ `Kody sent a frame that failed verification (${code}). Closing and reconnecting.`
618
+ );
619
+ closeAndSettle(frameRejectedCloseCode, code);
620
+ };
621
+ let inbound = Promise.resolve();
622
+ ws.addEventListener("message", (event) => {
623
+ lastInboundAt = Date.now();
624
+ const text = typeof event.data === "string" ? event.data : "";
625
+ inbound = inbound.then(() => onMessage(text)).catch((error) => input.log(`Frame error: ${String(error)}`));
626
+ });
627
+ const onMessage = async (text) => {
628
+ if (settled || settleTimer) return;
629
+ const classified = classifyFrameText(text);
630
+ if (classified.kind !== "frame") return;
631
+ const key = serverKeys.get(classified.envelope.k);
632
+ if (!key) {
633
+ rejectFrame("unknown_server_key");
634
+ return;
635
+ }
636
+ if (!sid) {
637
+ sid = peekSid(classified.envelope.p);
638
+ }
639
+ const verified = await verifyFrame({
640
+ envelope: classified.envelope,
641
+ publicKey: await importEd25519PublicKey(publishedKeyJwk(key)),
642
+ expect: { ec: input.ecid, sid, lastSeq: inSeq },
643
+ now: Date.now()
644
+ });
645
+ if (!verified.ok) {
646
+ rejectFrame(verified.code);
647
+ return;
648
+ }
649
+ inSeq = verified.frame.seq;
650
+ await handle(verified.frame);
651
+ };
652
+ ws.addEventListener("close", (event) => finish(event.code, event.reason));
653
+ });
654
+ }
655
+ function peekSid(p) {
656
+ try {
657
+ const decoded = decodeEnvelopePayload(p);
658
+ return decoded?.t === "welcome" && typeof decoded.body?.sid === "string" ? decoded.body.sid : "";
659
+ } catch {
660
+ return "";
661
+ }
662
+ }
663
+ async function runDaemon(input) {
664
+ let attempt = 0;
665
+ const stopping = () => input.signal?.aborted || input.drainSignal?.aborted;
666
+ while (!stopping()) {
667
+ const startedAt = Date.now();
668
+ try {
669
+ const closed = await runDaemonConnection(input);
670
+ if (closed.reason === "revoked") return "revoked";
671
+ if (stopping()) return "shutdown";
672
+ if (closed.code === 1012 && closed.reason === "replaced") {
673
+ return "replaced";
674
+ }
675
+ input.log(
676
+ `Disconnected (${closed.code}${closed.reason ? ` ${closed.reason}` : ""}). Reconnecting.`
677
+ );
678
+ } catch (error) {
679
+ if (stopping()) return "shutdown";
680
+ if (isExperimentOffError(error)) throw experimentOffError(input.apiUrl);
681
+ if (isPermanentContextRefusal(error)) {
682
+ input.log(
683
+ `Kody refused this context: ${error instanceof Error ? error.message : String(error)} Stopping for good.`
684
+ );
685
+ return error.reason === "revoked" ? "revoked" : "unknown_context";
686
+ }
687
+ input.log(
688
+ `Connect failed: ${error instanceof Error ? error.message : String(error)}`
689
+ );
690
+ }
691
+ if (Date.now() - startedAt > 6e4) attempt = 0;
692
+ attempt += 1;
693
+ const delay = Math.min(6e4, 1e3 * 2 ** Math.min(attempt, 6));
694
+ await abortableDelay(
695
+ delay * (0.5 + Math.random() / 2),
696
+ input.drainSignal ? AbortSignal.any(
697
+ [input.signal, input.drainSignal].filter(
698
+ (signal) => signal !== void 0
699
+ )
700
+ ) : input.signal
701
+ );
702
+ }
703
+ return "shutdown";
704
+ }
705
+ function abortableDelay(ms, signal) {
706
+ return new Promise((resolve) => {
707
+ if (signal?.aborted) return resolve();
708
+ const done = () => {
709
+ clearTimeout(timer);
710
+ signal?.removeEventListener("abort", done);
711
+ resolve();
712
+ };
713
+ const timer = setTimeout(done, ms);
714
+ signal?.addEventListener("abort", done, { once: true });
715
+ });
716
+ }
717
+
718
+ // src/execution-context/host-commands.ts
719
+ import { spawn } from "node:child_process";
720
+ import { randomBytes } from "node:crypto";
721
+ import { realpath, stat } from "node:fs/promises";
722
+ import { homedir } from "node:os";
723
+ import { isAbsolute as isAbsolute2 } from "node:path";
724
+ var HostCommandError = class extends Error {
725
+ constructor(code, message) {
726
+ super(`${message} (${code})`);
727
+ this.code = code;
728
+ this.name = "HostCommandError";
729
+ }
730
+ code;
731
+ };
732
+ var hostCommandLimits = {
733
+ foregroundDefaultTimeoutMs: 6e4,
734
+ foregroundMaxTimeoutMs: 15 * 6e4,
735
+ backgroundDefaultTimeoutMs: 2 * 60 * 6e4,
736
+ backgroundMaxTimeoutMs: 24 * 60 * 6e4,
737
+ defaultOutputBytes: 256 * 1024,
738
+ maxOutputBytes: 4 * 1024 * 1024,
739
+ backgroundBufferBytes: 4 * 1024 * 1024,
740
+ maxOutputReadBytes: 1024 * 1024,
741
+ maxBackgroundJobs: 16,
742
+ keepFinishedJobsMs: 60 * 6e4,
743
+ maxCommandChars: 64 * 1024,
744
+ maxStdinBytes: 5 * 1024 * 1024
745
+ };
746
+ var OutputBuffer = class {
747
+ constructor(capacity) {
748
+ this.capacity = capacity;
749
+ }
750
+ capacity;
751
+ #chunks = [];
752
+ #size = 0;
753
+ /** Bytes ever written. */
754
+ total = 0;
755
+ get dropped() {
756
+ return this.total - this.#size;
757
+ }
758
+ write(chunk) {
759
+ this.total += chunk.length;
760
+ this.#chunks.push(chunk);
761
+ this.#size += chunk.length;
762
+ while (this.#size > this.capacity && this.#chunks.length > 0) {
763
+ const head = this.#chunks[0];
764
+ const over = this.#size - this.capacity;
765
+ if (head.length <= over) {
766
+ this.#chunks.shift();
767
+ this.#size -= head.length;
768
+ } else {
769
+ this.#chunks[0] = head.subarray(over);
770
+ this.#size -= over;
771
+ }
772
+ }
773
+ }
774
+ /** Bytes from absolute `offset` (clamped to what is still kept). */
775
+ read(offset, maxBytes) {
776
+ const all = Buffer.concat(this.#chunks);
777
+ let start = Math.max(offset, this.dropped);
778
+ while (start - this.dropped < all.length && start > offset && isUtf8Continuation(all[start - this.dropped]))
779
+ start++;
780
+ let end = Math.min(start - this.dropped + maxBytes, all.length);
781
+ if (end < all.length && isUtf8Continuation(all[end])) {
782
+ let back = end;
783
+ while (back > start - this.dropped && isUtf8Continuation(all[back]))
784
+ back--;
785
+ if (back > start - this.dropped) end = back;
786
+ else {
787
+ while (end < all.length && isUtf8Continuation(all[end])) end++;
788
+ }
789
+ }
790
+ const slice = all.subarray(start - this.dropped, end);
791
+ return {
792
+ text: slice.toString("utf8"),
793
+ from: start,
794
+ next: start + slice.length,
795
+ skipped: start - offset
796
+ };
797
+ }
798
+ text() {
799
+ return Buffer.concat(this.#chunks).toString("utf8");
800
+ }
801
+ };
802
+ function newCommandId() {
803
+ return `cmd_${randomBytes(9).toString("base64url")}`;
804
+ }
805
+ function clampInt(value, fallback, max, min = 1) {
806
+ if (value === void 0 || value === null) return fallback;
807
+ if (typeof value !== "number" || !Number.isFinite(value)) {
808
+ throw new HostCommandError(
809
+ "invalid_request",
810
+ `Expected a number, got ${typeof value}.`
811
+ );
812
+ }
813
+ return Math.min(Math.max(Math.floor(value), min), max);
814
+ }
815
+ function isUtf8Continuation(byte) {
816
+ return (byte & 192) === 128;
817
+ }
818
+ function shellFor(env) {
819
+ const shell = env.SHELL;
820
+ return shell && isAbsolute2(shell) ? shell : "/bin/sh";
821
+ }
822
+ function killTree(child, signal) {
823
+ if (child.pid === void 0) return;
824
+ if (process.platform === "win32") {
825
+ void killWindowsTree(child.pid, {
826
+ leaderExited: child.exitCode !== null || child.signalCode !== null
827
+ });
828
+ return;
829
+ }
830
+ try {
831
+ process.kill(-child.pid, signal);
832
+ } catch {
833
+ try {
834
+ child.kill(signal);
835
+ } catch {
836
+ }
837
+ }
838
+ }
839
+ function stoppedOutcome(outcome, stoppedByKody) {
840
+ if (!stoppedByKody || process.platform !== "win32") return outcome;
841
+ return { ...outcome, code: null, signal: outcome.signal ?? "SIGKILL" };
842
+ }
843
+ function inheritedCommandEnv(env = process.env) {
844
+ return Object.fromEntries(
845
+ Object.entries(env).filter(([key]) => !/^KODY_/i.test(key))
846
+ );
847
+ }
848
+ var HostCommands = class {
849
+ #jobs = /* @__PURE__ */ new Map();
850
+ #onFinished = null;
851
+ /** Finishes that could not be sent yet (no live connection); sent on the next reporter. */
852
+ #unreported = [];
853
+ #foreground = /* @__PURE__ */ new Map();
854
+ #pendingStarts = 0;
855
+ #localEnabled;
856
+ /** The server grant's commands flag (off from website/API/CLI). */
857
+ #grantEnabled = false;
858
+ #platform;
859
+ #deniedPaths;
860
+ constructor(options = {}) {
861
+ this.#localEnabled = options.localEnabled === true;
862
+ this.#platform = options.platform ?? process.platform;
863
+ this.#deniedPaths = options.deniedPaths ?? credentialDenylist();
864
+ }
865
+ /** Both layers allow commands. */
866
+ get enabled() {
867
+ return this.#localEnabled && this.#grantEnabled;
868
+ }
869
+ setLocalEnabled(enabled) {
870
+ this.#localEnabled = enabled;
871
+ if (!enabled) this.killAll("commands_off");
872
+ }
873
+ setGrantEnabled(enabled) {
874
+ this.#grantEnabled = enabled;
875
+ if (!enabled) this.killAll("commands_off");
876
+ }
877
+ /** Clears the reporter if it is still `report` (a newer connection may own it). */
878
+ clearReporter(report) {
879
+ if (this.#onFinished === report) this.#onFinished = null;
880
+ }
881
+ setReporter(report) {
882
+ this.#onFinished = report;
883
+ if (!report) return;
884
+ const queued = this.#unreported.splice(0);
885
+ for (const finished of queued) this.#report(finished);
886
+ }
887
+ /** Throws the denial a run sees when it may not run commands here. */
888
+ assertAvailable() {
889
+ if (!this.#localEnabled) {
890
+ throw new HostCommandError(
891
+ "execution_context_commands_off",
892
+ "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)."
893
+ );
894
+ }
895
+ if (!this.#grantEnabled) {
896
+ throw new HostCommandError(
897
+ "execution_context_commands_off",
898
+ "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."
899
+ );
900
+ }
901
+ }
902
+ /** Dispatches one `kody.command.<name>(args)` call from a run. */
903
+ async call(name, args, run) {
904
+ this.assertAvailable();
905
+ if (name === "status" || name === "output" || name === "kill" || name === "list") {
906
+ await run.authorize({ lifecycle: name });
907
+ this.assertAvailable();
908
+ }
909
+ switch (name) {
910
+ case "run":
911
+ return await this.run(args, run);
912
+ case "start":
913
+ return await this.start(args, run);
914
+ case "status":
915
+ return this.status(args, run);
916
+ case "output":
917
+ return this.output(args, run);
918
+ case "kill":
919
+ return this.kill(args, run);
920
+ case "list":
921
+ return this.list(run);
922
+ default:
923
+ throw new HostCommandError(
924
+ "invalid_request",
925
+ `Unknown kody.command.${name}. Use run, start, status, output, kill or list.`
926
+ );
927
+ }
928
+ }
929
+ async #prepare(input, background) {
930
+ const raw = typeof input === "string" ? { command: input } : input;
931
+ const spec = raw ?? {};
932
+ if (typeof spec !== "object" || Array.isArray(spec)) {
933
+ throw new HostCommandError(
934
+ "invalid_request",
935
+ "Pass { command } or { file, args }."
936
+ );
937
+ }
938
+ const hasCommand = typeof spec.command === "string" && spec.command.length > 0;
939
+ const hasFile = typeof spec.file === "string" && spec.file.length > 0;
940
+ if (hasCommand === hasFile) {
941
+ throw new HostCommandError(
942
+ "invalid_request",
943
+ "Pass exactly one of `command` (a shell command line) or `file` (an executable, with optional `args`)."
944
+ );
945
+ }
946
+ const args = spec.args ?? [];
947
+ if (!Array.isArray(args) || !args.every((arg2) => typeof arg2 === "string")) {
948
+ throw new HostCommandError(
949
+ "invalid_request",
950
+ "`args` must be an array of strings."
951
+ );
952
+ }
953
+ if (hasCommand && spec.args !== void 0) {
954
+ throw new HostCommandError(
955
+ "invalid_request",
956
+ "`args` goes with `file`, not `command`."
957
+ );
958
+ }
959
+ const display = hasCommand ? spec.command : [spec.file, ...args].join(" ");
960
+ if (display.length > hostCommandLimits.maxCommandChars) {
961
+ throw new HostCommandError("invalid_request", "The command is too long.");
962
+ }
963
+ const cwd = spec.cwd ?? homedir();
964
+ if (typeof cwd !== "string" || !isAbsolute2(cwd)) {
965
+ throw new HostCommandError(
966
+ "invalid_request",
967
+ "`cwd` must be an absolute path on the machine."
968
+ );
969
+ }
970
+ const cwdStat = await stat(cwd).catch(() => null);
971
+ if (!cwdStat?.isDirectory()) {
972
+ throw new HostCommandError(
973
+ "invalid_request",
974
+ `cwd ${cwd} is not a folder on this machine.`
975
+ );
976
+ }
977
+ const realCwd = await realpath(cwd).catch(() => cwd);
978
+ if (isDeniedPath(cwd, this.#deniedPaths, this.#platform) || isDeniedPath(realCwd, this.#deniedPaths, this.#platform)) {
979
+ throw new HostCommandError(
980
+ "invalid_request",
981
+ `cwd ${cwd} holds credentials (the Kody CLI login and context keys, SSH, git, cloud or package-manager logins, or the OS keyring), so commands cannot run there.`
982
+ );
983
+ }
984
+ const extraEnv = spec.env ?? {};
985
+ if (typeof extraEnv !== "object" || Array.isArray(extraEnv) || !Object.entries(extraEnv).every(
986
+ ([key, value]) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(key) && typeof value === "string"
987
+ )) {
988
+ throw new HostCommandError(
989
+ "invalid_request",
990
+ "`env` must map variable names to string values."
991
+ );
992
+ }
993
+ if (spec.stdin !== void 0 && typeof spec.stdin !== "string") {
994
+ throw new HostCommandError("invalid_request", "`stdin` must be a string.");
995
+ }
996
+ if ((spec.stdin?.length ?? 0) > hostCommandLimits.maxStdinBytes) {
997
+ throw new HostCommandError(
998
+ "invalid_request",
999
+ "`stdin` is larger than 5 MB."
1000
+ );
1001
+ }
1002
+ const timeoutMs = background ? clampInt(
1003
+ spec.timeoutMs,
1004
+ hostCommandLimits.backgroundDefaultTimeoutMs,
1005
+ hostCommandLimits.backgroundMaxTimeoutMs,
1006
+ 1e3
1007
+ ) : clampInt(
1008
+ spec.timeoutMs,
1009
+ hostCommandLimits.foregroundDefaultTimeoutMs,
1010
+ hostCommandLimits.foregroundMaxTimeoutMs,
1011
+ 100
1012
+ );
1013
+ const maxOutputBytes = clampInt(
1014
+ spec.maxOutputBytes,
1015
+ hostCommandLimits.defaultOutputBytes,
1016
+ hostCommandLimits.maxOutputBytes,
1017
+ 1024
1018
+ );
1019
+ if (spec.shell !== void 0 && (!hasCommand || spec.shell !== "powershell" && spec.shell !== "cmd")) {
1020
+ throw new HostCommandError(
1021
+ "invalid_request",
1022
+ "`shell` goes with `command` and is 'powershell' or 'cmd' (Windows only)."
1023
+ );
1024
+ }
1025
+ const env = { ...inheritedCommandEnv(), ...extraEnv };
1026
+ const launch = this.#platform !== "win32" ? {
1027
+ file: hasCommand ? shellFor(env) : spec.file,
1028
+ argv: hasCommand ? ["-c", spec.command] : args,
1029
+ verbatim: false
1030
+ } : hasCommand ? windowsShellLaunch(
1031
+ spec.command,
1032
+ spec.shell ?? "powershell",
1033
+ env
1034
+ ) : windowsFileLaunch(spec.file, args, env);
1035
+ return {
1036
+ display,
1037
+ cwd,
1038
+ env,
1039
+ envKeys: Object.keys(extraEnv).sort(),
1040
+ stdin: spec.stdin,
1041
+ timeoutMs,
1042
+ maxOutputBytes,
1043
+ file: launch.file,
1044
+ argv: launch.argv,
1045
+ verbatim: launch.verbatim
1046
+ };
1047
+ }
1048
+ #spawn(prepared) {
1049
+ const child = spawn(prepared.file, prepared.argv, {
1050
+ cwd: prepared.cwd,
1051
+ env: prepared.env,
1052
+ // POSIX: own a process group so killTree reaches grandchildren.
1053
+ // Windows: taskkill /T walks the tree; detached would open a console.
1054
+ detached: this.#platform !== "win32",
1055
+ windowsHide: true,
1056
+ windowsVerbatimArguments: prepared.verbatim,
1057
+ stdio: [prepared.stdin === void 0 ? "ignore" : "pipe", "pipe", "pipe"]
1058
+ });
1059
+ if (prepared.stdin !== void 0 && child.stdin) {
1060
+ child.stdin.on("error", () => {
1061
+ });
1062
+ child.stdin.end(prepared.stdin);
1063
+ }
1064
+ return child;
1065
+ }
1066
+ #report(finished) {
1067
+ const requeue = () => {
1068
+ if (this.#unreported.length < 256) this.#unreported.push(finished);
1069
+ };
1070
+ const report = this.#onFinished;
1071
+ if (!report) return requeue();
1072
+ try {
1073
+ void Promise.resolve(report(finished)).catch(requeue);
1074
+ } catch {
1075
+ requeue();
1076
+ }
1077
+ }
1078
+ async run(raw, run) {
1079
+ const prepared = await this.#prepare(raw, false);
1080
+ const commandId = newCommandId();
1081
+ await run.authorize({
1082
+ commandId,
1083
+ command: prepared.display,
1084
+ cwd: prepared.cwd,
1085
+ envKeys: prepared.envKeys,
1086
+ background: false
1087
+ });
1088
+ this.assertAvailable();
1089
+ const startedAt = Date.now();
1090
+ const stdout = new OutputBuffer(prepared.maxOutputBytes);
1091
+ const stderr = new OutputBuffer(prepared.maxOutputBytes);
1092
+ const ended = { reason: "exited" };
1093
+ const child = this.#spawn(prepared);
1094
+ this.#foreground.set(child, ended);
1095
+ child.stdout?.on("data", (chunk) => stdout.write(chunk));
1096
+ child.stderr?.on("data", (chunk) => stderr.write(chunk));
1097
+ const timer = setTimeout(() => {
1098
+ ended.reason = "timed_out";
1099
+ killTree(child, "SIGKILL");
1100
+ }, prepared.timeoutMs);
1101
+ const onAbort = () => {
1102
+ ended.reason = "cancelled";
1103
+ killTree(child, "SIGKILL");
1104
+ };
1105
+ run.signal.addEventListener("abort", onAbort, { once: true });
1106
+ if (run.signal.aborted) onAbort();
1107
+ const exited = await new Promise((resolve) => {
1108
+ child.once(
1109
+ "error",
1110
+ (error) => resolve({ code: null, signal: null, error: error.message })
1111
+ );
1112
+ child.once("close", (code, signal) => resolve({ code, signal }));
1113
+ });
1114
+ const outcome = stoppedOutcome(exited, ended.reason !== "exited");
1115
+ clearTimeout(timer);
1116
+ this.#foreground.delete(child);
1117
+ run.signal.removeEventListener("abort", onAbort);
1118
+ if (outcome.error) ended.reason = "spawn_failed";
1119
+ const durationMs = Date.now() - startedAt;
1120
+ this.#report({
1121
+ commandId,
1122
+ runId: run.runId,
1123
+ command: prepared.display,
1124
+ cwd: prepared.cwd,
1125
+ exitCode: outcome.code,
1126
+ signal: outcome.signal,
1127
+ durationMs,
1128
+ background: false,
1129
+ reason: ended.reason
1130
+ });
1131
+ if (outcome.error) {
1132
+ throw new HostCommandError(
1133
+ "invalid_request",
1134
+ `Could not start the command: ${outcome.error}`
1135
+ );
1136
+ }
1137
+ return {
1138
+ commandId,
1139
+ exitCode: outcome.code,
1140
+ signal: outcome.signal,
1141
+ timedOut: ended.reason === "timed_out",
1142
+ stdout: stdout.text(),
1143
+ stderr: stderr.text(),
1144
+ stdoutTruncated: stdout.dropped > 0,
1145
+ stderrTruncated: stderr.dropped > 0,
1146
+ durationMs
1147
+ };
1148
+ }
1149
+ async start(raw, run) {
1150
+ this.#sweep();
1151
+ const running = [...this.#jobs.values()].filter(
1152
+ (job2) => job2.state === "running"
1153
+ );
1154
+ if (running.length + this.#pendingStarts >= hostCommandLimits.maxBackgroundJobs) {
1155
+ throw new HostCommandError(
1156
+ "invalid_request",
1157
+ `This machine already runs ${running.length + this.#pendingStarts} background commands. Kill one (kody.command.kill) first.`
1158
+ );
1159
+ }
1160
+ this.#pendingStarts++;
1161
+ let prepared;
1162
+ let commandId;
1163
+ let child;
1164
+ try {
1165
+ prepared = await this.#prepare(raw, true);
1166
+ commandId = newCommandId();
1167
+ await run.authorize({
1168
+ commandId,
1169
+ command: prepared.display,
1170
+ cwd: prepared.cwd,
1171
+ envKeys: prepared.envKeys,
1172
+ background: true
1173
+ });
1174
+ this.assertAvailable();
1175
+ child = this.#spawn(prepared);
1176
+ } finally {
1177
+ this.#pendingStarts--;
1178
+ }
1179
+ const job = {
1180
+ id: commandId,
1181
+ runId: run.runId,
1182
+ ownerUserId: run.requesterUserId,
1183
+ command: prepared.display,
1184
+ cwd: prepared.cwd,
1185
+ child,
1186
+ pid: child.pid,
1187
+ startedAt: Date.now(),
1188
+ endedAt: null,
1189
+ exitCode: null,
1190
+ signal: null,
1191
+ state: "running",
1192
+ stdout: new OutputBuffer(hostCommandLimits.backgroundBufferBytes),
1193
+ stderr: new OutputBuffer(hostCommandLimits.backgroundBufferBytes),
1194
+ done: Promise.resolve(),
1195
+ timer: null,
1196
+ error: null
1197
+ };
1198
+ child.stdout?.on("data", (chunk) => job.stdout.write(chunk));
1199
+ child.stderr?.on("data", (chunk) => job.stderr.write(chunk));
1200
+ job.timer = setTimeout(() => {
1201
+ if (job.state !== "running") return;
1202
+ job.state = "timed_out";
1203
+ killTree(child, "SIGKILL");
1204
+ }, prepared.timeoutMs);
1205
+ job.timer.unref?.();
1206
+ job.done = new Promise((resolve) => {
1207
+ const finish = (code, signal, error) => {
1208
+ if (job.endedAt !== null) return resolve();
1209
+ if (job.timer) clearTimeout(job.timer);
1210
+ ({ code, signal } = stoppedOutcome(
1211
+ { code, signal },
1212
+ job.state === "killed" || job.state === "timed_out"
1213
+ ));
1214
+ job.endedAt = Date.now();
1215
+ job.exitCode = code;
1216
+ job.signal = signal;
1217
+ if (error) {
1218
+ job.state = "failed";
1219
+ job.error = error;
1220
+ } else if (job.state === "running") {
1221
+ job.state = "exited";
1222
+ }
1223
+ this.#report({
1224
+ commandId,
1225
+ runId: job.runId,
1226
+ command: job.command,
1227
+ cwd: job.cwd,
1228
+ exitCode: code,
1229
+ signal,
1230
+ durationMs: job.endedAt - job.startedAt,
1231
+ background: true,
1232
+ reason: job.state === "failed" ? "spawn_failed" : job.state === "killed" ? job.error === "commands_off" ? "commands_off" : "killed" : job.state === "timed_out" ? "timed_out" : "exited"
1233
+ });
1234
+ resolve();
1235
+ };
1236
+ child.once("error", (error) => finish(null, null, error.message));
1237
+ child.once("close", (code, signal) => finish(code, signal));
1238
+ });
1239
+ this.#jobs.set(commandId, job);
1240
+ return {
1241
+ commandId,
1242
+ pid: job.pid ?? null,
1243
+ startedAt: new Date(job.startedAt).toISOString(),
1244
+ timeoutMs: prepared.timeoutMs
1245
+ };
1246
+ }
1247
+ #job(raw, run) {
1248
+ const id = typeof raw === "string" ? raw : raw?.commandId;
1249
+ const job = typeof id === "string" ? this.#jobs.get(id) : void 0;
1250
+ if (!job || job.ownerUserId !== run.requesterUserId) {
1251
+ throw new HostCommandError(
1252
+ "not_found",
1253
+ `No background command ${String(id)} on this machine for you. kody.command.list() shows yours.`
1254
+ );
1255
+ }
1256
+ return job;
1257
+ }
1258
+ #describe(job) {
1259
+ return {
1260
+ commandId: job.id,
1261
+ command: job.command,
1262
+ cwd: job.cwd,
1263
+ state: job.state,
1264
+ pid: job.pid ?? null,
1265
+ exitCode: job.exitCode,
1266
+ signal: job.signal,
1267
+ startedAt: new Date(job.startedAt).toISOString(),
1268
+ endedAt: job.endedAt === null ? null : new Date(job.endedAt).toISOString(),
1269
+ durationMs: (job.endedAt ?? Date.now()) - job.startedAt,
1270
+ stdoutBytes: job.stdout.total,
1271
+ stderrBytes: job.stderr.total,
1272
+ ...job.error && job.state === "failed" ? { error: job.error } : {}
1273
+ };
1274
+ }
1275
+ status(raw, run) {
1276
+ return this.#describe(this.#job(raw, run));
1277
+ }
1278
+ output(raw, run) {
1279
+ const job = this.#job(raw, run);
1280
+ const input = typeof raw === "object" && raw ? raw : {};
1281
+ const maxBytes = clampInt(
1282
+ input.maxBytes,
1283
+ hostCommandLimits.defaultOutputBytes,
1284
+ hostCommandLimits.maxOutputReadBytes
1285
+ );
1286
+ const stdout = job.stdout.read(
1287
+ clampInt(input.stdoutOffset, 0, Number.MAX_SAFE_INTEGER, 0),
1288
+ maxBytes
1289
+ );
1290
+ const stderr = job.stderr.read(
1291
+ clampInt(input.stderrOffset, 0, Number.MAX_SAFE_INTEGER, 0),
1292
+ maxBytes
1293
+ );
1294
+ return {
1295
+ commandId: job.id,
1296
+ state: job.state,
1297
+ exitCode: job.exitCode,
1298
+ stdout: stdout.text,
1299
+ stderr: stderr.text,
1300
+ stdoutOffset: stdout.next,
1301
+ stderrOffset: stderr.next,
1302
+ stdoutSkipped: stdout.skipped,
1303
+ stderrSkipped: stderr.skipped,
1304
+ done: job.state !== "running" && stdout.next >= job.stdout.total && stderr.next >= job.stderr.total
1305
+ };
1306
+ }
1307
+ kill(raw, run) {
1308
+ const job = this.#job(raw, run);
1309
+ const requested = raw?.signal;
1310
+ const signal = requested === "SIGINT" || requested === "SIGKILL" || requested === "SIGTERM" ? requested : "SIGTERM";
1311
+ if (job.state === "running") {
1312
+ job.state = "killed";
1313
+ killTree(job.child, signal);
1314
+ if (signal !== "SIGKILL") {
1315
+ const escalate = setTimeout(() => killTree(job.child, "SIGKILL"), 5e3);
1316
+ escalate.unref?.();
1317
+ }
1318
+ }
1319
+ return this.#describe(job);
1320
+ }
1321
+ list(run) {
1322
+ this.#sweep();
1323
+ return {
1324
+ commands: [...this.#jobs.values()].filter((job) => job.ownerUserId === run.requesterUserId).map((job) => this.#describe(job))
1325
+ };
1326
+ }
1327
+ /** Commands were turned off (or the daemon stops): end every background job. */
1328
+ killAll(reason) {
1329
+ for (const [child, ended] of this.#foreground) {
1330
+ ended.reason = reason === "commands_off" ? "commands_off" : "cancelled";
1331
+ killTree(child, "SIGKILL");
1332
+ }
1333
+ for (const job of this.#jobs.values()) {
1334
+ if (job.state !== "running") continue;
1335
+ job.state = "killed";
1336
+ job.error = reason === "commands_off" ? "commands_off" : null;
1337
+ killTree(job.child, "SIGKILL");
1338
+ }
1339
+ }
1340
+ /** Background jobs still running (auto-update waits for them). */
1341
+ runningBackground() {
1342
+ let count = 0;
1343
+ for (const job of this.#jobs.values()) if (job.state === "running") count++;
1344
+ return count;
1345
+ }
1346
+ async idle() {
1347
+ await Promise.all([...this.#jobs.values()].map((job) => job.done));
1348
+ }
1349
+ #sweep() {
1350
+ const cutoff = Date.now() - hostCommandLimits.keepFinishedJobsMs;
1351
+ for (const [id, job] of this.#jobs) {
1352
+ if (job.endedAt !== null && job.endedAt < cutoff) this.#jobs.delete(id);
1353
+ }
1354
+ }
1355
+ };
1356
+
1357
+ // src/execution-context/package-graph-cache.ts
1358
+ import { createHash } from "node:crypto";
1359
+ function createPackageGraphCache(options = {}) {
1360
+ const maxEntries = options.maxEntries ?? 32;
1361
+ const ttlMs = options.ttlMs ?? 6e4;
1362
+ const now = options.now ?? Date.now;
1363
+ const entries = /* @__PURE__ */ new Map();
1364
+ return {
1365
+ get size() {
1366
+ return entries.size;
1367
+ },
1368
+ slot(scope) {
1369
+ const key = createHash("sha256").update(
1370
+ JSON.stringify([
1371
+ scope.apiUrl,
1372
+ scope.userId,
1373
+ scope.orgId,
1374
+ scope.conversationId ?? null,
1375
+ scope.code
1376
+ ])
1377
+ ).digest("hex");
1378
+ return {
1379
+ get: () => {
1380
+ const entry = entries.get(key);
1381
+ if (!entry) return void 0;
1382
+ entries.delete(key);
1383
+ if (entry.expiresAt <= now()) return void 0;
1384
+ entries.set(key, entry);
1385
+ return entry.graph;
1386
+ },
1387
+ set: (graph) => {
1388
+ entries.delete(key);
1389
+ entries.set(key, { graph, expiresAt: now() + ttlMs });
1390
+ while (entries.size > maxEntries) {
1391
+ const oldest = entries.keys().next().value;
1392
+ if (oldest === void 0) break;
1393
+ entries.delete(oldest);
1394
+ }
1395
+ }
1396
+ };
1397
+ }
1398
+ };
1399
+ }
1400
+
1401
+ // src/execution-context/host-access.ts
1402
+ var grantUsage = "Usage: kody context grant [show] [--context <name>] | kody context grant allow <path> [--mode ro|rw] [--context <name>] | kody context grant remove <path> [--context <name>] | kody context grant lan on|off [--context <name>]";
1403
+ function arg(value) {
1404
+ return /^[\w@%+=:,./\\-]+$/.test(value) ? value : JSON.stringify(value);
1405
+ }
1406
+ function overlaps(a, b) {
1407
+ return isWithin(a, b) || isWithin(b, a);
1408
+ }
1409
+ function contextPageUrl(apiUrl, context) {
1410
+ const slug = context.ownerOrg?.slug;
1411
+ return slug ? `${apiUrl.replace(/\/+$/, "")}/@${slug}/-/execution-contexts/${context.id}` : null;
1412
+ }
1413
+ function lanState(mode) {
1414
+ return mode === "public-and-lan" ? "on" : mode === "allowlist" ? "allowlist only" : "off";
1415
+ }
1416
+ function hostAccessNotes(context, policyFs) {
1417
+ const name = arg(context.name);
1418
+ const grantFs = context.hostAccess?.fs;
1419
+ if (!grantFs) {
1420
+ const count = context.grantSummary?.fs;
1421
+ if (count === void 0) return [];
1422
+ if (policyFs.length > 0 && count === 0) {
1423
+ return [
1424
+ `This machine's local policy allows host folders, but ${context.name}'s server grant lists none (grant.fs: 0), so runs cannot use them. Someone with Contribute or Manage on ${context.name} can turn it on with: kody context grant allow <folder> --mode ro|rw --context ${name}`
1425
+ ];
1426
+ }
1427
+ if (policyFs.length === 0 && count > 0) {
1428
+ return [
1429
+ `${context.name}'s server grant lists host folders, but this machine's local policy allows none, so runs cannot use them. The machine owner can allow one with: kody context policy allow <folder> --mode ro|rw`
1430
+ ];
1431
+ }
1432
+ return [];
1433
+ }
1434
+ const notes = [];
1435
+ for (const rule of policyFs) {
1436
+ if (grantFs.some((entry) => overlaps(entry.path, rule.path))) continue;
1437
+ notes.push(
1438
+ `${rule.path} (local policy ${rule.mode}) is not in ${context.name}'s server grant, so runs cannot use it. Turn it on with: kody context grant allow ${arg(rule.path)} --mode ${rule.mode} --context ${name}`
1439
+ );
1440
+ }
1441
+ for (const entry of grantFs) {
1442
+ if (policyFs.some((rule) => overlaps(entry.path, rule.path))) continue;
1443
+ notes.push(
1444
+ `${entry.path} (server grant ${entry.mode}) is not allowed by this machine's local policy, so runs cannot use it. The machine owner can allow it with: kody context policy allow ${arg(entry.path)} --mode ${entry.mode}`
1445
+ );
1446
+ }
1447
+ return notes;
1448
+ }
1449
+ function describeServerGrant(apiUrl, context) {
1450
+ const fs = context.hostAccess?.fs;
1451
+ const egress = context.hostAccess?.egress.mode ?? context.grantSummary?.egress.mode;
1452
+ const page = contextPageUrl(apiUrl, context);
1453
+ return [
1454
+ `Server grant for ${context.name} (Kody's side; changing it needs Contribute or Manage on the context):`,
1455
+ fs ? fs.length === 0 ? " Host folders (grant.fs): none" : [
1456
+ " Host folders (grant.fs):",
1457
+ ...fs.map((entry) => ` ${entry.mode} ${entry.path}`)
1458
+ ].join("\n") : ` Host folders (grant.fs): ${context.grantSummary?.fs ?? 0}`,
1459
+ ...egress ? [` Local network (grant.egress ${egress}): ${lanState(egress)}`] : [],
1460
+ ...page ? [` Page: ${page}`] : []
1461
+ ].join("\n");
1462
+ }
1463
+ async function getContext(api, id) {
1464
+ const body = await apiJson({
1465
+ ...api,
1466
+ method: "GET",
1467
+ path: `/v1/execution-contexts/${encodeURIComponent(id)}`
1468
+ });
1469
+ return body.context;
1470
+ }
1471
+ async function resolveId(api, ref) {
1472
+ if (ref.startsWith("ec_")) return ref;
1473
+ const body = await apiJson({
1474
+ ...api,
1475
+ method: "GET",
1476
+ path: "/v1/execution-contexts"
1477
+ });
1478
+ const match = (body.contexts ?? []).find((c) => c.name === ref);
1479
+ if (!match) throw new Error(`No execution context named ${ref} in this org.`);
1480
+ return match.id;
1481
+ }
1482
+ async function machineGrantNotes(input) {
1483
+ const ids = storedContextIds(input.apiUrl);
1484
+ if (ids.length === 0) return [];
1485
+ let token;
1486
+ try {
1487
+ token = await input.token();
1488
+ } catch (error) {
1489
+ return [
1490
+ {
1491
+ id: null,
1492
+ name: null,
1493
+ notes: [],
1494
+ error: `Could not check the server grant (grant.fs) for this machine's contexts: ${firstLine(error)}`
1495
+ }
1496
+ ];
1497
+ }
1498
+ return await Promise.all(
1499
+ ids.map(async (id) => {
1500
+ try {
1501
+ const context = await getContext({ ...input, token }, id);
1502
+ return {
1503
+ id,
1504
+ name: context.name,
1505
+ notes: hostAccessNotes(context, input.policyFs)
1506
+ };
1507
+ } catch (error) {
1508
+ return {
1509
+ id,
1510
+ name: null,
1511
+ notes: [],
1512
+ error: `Could not check the server grant for ${id}: ${firstLine(error)}`
1513
+ };
1514
+ }
1515
+ })
1516
+ );
1517
+ }
1518
+ function describeMachineGrantNotes(results) {
1519
+ if (results.length === 0) return "";
1520
+ const lines = results.flatMap(
1521
+ (result) => "error" in result && result.error ? [` ${result.error}`] : result.notes.length === 0 ? [` ${result.name}: server grant and local policy agree.`] : result.notes.map((note) => ` ${note}`)
1522
+ );
1523
+ return `
1524
+ Server grant check (a run can use a folder only if both layers allow it):
1525
+ ${lines.join("\n")}`;
1526
+ }
1527
+ function firstLine(error) {
1528
+ return (error instanceof Error ? error.message : String(error)).split("\n")[0];
1529
+ }
1530
+ async function runGrantCommand(input) {
1531
+ const [action = "show", target, ...extra] = input.positionals;
1532
+ const valid = action === "show" && target === void 0 || (action === "allow" || action === "remove") && target !== void 0 || action === "lan" && (target === "on" || target === "off");
1533
+ if (!valid || extra.length > 0) throw new Error(grantUsage);
1534
+ const ref = input.values.context ?? localContextId(input.apiUrl);
1535
+ if (!ref) {
1536
+ throw new Error(
1537
+ `No execution context is registered on this machine; pass --context <name>.
1538
+ ${grantUsage}`
1539
+ );
1540
+ }
1541
+ const api = {
1542
+ apiUrl: input.apiUrl,
1543
+ ...input.org ? { org: input.org } : {},
1544
+ ...input.fetchFn ? { fetchFn: input.fetchFn } : {},
1545
+ token: await input.token()
1546
+ };
1547
+ const onThisMachine = localContextId(input.apiUrl, ref);
1548
+ const id = onThisMachine ?? await resolveId(api, ref);
1549
+ let context = await getContext(api, id);
1550
+ const emit = async (summary) => {
1551
+ const policy = onThisMachine ? await readLocalPolicy() : null;
1552
+ const notes = policy ? hostAccessNotes(context, policy.fs) : [];
1553
+ const text = [
1554
+ ...summary ? [summary] : [],
1555
+ describeServerGrant(input.apiUrl, context),
1556
+ ...notes.length > 0 ? [
1557
+ "This machine (a run can use a folder only if both layers allow it):",
1558
+ ...notes.map((note) => ` ${note}`)
1559
+ ] : []
1560
+ ].join("\n");
1561
+ input.write(
1562
+ input.values.json ? `${JSON.stringify({ context, ...policy ? { localPolicy: policy.fs, notes } : {} }, null, 2)}
1563
+ ` : `${text}
1564
+ `
1565
+ );
1566
+ return 0;
1567
+ };
1568
+ if (action === "show") return await emit(null);
1569
+ const access = context.hostAccess;
1570
+ if (!access) {
1571
+ throw new Error(
1572
+ `Changing ${context.name}'s server grant needs Contribute or Manage on it (the same check as executionContextUpdate). Ask its operator or someone who manages it${contextPageUrl(input.apiUrl, context) ? `: ${contextPageUrl(input.apiUrl, context)}` : "."}`
1573
+ );
1574
+ }
1575
+ const patch = async (grant) => {
1576
+ const body = await apiJson({
1577
+ ...api,
1578
+ method: "PATCH",
1579
+ path: `/v1/execution-contexts/${encodeURIComponent(id)}`,
1580
+ body: { grant }
1581
+ });
1582
+ context = body.context ?? context;
1583
+ };
1584
+ if (action === "lan") {
1585
+ const mode2 = access.egress.mode;
1586
+ if (target === "on") {
1587
+ if (mode2 === "public-and-lan") {
1588
+ return await emit(
1589
+ `The local network is already on for ${context.name}.`
1590
+ );
1591
+ }
1592
+ if (mode2 !== "public") {
1593
+ throw new Error(
1594
+ `${context.name}'s egress is ${mode2}, not public. \`kody context grant lan on\` only switches public to public-and-lan; change a ${mode2} egress with executionContextUpdate grant.egress or on the context page.`
1595
+ );
1596
+ }
1597
+ await patch({ egress: { mode: "public-and-lan" } });
1598
+ return await emit(
1599
+ `Turned the local network on in ${context.name}'s server grant (grant.egress public-and-lan).`
1600
+ );
1601
+ }
1602
+ if (mode2 !== "public-and-lan") {
1603
+ return await emit(`The local network is already off for ${context.name}.`);
1604
+ }
1605
+ await patch({ egress: { mode: "public" } });
1606
+ return await emit(
1607
+ `Turned the local network off in ${context.name}'s server grant (grant.egress public).`
1608
+ );
1609
+ }
1610
+ const raw = plainPath(target);
1611
+ if (!isAbsolute(raw)) throw new Error(`${target} is not an absolute path.`);
1612
+ const path = onThisMachine ? await canonicalHostPath(raw).catch((error) => {
1613
+ if (action === "remove") return raw;
1614
+ throw error;
1615
+ }) : raw;
1616
+ const rest = access.fs.filter((entry) => !samePath(entry.path, path));
1617
+ if (action === "remove") {
1618
+ if (rest.length === access.fs.length) {
1619
+ return await emit(`${path} was not in ${context.name}'s server grant.`);
1620
+ }
1621
+ await patch({ fs: rest });
1622
+ return await emit(`Removed ${path} from ${context.name}'s server grant.`);
1623
+ }
1624
+ const mode = input.values.mode ?? "ro";
1625
+ if (mode !== "ro" && mode !== "rw") {
1626
+ throw new Error("--mode must be ro (read-only) or rw (read-write).");
1627
+ }
1628
+ const fs = [...rest, { path, mode }].sort(
1629
+ (a, b) => a.path.localeCompare(b.path)
1630
+ );
1631
+ await patch({ fs });
1632
+ return await emit(
1633
+ `Added ${path} (${mode}) to ${context.name}'s server grant. Running daemons pick this up right away.`
1634
+ );
1635
+ }
1636
+
1637
+ // src/execution-context/worker-tracker.ts
1638
+ import { execFileSync } from "node:child_process";
1639
+ import {
1640
+ mkdirSync,
1641
+ readFileSync,
1642
+ readdirSync,
1643
+ rmSync,
1644
+ writeFileSync
1645
+ } from "node:fs";
1646
+ import { dirname, join } from "node:path";
1647
+ var defaultOps = {
1648
+ isAlive(pid) {
1649
+ try {
1650
+ process.kill(pid, 0);
1651
+ return true;
1652
+ } catch (error) {
1653
+ return error.code === "EPERM";
1654
+ }
1655
+ },
1656
+ commandLine(pid) {
1657
+ try {
1658
+ if (process.platform === "linux") {
1659
+ return readFileSync(`/proc/${pid}/cmdline`, "utf8").replaceAll(
1660
+ "\0",
1661
+ " "
1662
+ );
1663
+ }
1664
+ if (process.platform === "win32") return windowsCommandLine(pid);
1665
+ return execFileSync("ps", ["-p", String(pid), "-o", "command="], {
1666
+ encoding: "utf8",
1667
+ stdio: ["ignore", "pipe", "ignore"]
1668
+ });
1669
+ } catch {
1670
+ return null;
1671
+ }
1672
+ },
1673
+ kill(pid) {
1674
+ try {
1675
+ process.kill(pid, "SIGKILL");
1676
+ } catch {
1677
+ }
1678
+ }
1679
+ };
1680
+ function readRecord(path) {
1681
+ try {
1682
+ const value = JSON.parse(readFileSync(path, "utf8"));
1683
+ return Number.isInteger(value.pid) && value.pid > 0 && typeof value.configPath === "string" && value.configPath.endsWith("config.capnp") && Number.isInteger(value.ownerPid) ? value : null;
1684
+ } catch {
1685
+ return null;
1686
+ }
1687
+ }
1688
+ function reapLeftoverWorkers(dir, input = {}) {
1689
+ const ops = input.ops ?? defaultOps;
1690
+ const selfPid = input.selfPid ?? process.pid;
1691
+ let entries;
1692
+ try {
1693
+ entries = readdirSync(dir).filter((name) => name.endsWith(".json"));
1694
+ } catch {
1695
+ return [];
1696
+ }
1697
+ const killed = [];
1698
+ for (const name of entries) {
1699
+ const path = join(dir, name);
1700
+ const record = readRecord(path);
1701
+ if (!record) {
1702
+ rmSync(path, { force: true });
1703
+ continue;
1704
+ }
1705
+ if (record.ownerPid !== selfPid && ops.isAlive(record.ownerPid)) continue;
1706
+ if (ops.isAlive(record.pid) && ops.commandLine(record.pid)?.includes(record.configPath)) {
1707
+ ops.kill(record.pid);
1708
+ killed.push(record.pid);
1709
+ }
1710
+ rmSync(dirname(record.configPath), { recursive: true, force: true });
1711
+ rmSync(path, { force: true });
1712
+ }
1713
+ return killed;
1714
+ }
1715
+ function createLocalWorkerTracker(dir, input = {}) {
1716
+ const ops = input.ops ?? defaultOps;
1717
+ const live = /* @__PURE__ */ new Set();
1718
+ const recordPath = (pid) => join(dir, `${pid}.json`);
1719
+ const killAll = () => {
1720
+ for (const pid of live) {
1721
+ ops.kill(pid);
1722
+ rmSync(recordPath(pid), { force: true });
1723
+ }
1724
+ live.clear();
1725
+ };
1726
+ process.on("exit", killAll);
1727
+ return {
1728
+ started({ pid, configPath }) {
1729
+ live.add(pid);
1730
+ try {
1731
+ mkdirSync(dir, { recursive: true, mode: 448 });
1732
+ const record = {
1733
+ pid,
1734
+ configPath,
1735
+ ownerPid: process.pid
1736
+ };
1737
+ writeFileSync(recordPath(pid), JSON.stringify(record), {
1738
+ mode: 384
1739
+ });
1740
+ } catch {
1741
+ }
1742
+ },
1743
+ exited(pid) {
1744
+ live.delete(pid);
1745
+ rmSync(recordPath(pid), { force: true });
1746
+ },
1747
+ killAll,
1748
+ dispose() {
1749
+ process.off("exit", killAll);
1750
+ }
1751
+ };
1752
+ }
1753
+
1754
+ // src/execution-context/commands.ts
1755
+ var defaultMaxConcurrentRuns = 2;
1756
+ var loginCheckIntervalMs = 6 * 60 * 6e4;
1757
+ function maxConcurrentRuns(value = process.env.KODY_CONTEXT_MAX_CONCURRENT) {
1758
+ if (value === void 0 || value === "") return defaultMaxConcurrentRuns;
1759
+ const parsed = Number(value);
1760
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > ecpMaxConcurrentRunsCap) {
1761
+ throw new Error(
1762
+ `--max-concurrent (or KODY_CONTEXT_MAX_CONCURRENT) must be a whole number from 1 to ${ecpMaxConcurrentRunsCap}; got ${value}.`
1763
+ );
1764
+ }
1765
+ return parsed;
1766
+ }
1767
+ function localCapabilities(maxConcurrent = defaultMaxConcurrentRuns) {
1768
+ return {
1769
+ runtime: "workerd",
1770
+ node: process.versions.node,
1771
+ os: platform(),
1772
+ cpuCount: cpus().length,
1773
+ memoryMb: Math.round(totalmem() / (1024 * 1024)),
1774
+ maxConcurrent,
1775
+ features: []
1776
+ };
1777
+ }
1778
+ function out(input, value, text) {
1779
+ input.write(
1780
+ input.values.json ? `${JSON.stringify(value, null, 2)}
1781
+ ` : `${text}
1782
+ `
1783
+ );
1784
+ }
1785
+ async function runExecutionContextCommand(input) {
1786
+ try {
1787
+ return await runCommand(input);
1788
+ } catch (error) {
1789
+ if (isExperimentOffError(error)) throw experimentOffError(input.apiUrl);
1790
+ throw error;
1791
+ }
1792
+ }
1793
+ async function runCommand(input) {
1794
+ const [sub, ...rest] = input.positionals;
1795
+ const base = {
1796
+ apiUrl: input.apiUrl,
1797
+ ...input.org ? { org: input.org } : {},
1798
+ ...input.fetchFn ? { fetchFn: input.fetchFn } : {}
1799
+ };
1800
+ if (input.command === "context" && sub === "commands") {
1801
+ return await runCommandsOptInCommand(input, rest);
1802
+ }
1803
+ if (input.command === "context" && sub === "policy") {
1804
+ return await runPolicyCommand(input, rest);
1805
+ }
1806
+ if (input.command === "context" && sub === "grant") {
1807
+ return await runGrantCommand({ ...input, ...base, positionals: rest });
1808
+ }
1809
+ const serviceEnv = {
1810
+ apiUrl: input.apiUrl,
1811
+ clientVersion: input.clientVersion,
1812
+ write: input.write,
1813
+ ...input.values.json ? { json: true } : {},
1814
+ ...input.values.yes ? { yes: true } : {},
1815
+ confirm: input.values.json ? null : terminalConfirm(),
1816
+ ...input.service
1817
+ };
1818
+ const maxConcurrentFlag = () => {
1819
+ if (input.values.maxConcurrent === "") {
1820
+ throw new Error("--max-concurrent needs a value.");
1821
+ }
1822
+ return input.values.maxConcurrent === void 0 ? void 0 : maxConcurrentRuns(input.values.maxConcurrent);
1823
+ };
1824
+ if (input.command === "update") return await runUpdate(serviceEnv);
1825
+ if (input.command === "daemon" && sub === "env") {
1826
+ return await runDaemonEnvCommand(serviceEnv, {
1827
+ action: rest[0],
1828
+ args: rest.slice(1),
1829
+ ...input.values.context ? { context: input.values.context } : {}
1830
+ });
1831
+ }
1832
+ if (input.command === "daemon" && sub === "install" && input.values.env?.length) {
1833
+ await saveServiceEnvAssignments(input.values.env);
1834
+ }
1835
+ if (input.command === "daemon" && sub === "auto-update") {
1836
+ return await runAutoUpdateCommand(serviceEnv, rest[0]);
1837
+ }
1838
+ if (input.command === "daemon" && isRemoteDaemonCommand({
1839
+ sub,
1840
+ apiUrl: input.apiUrl,
1841
+ ...input.values.context ? { context: input.values.context } : {},
1842
+ ...input.values.remote ? { remote: true } : {}
1843
+ })) {
1844
+ return await runRemoteDaemonCommand({
1845
+ ...base,
1846
+ sub,
1847
+ args: rest,
1848
+ token: input.token,
1849
+ write: input.write,
1850
+ ...input.values.context ? { context: input.values.context } : {},
1851
+ ...input.values.reason ? { reason: input.values.reason } : {},
1852
+ ...input.values.cancelRuns ? { cancelRuns: true } : {},
1853
+ ...input.values.lines ? { lines: input.values.lines } : {},
1854
+ ...input.values.json ? { json: true } : {}
1855
+ });
1856
+ }
1857
+ if (input.command === "daemon" && sub === "update") {
1858
+ return await runUpdate(serviceEnv);
1859
+ }
1860
+ if (input.command === "daemon" && sub !== void 0) {
1861
+ const maxConcurrent = maxConcurrentFlag();
1862
+ return await runDaemonServiceCommand(serviceEnv, {
1863
+ sub,
1864
+ ...input.values.context ? { context: input.values.context } : {},
1865
+ ...maxConcurrent === void 0 ? {} : { maxConcurrent },
1866
+ ...input.values.keyStorage ? { keyStorage: input.values.keyStorage } : {},
1867
+ ...input.values.lines ? { lines: input.values.lines } : {},
1868
+ ...input.values.follow ? { follow: true } : {},
1869
+ ...input.values.unregister === void 0 ? {} : { unregister: input.values.unregister },
1870
+ revoke: async (ecid) => {
1871
+ await apiJson({
1872
+ ...base,
1873
+ token: await input.token(),
1874
+ method: "DELETE",
1875
+ path: `/v1/execution-contexts/${encodeURIComponent(ecid)}`
1876
+ });
1877
+ }
1878
+ });
1879
+ }
1880
+ if (input.command === "connect" && !input.values.name && !sub && localContextId(input.apiUrl, input.values.context)) {
1881
+ const ecid = localContextId(input.apiUrl, input.values.context);
1882
+ input.write(`This machine is already registered as ${ecid}.
1883
+ `);
1884
+ const maxConcurrent = maxConcurrentFlag();
1885
+ await offerInstall(serviceEnv, {
1886
+ ecid,
1887
+ install: input.values.install ?? true,
1888
+ ...input.values.keyStorage ? { keyStorage: input.values.keyStorage } : {},
1889
+ ...maxConcurrent === void 0 ? {} : { maxConcurrent }
1890
+ });
1891
+ return 0;
1892
+ }
1893
+ if (input.command === "context" && sub === "register" || input.command === "connect") {
1894
+ const connect = input.command === "connect";
1895
+ const name = input.values.name ?? (connect ? sub : rest[0]);
1896
+ if (!name) throw new Error("Pass --name <name> for this machine.");
1897
+ const maxConcurrent = maxConcurrentFlag();
1898
+ if (input.values.keyStorage !== void 0 && input.values.keyStorage !== "file" && input.values.keyStorage !== "keyring") {
1899
+ throw new Error("--key-storage must be keyring or file.");
1900
+ }
1901
+ const wrappingFor = async (ecid) => {
1902
+ if (input.values.keyStorage === "file") {
1903
+ return fileWrappingKey({ apiUrl: input.apiUrl, ecid, create: true });
1904
+ }
1905
+ try {
1906
+ const source = resolveWrappingKey({ ecid, create: true });
1907
+ if (source.kind === "keyring") source.key(Buffer.alloc(16));
1908
+ return source;
1909
+ } catch (error) {
1910
+ if (input.values.keyStorage === "keyring") throw error;
1911
+ const question = `No unlocked OS keyring is available (${error instanceof Error ? error.message : String(error)}).
1912
+ Store the machine key wrapping key in a file instead (only readable by your user, 600 permissions, in the kody state directory)?`;
1913
+ const useFile = serviceEnv.yes ? true : serviceEnv.confirm ? await serviceEnv.confirm(question, true) : false;
1914
+ if (!useFile) {
1915
+ throw new Error(
1916
+ `${error instanceof Error ? error.message : String(error)} Or re-run with --key-storage file.`
1917
+ );
1918
+ }
1919
+ return fileWrappingKey({ apiUrl: input.apiUrl, ecid, create: true });
1920
+ }
1921
+ };
1922
+ const { publicKeyJwk, privateKeyJwk } = await generateContextKey();
1923
+ const privateKey = await importContextKey(privateKeyJwk);
1924
+ const thumbprint = await ed25519JwkThumbprint(publicKeyJwk);
1925
+ const registered = await registerContext({
1926
+ ...base,
1927
+ token: await input.token(),
1928
+ name,
1929
+ publicKeyJwk,
1930
+ privateKey,
1931
+ thumbprint,
1932
+ capabilities: localCapabilities(),
1933
+ client: { name: "kody-cli", version: input.clientVersion }
1934
+ });
1935
+ try {
1936
+ saveContext({
1937
+ context: {
1938
+ version: 1,
1939
+ ecid: registered.ecid,
1940
+ name: registered.name,
1941
+ apiUrl: input.apiUrl,
1942
+ orgSlug: registered.owner.orgSlug,
1943
+ publicKeyJwk
1944
+ },
1945
+ privateJwk: privateKeyJwk,
1946
+ wrapping: await wrappingFor(registered.ecid)
1947
+ });
1948
+ } catch (error) {
1949
+ const path = `/v1/execution-contexts/${encodeURIComponent(registered.ecid)}`;
1950
+ const token = await input.token();
1951
+ await apiJson({ ...base, token, method: "DELETE", path }).then(
1952
+ () => apiJson({ ...base, token, method: "POST", path: `${path}/delete` })
1953
+ ).catch(() => {
1954
+ });
1955
+ throw error;
1956
+ }
1957
+ const steps = (registered.nextSteps ?? []).map(
1958
+ (step) => ` ${step.text ?? ""}${step.cli ? `
1959
+ ${step.cli}` : ""}`
1960
+ ).join("\n");
1961
+ out(
1962
+ input,
1963
+ registered,
1964
+ [
1965
+ registered.notice ?? `Registered ${registered.name} (${registered.ecid}).`,
1966
+ steps ? `Next steps:
1967
+ ${steps}` : ""
1968
+ ].filter(Boolean).join("\n")
1969
+ );
1970
+ if (input.values.json && input.values.install === void 0) return 0;
1971
+ const install = {
1972
+ ecid: registered.ecid,
1973
+ ...input.values.install !== void 0 ? { install: input.values.install } : connect && !serviceEnv.confirm ? { install: true } : {},
1974
+ ...maxConcurrent === void 0 ? {} : { maxConcurrent }
1975
+ };
1976
+ if (input.values.install === true) {
1977
+ const installEnv = input.values.json ? {
1978
+ ...serviceEnv,
1979
+ write: (text) => {
1980
+ process.stderr.write(text);
1981
+ }
1982
+ } : serviceEnv;
1983
+ return await offerInstall(installEnv, install) ? 0 : 1;
1984
+ }
1985
+ try {
1986
+ await offerInstall(serviceEnv, install);
1987
+ } catch (error) {
1988
+ input.write(
1989
+ `Registered, but the background service was not installed: ${error instanceof Error ? error.message : String(error)}
1990
+ Run \`kody daemon\` in a terminal, or fix that and run: kody daemon install --context ${registered.ecid}
1991
+ `
1992
+ );
1993
+ }
1994
+ return 0;
1995
+ }
1996
+ if (input.command === "context" && (sub === "list" || sub === void 0)) {
1997
+ const body = await apiJson({
1998
+ ...base,
1999
+ token: await input.token(),
2000
+ method: "GET",
2001
+ path: "/v1/execution-contexts"
2002
+ });
2003
+ const contexts = body.contexts ?? [];
2004
+ const local = new Set(storedContextIds(input.apiUrl));
2005
+ const policyFs = contexts.some((c) => local.has(c.id)) ? (await readLocalPolicy()).fs : [];
2006
+ const notesFor = (c) => local.has(c.id) ? hostAccessNotes(c, policyFs) : [];
2007
+ out(
2008
+ input,
2009
+ {
2010
+ ...body,
2011
+ ...local.size > 0 ? {
2012
+ thisMachine: {
2013
+ localPolicy: policyFs,
2014
+ notes: Object.fromEntries(
2015
+ contexts.filter((c) => local.has(c.id)).map((c) => [c.name, notesFor(c)])
2016
+ )
2017
+ }
2018
+ } : {}
2019
+ },
2020
+ contexts.length === 0 ? "No execution contexts yet. Register this machine with `kody context register --name <name>`." : contexts.map(
2021
+ (c) => [
2022
+ `${c.name} (${c.id}) ${c.status}${c.usable ? "" : `, not usable: ${c.unusableReason}`}${c.grantSummary ? `; server grant: ${c.grantSummary.fs} host folder${c.grantSummary.fs === 1 ? "" : "s"}, LAN ${lanState(c.grantSummary.egress.mode)}` : ""}${local.has(c.id) ? " (this machine)" : ""}`,
2023
+ ...notesFor(c).map((note) => ` ${note}`)
2024
+ ].join("\n")
2025
+ ).join("\n")
2026
+ );
2027
+ return 0;
2028
+ }
2029
+ if (input.command === "context" && (sub === "revoke" || sub === "delete")) {
2030
+ const ref = rest[0];
2031
+ if (!ref) throw new Error(`Usage: kody context ${sub} <name|ec id>`);
2032
+ const id = encodeURIComponent(ref);
2033
+ const body = await apiJson({
2034
+ ...base,
2035
+ token: await input.token(),
2036
+ ...sub === "revoke" ? { method: "DELETE", path: `/v1/execution-contexts/${id}` } : { method: "POST", path: `/v1/execution-contexts/${id}/delete` }
2037
+ });
2038
+ out(
2039
+ input,
2040
+ body,
2041
+ sub === "revoke" ? `Revoked ${ref}. Delete it for good with: kody context delete ${ref}` : `Deleted ${ref}.`
2042
+ );
2043
+ const revokedId = typeof body.id === "string" ? body.id : typeof body.context?.id === "string" ? body.context.id : null;
2044
+ await offerUninstallAfterRevoke(
2045
+ input.values.json ? { ...serviceEnv, write: () => {
2046
+ } } : serviceEnv,
2047
+ {
2048
+ ref,
2049
+ ecid: revokedId && localContextId(input.apiUrl, revokedId) ? revokedId : null
2050
+ }
2051
+ );
2052
+ return 0;
2053
+ }
2054
+ if (input.command === "context" && sub === "cancel-run") {
2055
+ const [ref, runId] = rest;
2056
+ if (!ref || !runId) {
2057
+ throw new Error("Usage: kody context cancel-run <name|ec id> <run id>");
2058
+ }
2059
+ const body = await apiJson({
2060
+ ...base,
2061
+ token: await input.token(),
2062
+ method: "POST",
2063
+ path: `/v1/execution-contexts/${encodeURIComponent(ref)}/runs/${encodeURIComponent(runId)}/cancel`
2064
+ });
2065
+ out(
2066
+ input,
2067
+ body,
2068
+ body.cancelled === true ? `Cancelled run ${runId} on ${ref}.` : `Run ${runId} already ended (${typeof body.state === "string" ? body.state : "finished"}).`
2069
+ );
2070
+ return 0;
2071
+ }
2072
+ if (input.command === "chain") {
2073
+ const token = await input.token();
2074
+ const read = await apiJson({
2075
+ ...base,
2076
+ token,
2077
+ method: "GET",
2078
+ path: "/v1/execution-chain"
2079
+ });
2080
+ const current = chainOf(read);
2081
+ const contexts = async () => contextsById(
2082
+ await apiJson({
2083
+ ...base,
2084
+ token,
2085
+ method: "GET",
2086
+ path: "/v1/execution-contexts"
2087
+ })
2088
+ );
2089
+ const contextMetadata = async () => {
2090
+ if (input.values.json) return /* @__PURE__ */ new Map();
2091
+ try {
2092
+ return await contexts();
2093
+ } catch {
2094
+ return /* @__PURE__ */ new Map();
2095
+ }
2096
+ };
2097
+ if (sub === "show" || sub === void 0) {
2098
+ out(input, read, describeChain(current, await contextMetadata()));
2099
+ return 0;
2100
+ }
2101
+ if (sub !== "add" && sub !== "remove") {
2102
+ throw new Error("Usage: kody chain show | add <name> | remove <name>");
2103
+ }
2104
+ const ref = rest[0];
2105
+ if (!ref) throw new Error(`Pass the context name: kody chain ${sub} <name>`);
2106
+ const id = await resolveContextId({
2107
+ ...base,
2108
+ token,
2109
+ ref
2110
+ });
2111
+ const entries = (current.entries ?? []).map(
2112
+ (entry) => entry.kind === "cloud" ? { kind: "cloud" } : { kind: "context", id: entry.id }
2113
+ ).filter((entry) => !(entry.kind === "context" && entry.id === id));
2114
+ if (sub === "add") {
2115
+ if (entries.length === 0) entries.push({ kind: "cloud" });
2116
+ const cloudAt = entries.findIndex((entry) => entry.kind === "cloud");
2117
+ entries.splice(cloudAt === -1 ? entries.length : cloudAt, 0, {
2118
+ kind: "context",
2119
+ id
2120
+ });
2121
+ }
2122
+ const updated = await apiJson({
2123
+ ...base,
2124
+ token,
2125
+ method: "PUT",
2126
+ path: "/v1/execution-chain",
2127
+ body: {
2128
+ entries,
2129
+ strict: !entries.some((entry) => entry.kind === "cloud"),
2130
+ ifMatch: current.updatedAt ?? null
2131
+ }
2132
+ });
2133
+ out(
2134
+ input,
2135
+ updated,
2136
+ describeChain(chainOf(updated), await contextMetadata())
2137
+ );
2138
+ return 0;
2139
+ }
2140
+ if (input.command === "daemon") {
2141
+ if (input.values.maxConcurrent === "") {
2142
+ throw new Error("--max-concurrent needs a value.");
2143
+ }
2144
+ const maxConcurrent = maxConcurrentRuns(input.values.maxConcurrent);
2145
+ const ecid = input.values.context ? localContextId(input.apiUrl, input.values.context) ?? input.values.context : storedContextIds(input.apiUrl)[0];
2146
+ if (!ecid) {
2147
+ throw new Error(
2148
+ "This machine has no registered execution context. Run `kody connect --name <name>` first."
2149
+ );
2150
+ }
2151
+ const asService = process.env[serviceEnvVar];
2152
+ const manager = isServiceManager(asService) ? asService : null;
2153
+ const paths = manager ? servicePaths({ apiUrl: input.apiUrl, ecid, manager }) : null;
2154
+ const supervised = process.env[supervisedEnvVar] === "1";
2155
+ if (paths && !supervised) rotateLog(paths.logPath);
2156
+ if (paths && manager === "taskscheduler") appendOutputTo(paths.logPath);
2157
+ const readAutoUpdate = async () => autoUpdateSetting(await readLocalPolicy().catch(() => null));
2158
+ const relaunchArgs = [
2159
+ "daemon",
2160
+ "--context",
2161
+ ecid,
2162
+ "--api-url",
2163
+ input.apiUrl,
2164
+ ...input.values.maxConcurrent === void 0 ? [] : ["--max-concurrent", input.values.maxConcurrent]
2165
+ ];
2166
+ const recentLog = [];
2167
+ const log = (line) => {
2168
+ recentLog.push(`${(/* @__PURE__ */ new Date()).toISOString()} ${line}`);
2169
+ if (recentLog.length > daemonLogBufferLines) recentLog.shift();
2170
+ input.write(`${line}
2171
+ `);
2172
+ };
2173
+ if (!supervised && (await readAutoUpdate()).enabled) {
2174
+ const newer = newerInstalledVersion({ selfVersion: input.clientVersion });
2175
+ if (newer) {
2176
+ const outcome = await superviseNewerVersion({
2177
+ first: newer,
2178
+ selfVersion: input.clientVersion,
2179
+ args: relaunchArgs,
2180
+ log
2181
+ });
2182
+ if (outcome.kind === "exit") return outcome.code;
2183
+ }
2184
+ }
2185
+ let started;
2186
+ try {
2187
+ const { context: context2, privateJwk } = loadContext({
2188
+ apiUrl: input.apiUrl,
2189
+ ecid,
2190
+ wrapping: wrappingKeyForStoredContext({ apiUrl: input.apiUrl, ecid })
2191
+ });
2192
+ started = {
2193
+ context: context2,
2194
+ privateKey: await importContextKey(privateJwk),
2195
+ serverKeys: await fetchServerKeys({ apiUrl: input.apiUrl })
2196
+ };
2197
+ } catch (error) {
2198
+ if (!supervised) throw error;
2199
+ log(
2200
+ `Could not start: ${error instanceof Error ? error.message : String(error)}`
2201
+ );
2202
+ return startupRefusedExitCode;
2203
+ }
2204
+ const { context, privateKey } = started;
2205
+ let { serverKeys } = started;
2206
+ const { runContextRun } = await import("./run-executor-J3MF4RCT.js");
2207
+ const hostCommands = new HostCommands({
2208
+ localEnabled: await readLocalCommandsEnabled().catch(() => false)
2209
+ });
2210
+ const commandsPolicyPath = localPolicyPath();
2211
+ const onCommandsPolicyChange = () => {
2212
+ void readLocalCommandsEnabled().catch(() => false).then((enabled) => hostCommands.setLocalEnabled(enabled));
2213
+ };
2214
+ watchFile(commandsPolicyPath, { interval: 2e3 }, onCommandsPolicyChange);
2215
+ const lockStatePath = servicePaths({
2216
+ apiUrl: input.apiUrl,
2217
+ ecid,
2218
+ manager: serviceManagerFor() ?? "systemd"
2219
+ }).statePath;
2220
+ const launcher = manager ?? (process.env[launcherEnvVar] === "desktop" ? "desktop" : "terminal");
2221
+ const lockInfo = {
2222
+ version: input.clientVersion,
2223
+ launcher,
2224
+ startedAt: (/* @__PURE__ */ new Date()).toISOString()
2225
+ };
2226
+ let lock = acquireRunnerLock(lockPathFor(lockStatePath), lockInfo);
2227
+ if (!lock.ok && manager) {
2228
+ let holder = lock.holder;
2229
+ log(
2230
+ `Another kody daemon already runs ${context.name} (${describeHolder(holder)}). One runner per context: this service waits for it to stop instead of replacing it.`
2231
+ );
2232
+ let stopWaiting = false;
2233
+ const onWaitSignal = () => {
2234
+ stopWaiting = true;
2235
+ };
2236
+ process.on("SIGINT", onWaitSignal);
2237
+ process.on("SIGTERM", onWaitSignal);
2238
+ try {
2239
+ while (!lock.ok && !stopWaiting) {
2240
+ await new Promise((resolve) => setTimeout(resolve, 15e3));
2241
+ lock = acquireRunnerLock(lockPathFor(lockStatePath), lockInfo);
2242
+ if (!lock.ok && lock.holder.pid !== holder.pid) {
2243
+ holder = lock.holder;
2244
+ log(
2245
+ `The runner for ${context.name} is now ${describeHolder(holder)}. Still waiting.`
2246
+ );
2247
+ }
2248
+ }
2249
+ } finally {
2250
+ process.off("SIGINT", onWaitSignal);
2251
+ process.off("SIGTERM", onWaitSignal);
2252
+ }
2253
+ if (!lock.ok) {
2254
+ unwatchFile(commandsPolicyPath, onCommandsPolicyChange);
2255
+ return stayStoppedExitCode;
2256
+ }
2257
+ log(`The other daemon stopped. Starting ${context.name}.`);
2258
+ serverKeys = await fetchServerKeys({ apiUrl: input.apiUrl });
2259
+ }
2260
+ if (!lock.ok) {
2261
+ unwatchFile(commandsPolicyPath, onCommandsPolicyChange);
2262
+ const message = `Another kody daemon already runs ${context.name} (${describeHolder(lock.holder)}). One runner per context on a machine: use that one, or stop it first (\`kody daemon stop\`, or Machine > Stop runner in the desktop app).`;
2263
+ if (!supervised) throw new Error(message);
2264
+ log(message);
2265
+ return startupRefusedExitCode;
2266
+ }
2267
+ const releaseLock = lock.release;
2268
+ const abort = new AbortController();
2269
+ const drain = new AbortController();
2270
+ let hardStop;
2271
+ let signalled = false;
2272
+ let signalledAt = 0;
2273
+ let updateTo = null;
2274
+ let forcedUpdate = false;
2275
+ let restartRequested = false;
2276
+ let paused = null;
2277
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
2278
+ const onSignal = () => {
2279
+ if (signalled) {
2280
+ if (Date.now() - signalledAt < 2e3) return;
2281
+ return abort.abort();
2282
+ }
2283
+ signalled = true;
2284
+ signalledAt = Date.now();
2285
+ updateTo = null;
2286
+ if (!drain.signal.aborted) drain.abort();
2287
+ hardStop = setTimeout(() => abort.abort(), 8e4);
2288
+ hardStop.unref();
2289
+ };
2290
+ process.on("SIGINT", onSignal);
2291
+ process.on("SIGTERM", onSignal);
2292
+ input.write(
2293
+ `Starting ${context.name} (${context.ecid}) against ${input.apiUrl}${manager ? ` as a ${manager} service` : ""}.
2294
+ `
2295
+ );
2296
+ if (!manager && serviceManagerFor()) {
2297
+ input.write(
2298
+ "Tip: keep it running after reboots and crashes with: kody daemon install\n"
2299
+ );
2300
+ }
2301
+ const statePath = servicePaths({
2302
+ apiUrl: input.apiUrl,
2303
+ ecid,
2304
+ manager: serviceManagerFor() ?? "systemd"
2305
+ }).statePath;
2306
+ writeJson(statePath, {
2307
+ pid: process.pid,
2308
+ version: input.clientVersion,
2309
+ service: manager,
2310
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
2311
+ ...supervised ? { supervisorPid: process.ppid } : {}
2312
+ });
2313
+ const workersDir = contextWorkersDir(input.apiUrl, context.ecid);
2314
+ const reaped = reapLeftoverWorkers(workersDir);
2315
+ if (reaped.length > 0) {
2316
+ input.write(
2317
+ `Stopped ${reaped.length} local worker(s) left running by an earlier daemon for this context.
2318
+ `
2319
+ );
2320
+ }
2321
+ const workerTracker = createLocalWorkerTracker(workersDir);
2322
+ const packageGraphCache = createPackageGraphCache();
2323
+ let stop = "shutdown";
2324
+ let autoUpdateEnabled = (await readAutoUpdate()).enabled;
2325
+ let reportedServerFsOff = false;
2326
+ const activity = { runs: 0 };
2327
+ const updater = startDaemonUpdater({
2328
+ selfVersion: input.clientVersion,
2329
+ setting: async () => {
2330
+ const setting = await readAutoUpdate();
2331
+ autoUpdateEnabled = setting.enabled;
2332
+ return setting;
2333
+ },
2334
+ busy: () => ({
2335
+ runs: activity.runs,
2336
+ background: hostCommands.runningBackground()
2337
+ }),
2338
+ log,
2339
+ onReady: (current, forced) => {
2340
+ if (signalled) return;
2341
+ updateTo = current;
2342
+ forcedUpdate = forced;
2343
+ if (!drain.signal.aborted) drain.abort();
2344
+ }
2345
+ });
2346
+ const checkLogin = async () => {
2347
+ try {
2348
+ const result = await checkContextLogin({
2349
+ apiUrl: input.apiUrl,
2350
+ ecid: context.ecid,
2351
+ privateKey,
2352
+ token: await input.token(),
2353
+ org: context.orgSlug,
2354
+ ...input.fetchFn ? { fetchFn: input.fetchFn } : {}
2355
+ });
2356
+ if (result.changed) {
2357
+ log(
2358
+ `Recorded this machine's login (${result.login.kind === "profile" ? "agent profile" : "person"}) with Kody.`
2359
+ );
2360
+ }
2361
+ } catch (error) {
2362
+ log(
2363
+ `Could not check this machine's login with Kody: ${error instanceof Error ? error.message : String(error)}`
2364
+ );
2365
+ }
2366
+ };
2367
+ void checkLogin();
2368
+ const loginTimer = setInterval(
2369
+ () => void checkLogin(),
2370
+ loginCheckIntervalMs
2371
+ );
2372
+ loginTimer.unref();
2373
+ try {
2374
+ stop = await runDaemon({
2375
+ apiUrl: input.apiUrl,
2376
+ ecid: context.ecid,
2377
+ privateKey,
2378
+ serverKeys,
2379
+ maxConcurrent,
2380
+ client: { name: "kody-cli", version: input.clientVersion },
2381
+ capabilities: {
2382
+ ...localCapabilities(maxConcurrent),
2383
+ ...manager ? { service: manager } : {}
2384
+ },
2385
+ extraCapabilities: () => ({
2386
+ autoUpdate: autoUpdateEnabled ? "on" : "off"
2387
+ }),
2388
+ activity,
2389
+ // An update drain also waits for background host commands.
2390
+ drainHold: () => updateTo !== null && !signalled && !forcedUpdate && hostCommands.runningBackground() > 0,
2391
+ hostCommands,
2392
+ execute: (run) => runContextRun({
2393
+ ...run,
2394
+ apiUrl: input.apiUrl,
2395
+ workerTracker,
2396
+ packageGraphCache
2397
+ }),
2398
+ fs: {
2399
+ effective: async (grantFs) => {
2400
+ const policy = await readLocalPolicy();
2401
+ autoUpdateEnabled = autoUpdateSetting(policy).enabled;
2402
+ const serverOff = grantFs.length === 0 && policy.fs.length > 0;
2403
+ if (serverOff && !reportedServerFsOff) {
2404
+ log(
2405
+ "This machine's local policy allows host folders, but this context's server grant (grant.fs) lists none, so runs get no host folders. Someone with Contribute or Manage on the context can turn it on with: kody context grant allow <folder> --mode ro|rw"
2406
+ );
2407
+ }
2408
+ reportedServerFsOff = serverOff;
2409
+ return await effectiveFs(grantFs, policy.fs);
2410
+ },
2411
+ onChange: (listener) => {
2412
+ const path = localPolicyPath();
2413
+ watchFile(path, { interval: 2e3 }, listener);
2414
+ return () => unwatchFile(path, listener);
2415
+ }
2416
+ },
2417
+ log,
2418
+ onPaused: (next) => {
2419
+ if (JSON.stringify(next) === JSON.stringify(paused)) return;
2420
+ log(
2421
+ next ? `Paused in Kody${next.by ? ` by @${next.by}` : ""}${next.reason ? `: ${next.reason}` : ""}. This daemon stays connected but gets no runs and no host commands until it is resumed (kody daemon resume).` : paused ? "Resumed in Kody. Taking runs again." : ""
2422
+ );
2423
+ paused = next;
2424
+ },
2425
+ control: async (op, args) => {
2426
+ const restartable = Boolean(manager) || supervised;
2427
+ const busyDraining = () => {
2428
+ if (drain.signal.aborted) {
2429
+ throw new DaemonControlError(
2430
+ "daemon_busy",
2431
+ "This daemon is already stopping for a restart or update."
2432
+ );
2433
+ }
2434
+ };
2435
+ switch (op) {
2436
+ case "status":
2437
+ return {
2438
+ version: input.clientVersion,
2439
+ service: manager,
2440
+ supervised,
2441
+ pid: process.pid,
2442
+ platform: platform(),
2443
+ startedAt,
2444
+ autoUpdate: autoUpdateEnabled ? "on" : "off",
2445
+ maxConcurrent,
2446
+ runs: activity.runs,
2447
+ backgroundCommands: hostCommands.runningBackground(),
2448
+ draining: drain.signal.aborted,
2449
+ paused
2450
+ };
2451
+ case "restart": {
2452
+ if (!restartable) {
2453
+ throw new DaemonControlError(
2454
+ "not_service_managed",
2455
+ "This daemon runs in a terminal, so nothing would start it again."
2456
+ );
2457
+ }
2458
+ busyDraining();
2459
+ log(
2460
+ "Restart requested from Kody. Stopping after runs in flight finish; the service manager starts it again."
2461
+ );
2462
+ restartRequested = true;
2463
+ setTimeout(() => {
2464
+ if (!drain.signal.aborted) drain.abort();
2465
+ }, 250).unref();
2466
+ return { restarting: true, runs: activity.runs };
2467
+ }
2468
+ case "update": {
2469
+ busyDraining();
2470
+ const result = await checkForUpdate({
2471
+ selfVersion: input.clientVersion,
2472
+ enabled: true
2473
+ });
2474
+ if (result.kind === "ready") {
2475
+ log(
2476
+ `Update requested from Kody: moving kody ${input.clientVersion} to ${result.current.version} after runs in flight finish.`
2477
+ );
2478
+ updateTo = result.current;
2479
+ setTimeout(() => {
2480
+ if (!drain.signal.aborted) drain.abort();
2481
+ }, 250).unref();
2482
+ return {
2483
+ version: input.clientVersion,
2484
+ updatingTo: result.current.version,
2485
+ message: `Updating to kody ${result.current.version} after runs in flight finish.`
2486
+ };
2487
+ }
2488
+ if (result.kind === "up-to-date") {
2489
+ return {
2490
+ version: input.clientVersion,
2491
+ latest: result.latest,
2492
+ message: `Already on the latest kody (${input.clientVersion}).`
2493
+ };
2494
+ }
2495
+ throw new DaemonControlError(
2496
+ "daemon_control_failed",
2497
+ result.kind === "failed" ? `Could not update to ${result.version}: ${result.error}` : result.kind === "backoff" ? `${result.version} failed before; next try after ${result.until}.` : "Another update check is running. Try again shortly."
2498
+ );
2499
+ }
2500
+ case "auto-update": {
2501
+ const enabled = args.enabled === true;
2502
+ await setLocalAutoUpdateEnabled({ enabled });
2503
+ autoUpdateEnabled = (await readAutoUpdate()).enabled;
2504
+ log(
2505
+ `Auto-update turned ${enabled ? "on" : "off"} from Kody (for every kody daemon on this machine).`
2506
+ );
2507
+ return { autoUpdate: autoUpdateEnabled ? "on" : "off" };
2508
+ }
2509
+ case "logs": {
2510
+ const lines = Math.max(
2511
+ 1,
2512
+ Math.min(
2513
+ daemonLogBufferLines,
2514
+ typeof args.lines === "number" ? Math.floor(args.lines) : 100
2515
+ )
2516
+ );
2517
+ return {
2518
+ lines: recentDaemonLog(paths?.logPath, recentLog, lines)
2519
+ };
2520
+ }
2521
+ default:
2522
+ throw new DaemonControlError(
2523
+ "daemon_control_failed",
2524
+ `Unknown daemon operation ${op}. Update kody on this machine.`
2525
+ );
2526
+ }
2527
+ },
2528
+ signal: abort.signal,
2529
+ drainSignal: drain.signal
2530
+ });
2531
+ } finally {
2532
+ clearInterval(loginTimer);
2533
+ updater.stop();
2534
+ unwatchFile(commandsPolicyPath, onCommandsPolicyChange);
2535
+ hostCommands.killAll("shutdown");
2536
+ workerTracker.killAll();
2537
+ workerTracker.dispose();
2538
+ if (hardStop) clearTimeout(hardStop);
2539
+ process.off("SIGINT", onSignal);
2540
+ process.off("SIGTERM", onSignal);
2541
+ rmSync2(statePath, { force: true });
2542
+ releaseLock();
2543
+ }
2544
+ if (stop === "replaced") {
2545
+ const others = await otherLocalDaemons({ ecid: context.ecid });
2546
+ log(
2547
+ others.length > 0 ? `Another kody daemon for ${context.name} connected and replaced this one: ${others.map((other) => `pid ${other.pid} (${other.cmd})`).join("; ")}. It predates the one-runner lock. Stopping this daemon instead of reconnecting, so they do not keep replacing each other. Keep one: stop the other, or run \`kody update\` so both use the lock.` : `Another kody daemon for ${context.name} connected and replaced this one (not on this machine as far as kody can tell: is the same context key copied to another machine?). Stopping this daemon instead of reconnecting, so they do not keep replacing each other. Restart it with \`kody daemon restart\` once the other is gone.`
2548
+ );
2549
+ if (manager) return stayStoppedExitCode;
2550
+ return supervised ? startupRefusedExitCode : 1;
2551
+ }
2552
+ const target = updateTo;
2553
+ if (stop === "shutdown" && restartRequested && !target && !signalled) {
2554
+ return relaunchExitCode;
2555
+ }
2556
+ if (stop === "shutdown" && target && !signalled) {
2557
+ if (manager || supervised) return relaunchExitCode;
2558
+ const outcome = await superviseNewerVersion({
2559
+ first: target,
2560
+ selfVersion: input.clientVersion,
2561
+ args: relaunchArgs,
2562
+ log
2563
+ });
2564
+ if (outcome.kind === "exit") return outcome.code;
2565
+ log(`Auto-update: back on kody ${input.clientVersion}.`);
2566
+ return await runExecutionContextCommand(input);
2567
+ }
2568
+ if (stop === "revoked" || stop === "unknown_context") {
2569
+ const reason = stop === "revoked" ? "Kody revoked this context" : "Kody no longer knows this context (deleted)";
2570
+ writeJson(
2571
+ servicePaths({
2572
+ apiUrl: input.apiUrl,
2573
+ ecid,
2574
+ manager: serviceManagerFor() ?? "systemd"
2575
+ }).stoppedPath,
2576
+ { reason, at: (/* @__PURE__ */ new Date()).toISOString() }
2577
+ );
2578
+ if (manager) disableOwnService({ manager, ecid });
2579
+ input.write(
2580
+ `${reason}. Stopping for good${manager ? " and disabling the service" : ""}. Register again with: kody connect --name <name>
2581
+ `
2582
+ );
2583
+ }
2584
+ return stayStoppedExitCode;
2585
+ }
2586
+ throw new Error(
2587
+ "Usage: kody context register --name <name> [--org <slug>] | kody context list | kody context revoke <name> | kody context delete <name> | kody context cancel-run <name> <run id> | kody context policy [show | allow <path> [--mode ro|rw] | remove <path>] | kody context grant [show | allow <path> [--mode ro|rw] | remove <path> | lan on|off] [--context <name>] | kody context commands [status | on | off] [--context <name>] | kody chain show | add <name> | remove <name> | kody connect --name <name> | kody daemon [--context <ec id>] [--max-concurrent <n>] | kody daemon install | status | logs | restart | start | stop | uninstall | auto-update [on | off | status] | kody update"
2588
+ );
2589
+ }
2590
+ async function resolveContextId(input) {
2591
+ if (input.ref.startsWith("ec_")) return input.ref;
2592
+ const body = await apiJson({
2593
+ ...input,
2594
+ method: "GET",
2595
+ path: "/v1/execution-contexts"
2596
+ });
2597
+ const match = (body.contexts ?? []).find((c) => c.name === input.ref);
2598
+ if (!match)
2599
+ throw new Error(`No execution context named ${input.ref} in this org.`);
2600
+ return match.id;
2601
+ }
2602
+ function chainOf(body) {
2603
+ return body.chain ?? {};
2604
+ }
2605
+ function contextsById(body) {
2606
+ const contexts = body.contexts ?? [];
2607
+ return new Map(contexts.map((context) => [context.id, context]));
2608
+ }
2609
+ function describeChain(chain, contexts = /* @__PURE__ */ new Map()) {
2610
+ const entries = chain.entries ?? [];
2611
+ const lines = entries.map((entry, index) => {
2612
+ if (entry.kind === "cloud") return `${index + 1}. Kody cloud (always last)`;
2613
+ const known = entry.id ? contexts.get(entry.id) : void 0;
2614
+ const name = entry.name ?? known?.name;
2615
+ const label = name ? `${name} (${entry.id})` : String(entry.id);
2616
+ const offline = known?.paused ? " [paused]" : known?.status && known.status !== "online" ? ` [${known.status}]` : "";
2617
+ const skipped = entry.usable === false ? ` (skipped: ${entry.unusableReason})` : "";
2618
+ return `${index + 1}. ${label}${offline}${skipped}`;
2619
+ });
2620
+ if (chain.strict) lines.push("Strict: Kody cloud is not in this chain.");
2621
+ return lines.join("\n") || "Empty chain.";
2622
+ }
2623
+ var policyUsage = "Usage: kody context policy [show] | kody context policy allow <path> [--mode ro|rw] | kody context policy remove <path>";
2624
+ var commandsUsage = "Usage: kody context commands [status | on | off] [--context <name>] [--json]";
2625
+ async function runCommandsOptInCommand(input, [action = "status", ...extra]) {
2626
+ if (extra.length > 0 || !["status", "on", "off"].includes(action)) {
2627
+ throw new Error(commandsUsage);
2628
+ }
2629
+ const ecids = input.values.context ? [
2630
+ localContextId(input.apiUrl, input.values.context) ?? input.values.context
2631
+ ] : storedContextIds(input.apiUrl);
2632
+ if (action === "on" && input.values.context) {
2633
+ loadContext({
2634
+ apiUrl: input.apiUrl,
2635
+ ecid: ecids[0],
2636
+ wrapping: wrappingKeyForStoredContext({
2637
+ apiUrl: input.apiUrl,
2638
+ ecid: ecids[0]
2639
+ })
2640
+ });
2641
+ }
2642
+ if (action !== "status") {
2643
+ await setLocalCommandsEnabled({ enabled: action === "on" });
2644
+ }
2645
+ const local = await readLocalCommandsEnabled();
2646
+ const contexts = [];
2647
+ for (const ecid of ecids) {
2648
+ try {
2649
+ const { context, privateJwk } = loadContext({
2650
+ apiUrl: input.apiUrl,
2651
+ ecid,
2652
+ wrapping: wrappingKeyForStoredContext({ apiUrl: input.apiUrl, ecid })
2653
+ });
2654
+ const result = await setContextCommands({
2655
+ apiUrl: input.apiUrl,
2656
+ ecid: context.ecid,
2657
+ privateKey: await importContextKey(privateJwk),
2658
+ ...action === "status" ? {} : { enabled: action === "on" },
2659
+ ...input.fetchFn ? { fetchFn: input.fetchFn } : {}
2660
+ });
2661
+ contexts.push({
2662
+ id: result.id,
2663
+ name: result.name,
2664
+ commands: result.commands
2665
+ });
2666
+ } catch (error) {
2667
+ contexts.push({
2668
+ id: ecid,
2669
+ name: ecid,
2670
+ commands: null,
2671
+ error: error instanceof Error ? error.message : String(error)
2672
+ });
2673
+ }
2674
+ }
2675
+ const lines = [
2676
+ `Host commands on this machine: ${local ? "on" : "off"} (local opt-in, ${localPolicyPath()}).`,
2677
+ ...contexts.map(
2678
+ (context) => context.commands ? ` ${context.name}: ${context.commands.enabled ? "on" : "off"} in Kody` : ` ${context.name}: could not reach Kody (${context.error})`
2679
+ )
2680
+ ];
2681
+ if (contexts.length === 0) {
2682
+ lines.push(
2683
+ " This machine has no registered execution context. Run `kody connect --name <name>` first."
2684
+ );
2685
+ }
2686
+ if (action === "on") {
2687
+ lines.push(
2688
+ "Your own runs on this context can now run any command as your OS user, with no per-command approval (runs by people you share it with never can). Every command is recorded in the context audit log. Turn it off any time: kody context commands off, the desktop app, or the website."
2689
+ );
2690
+ } else if (action === "off") {
2691
+ lines.push("Background commands started by runs were stopped.");
2692
+ } else if (!local) {
2693
+ lines.push("Turn them on with: kody context commands on");
2694
+ }
2695
+ out(
2696
+ input,
2697
+ { local: { enabled: local, path: localPolicyPath() }, contexts },
2698
+ lines.join("\n")
2699
+ );
2700
+ return contexts.some((context) => context.error) ? 1 : 0;
2701
+ }
2702
+ async function runPolicyCommand(input, [action, path, ...extra]) {
2703
+ const file = localPolicyPath();
2704
+ const describe = (rules) => rules.length === 0 ? `No host folders are allowed on this machine (${file}). Execution-context runs only see their virtual filesystem.` : [
2705
+ `Host folders this machine allows (${file}):`,
2706
+ ...rules.map((rule) => ` ${rule.mode} ${rule.path}`),
2707
+ "This is the local policy. A run can use a folder only if its context server grant (grant.fs) also lists it; the narrower mode wins."
2708
+ ].join("\n");
2709
+ const grantNotes = (fs) => machineGrantNotes({
2710
+ apiUrl: input.apiUrl,
2711
+ ...input.org ? { org: input.org } : {},
2712
+ ...input.fetchFn ? { fetchFn: input.fetchFn } : {},
2713
+ token: input.token,
2714
+ policyFs: fs
2715
+ });
2716
+ if (action === void 0 || action === "show") {
2717
+ const policy = await readLocalPolicy(file);
2718
+ const serverGrant = await grantNotes(policy.fs);
2719
+ out(
2720
+ input,
2721
+ { path: file, ...policy, serverGrant },
2722
+ `${describe(policy.fs)}${describeMachineGrantNotes(serverGrant)}`
2723
+ );
2724
+ return 0;
2725
+ }
2726
+ if (!path || extra.length > 0) throw new Error(policyUsage);
2727
+ if (action === "allow") {
2728
+ const mode = input.values.mode ?? "ro";
2729
+ if (mode !== "ro" && mode !== "rw") {
2730
+ throw new Error("--mode must be ro (read-only) or rw (read-write).");
2731
+ }
2732
+ const { policy, added } = await allowLocalPath({
2733
+ path,
2734
+ mode,
2735
+ policyPath: file
2736
+ });
2737
+ const serverGrant = await grantNotes(policy.fs);
2738
+ out(
2739
+ input,
2740
+ { path: file, ...policy, serverGrant },
2741
+ `Allowed ${added.path} (${added.mode}) in this machine's local policy. Running daemons pick this up within a few seconds. This does not change the context's server grant.
2742
+ ${describe(policy.fs)}${describeMachineGrantNotes(serverGrant)}`
2743
+ );
2744
+ return 0;
2745
+ }
2746
+ if (action === "remove") {
2747
+ const { policy, removed } = await removeLocalPath({
2748
+ path,
2749
+ policyPath: file
2750
+ });
2751
+ out(
2752
+ input,
2753
+ { path: file, removed, ...policy },
2754
+ `${removed ? `Removed ${path}.` : `${path} was not in the policy.`}
2755
+ ${describe(policy.fs)}`
2756
+ );
2757
+ return 0;
2758
+ }
2759
+ throw new Error(policyUsage);
2760
+ }
2761
+ var daemonLogBufferLines = 500;
2762
+ function recentDaemonLog(logPath, buffered, lines) {
2763
+ if (logPath && existsSync(logPath)) {
2764
+ try {
2765
+ const text = readFileSync2(logPath, "utf8");
2766
+ return text.split(/\r?\n/).filter(Boolean).slice(-lines);
2767
+ } catch {
2768
+ }
2769
+ }
2770
+ return buffered.slice(-lines);
2771
+ }
2772
+ function appendOutputTo(path) {
2773
+ for (const stream of [process.stdout, process.stderr]) {
2774
+ const write = stream.write.bind(stream);
2775
+ stream.write = ((chunk, ...rest) => {
2776
+ try {
2777
+ appendFileSync(path, chunk, { mode: 384 });
2778
+ } catch {
2779
+ }
2780
+ return write(chunk, ...rest);
2781
+ });
2782
+ }
2783
+ }
2784
+ export {
2785
+ maxConcurrentRuns,
2786
+ runExecutionContextCommand
2787
+ };
2788
+ //# sourceMappingURL=commands-3CZ5DOQA.js.map