@kodycodes/cli 3.11.0 → 3.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +1 -1
- package/dist/{chunk-L225BIT7.js → chunk-CDFCKKEC.js} +1 -1
- package/dist/{chunk-L225BIT7.js.map → chunk-CDFCKKEC.js.map} +1 -1
- package/dist/{chunk-CASZNLFR.js → chunk-NN3I7FJQ.js} +34 -3
- package/dist/chunk-NN3I7FJQ.js.map +6 -0
- package/dist/cli.d.ts +8 -1
- package/dist/cli.js +1 -1
- package/dist/commands-LSLLUXHL.js +2523 -0
- package/dist/commands-LSLLUXHL.js.map +6 -0
- package/dist/execution-context/client.d.ts +4 -1
- package/dist/execution-context/commands.d.ts +11 -1
- package/dist/execution-context/daemon.d.ts +12 -2
- package/dist/execution-context/keystore.d.ts +32 -2
- package/dist/execution-context/service-commands.d.ts +75 -0
- package/dist/execution-context/service.d.ts +157 -0
- package/dist/{run-executor-NNH65ODC.js → run-executor-7CL5RXNG.js} +2 -2
- package/package.json +1 -1
- package/dist/chunk-CASZNLFR.js.map +0 -6
- package/dist/commands-DOND3A3A.js +0 -1217
- package/dist/commands-DOND3A3A.js.map +0 -6
- /package/dist/{run-executor-NNH65ODC.js.map → run-executor-7CL5RXNG.js.map} +0 -0
|
@@ -0,0 +1,2523 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
classifyFrameText,
|
|
4
|
+
decodeEnvelopePayload,
|
|
5
|
+
ecpContextKeyId,
|
|
6
|
+
ecpDefaultGrant,
|
|
7
|
+
ecpMaxConcurrentRunsCap,
|
|
8
|
+
ecpPingFrame,
|
|
9
|
+
ecpProtocolVersion,
|
|
10
|
+
ecpRunHeader,
|
|
11
|
+
ecpSignatureHeader,
|
|
12
|
+
ed25519JwkThumbprint,
|
|
13
|
+
formatEcpSignatureHeader,
|
|
14
|
+
importEd25519PrivateKey,
|
|
15
|
+
importEd25519PublicKey,
|
|
16
|
+
publishedKeyJwk,
|
|
17
|
+
signEcpHttpRequest,
|
|
18
|
+
signFrame,
|
|
19
|
+
verifyFrame,
|
|
20
|
+
verifyServerKeySet
|
|
21
|
+
} from "./chunk-CDFCKKEC.js";
|
|
22
|
+
import {
|
|
23
|
+
allowLocalPath,
|
|
24
|
+
createLocalWorkerTracker,
|
|
25
|
+
createPackageGraphCache,
|
|
26
|
+
effectiveFs,
|
|
27
|
+
emptyEffectiveFs,
|
|
28
|
+
fsFeatures,
|
|
29
|
+
localPolicyPath,
|
|
30
|
+
readLocalPolicy,
|
|
31
|
+
reapLeftoverWorkers,
|
|
32
|
+
removeLocalPath
|
|
33
|
+
} from "./chunk-CBFSRN34.js";
|
|
34
|
+
import "./chunk-LD6ND6Z3.js";
|
|
35
|
+
import {
|
|
36
|
+
apiTokenFileStorePath
|
|
37
|
+
} from "./chunk-AZ6UXLP6.js";
|
|
38
|
+
import "./chunk-NHRYNRXG.js";
|
|
39
|
+
import {
|
|
40
|
+
secretServiceKeyringOptions
|
|
41
|
+
} from "./chunk-D6XME4RY.js";
|
|
42
|
+
import {
|
|
43
|
+
keyringService
|
|
44
|
+
} from "./chunk-VP2O3HLT.js";
|
|
45
|
+
import "./chunk-UW6AWLXX.js";
|
|
46
|
+
|
|
47
|
+
// src/execution-context/commands.ts
|
|
48
|
+
import { readFileSync as readFileSync4, rmSync as rmSync2, unwatchFile, watchFile } from "node:fs";
|
|
49
|
+
import { cpus, platform, totalmem } from "node:os";
|
|
50
|
+
|
|
51
|
+
// src/execution-context/client.ts
|
|
52
|
+
var executionContextsPath = "/v1/execution-contexts";
|
|
53
|
+
var reloginHint = "Run `kody login` again, then retry `kody context register`.";
|
|
54
|
+
var ExecutionContextApiError = class extends Error {
|
|
55
|
+
constructor(message, status, code, reason = null) {
|
|
56
|
+
super(message);
|
|
57
|
+
this.status = status;
|
|
58
|
+
this.code = code;
|
|
59
|
+
this.reason = reason;
|
|
60
|
+
}
|
|
61
|
+
status;
|
|
62
|
+
code;
|
|
63
|
+
reason;
|
|
64
|
+
};
|
|
65
|
+
function isPermanentContextRefusal(error) {
|
|
66
|
+
return error instanceof ExecutionContextApiError && (error.status === 401 || error.status === 403) && (error.reason === "revoked" || error.reason === "unknown_context");
|
|
67
|
+
}
|
|
68
|
+
function experimentOffError(apiUrl) {
|
|
69
|
+
const origin = new URL(apiUrl).origin;
|
|
70
|
+
return new ExecutionContextApiError(
|
|
71
|
+
[
|
|
72
|
+
"Execution contexts are an experiment that is off for this account.",
|
|
73
|
+
`Turn them on at ${origin}/account/experiments, or ask your agent to call experimentSet with { "experiment": "execution-contexts", "enabled": true }.`,
|
|
74
|
+
`Then run this command again. Guide: ${origin}/docs/execution-contexts`
|
|
75
|
+
].join("\n"),
|
|
76
|
+
403,
|
|
77
|
+
"feature_disabled"
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
function isExperimentOffError(error) {
|
|
81
|
+
return error instanceof ExecutionContextApiError && error.code === "feature_disabled";
|
|
82
|
+
}
|
|
83
|
+
async function readError(response) {
|
|
84
|
+
const text = await response.text();
|
|
85
|
+
let code = null;
|
|
86
|
+
let reason = null;
|
|
87
|
+
let message = text || `HTTP ${response.status}`;
|
|
88
|
+
try {
|
|
89
|
+
const body = JSON.parse(text);
|
|
90
|
+
if (typeof body.error === "string") {
|
|
91
|
+
code = body.error;
|
|
92
|
+
message = body.message ?? body.error;
|
|
93
|
+
} else if (body.error) {
|
|
94
|
+
code = body.error.code ?? null;
|
|
95
|
+
message = body.error.message ?? message;
|
|
96
|
+
if (typeof body.error.details?.reason === "string") {
|
|
97
|
+
reason = body.error.details.reason;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
} catch {
|
|
101
|
+
}
|
|
102
|
+
return new ExecutionContextApiError(message, response.status, code, reason);
|
|
103
|
+
}
|
|
104
|
+
async function signedFetch(input) {
|
|
105
|
+
const body = input.body ?? "";
|
|
106
|
+
const signature = await signEcpHttpRequest({
|
|
107
|
+
ec: input.ecid,
|
|
108
|
+
method: input.method,
|
|
109
|
+
pathAndQuery: input.pathAndQuery,
|
|
110
|
+
body,
|
|
111
|
+
privateKey: input.privateKey
|
|
112
|
+
});
|
|
113
|
+
return (input.fetchFn ?? fetch)(new URL(input.pathAndQuery, input.apiUrl), {
|
|
114
|
+
method: input.method,
|
|
115
|
+
signal: input.signal,
|
|
116
|
+
headers: {
|
|
117
|
+
...input.headers,
|
|
118
|
+
[ecpSignatureHeader]: formatEcpSignatureHeader(signature),
|
|
119
|
+
...input.runId ? { [ecpRunHeader]: input.runId } : {}
|
|
120
|
+
},
|
|
121
|
+
...input.method === "GET" || input.method === "HEAD" ? {} : { body: typeof body === "string" ? body : Buffer.from(body) }
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
async function generateContextKey() {
|
|
125
|
+
const pair = await crypto.subtle.generateKey({ name: "Ed25519" }, true, [
|
|
126
|
+
"sign",
|
|
127
|
+
"verify"
|
|
128
|
+
]);
|
|
129
|
+
const privateJwk = await crypto.subtle.exportKey(
|
|
130
|
+
"jwk",
|
|
131
|
+
pair.privateKey
|
|
132
|
+
);
|
|
133
|
+
const publicKeyJwk = {
|
|
134
|
+
kty: "OKP",
|
|
135
|
+
crv: "Ed25519",
|
|
136
|
+
x: String(privateJwk.x)
|
|
137
|
+
};
|
|
138
|
+
const privateKeyJwk = {
|
|
139
|
+
...publicKeyJwk,
|
|
140
|
+
d: String(privateJwk.d)
|
|
141
|
+
};
|
|
142
|
+
return { publicKeyJwk, privateKeyJwk };
|
|
143
|
+
}
|
|
144
|
+
function importContextKey(privateJwk) {
|
|
145
|
+
return importEd25519PrivateKey(privateJwk);
|
|
146
|
+
}
|
|
147
|
+
async function registerContext(input) {
|
|
148
|
+
const fetchFn = input.fetchFn ?? fetch;
|
|
149
|
+
const query = input.org ? `?org=${encodeURIComponent(input.org)}` : "";
|
|
150
|
+
const auth = { authorization: `Bearer ${input.token}` };
|
|
151
|
+
const challengeResponse = await fetchFn(
|
|
152
|
+
new URL(
|
|
153
|
+
`${executionContextsPath}/registration-challenge${query}`,
|
|
154
|
+
input.apiUrl
|
|
155
|
+
),
|
|
156
|
+
{ method: "POST", headers: auth }
|
|
157
|
+
);
|
|
158
|
+
if (!challengeResponse.ok) throw await registrationError(challengeResponse);
|
|
159
|
+
const { challenge } = await challengeResponse.json();
|
|
160
|
+
const body = JSON.stringify({
|
|
161
|
+
name: input.name,
|
|
162
|
+
publicKeyJwk: input.publicKeyJwk,
|
|
163
|
+
challenge,
|
|
164
|
+
capabilities: input.capabilities,
|
|
165
|
+
client: input.client
|
|
166
|
+
});
|
|
167
|
+
const response = await signedFetch({
|
|
168
|
+
apiUrl: input.apiUrl,
|
|
169
|
+
ecid: input.thumbprint,
|
|
170
|
+
privateKey: input.privateKey,
|
|
171
|
+
method: "POST",
|
|
172
|
+
pathAndQuery: `${executionContextsPath}${query}`,
|
|
173
|
+
body,
|
|
174
|
+
headers: { ...auth, "content-type": "application/json" },
|
|
175
|
+
fetchFn
|
|
176
|
+
});
|
|
177
|
+
if (!response.ok) throw await registrationError(response);
|
|
178
|
+
return await response.json();
|
|
179
|
+
}
|
|
180
|
+
async function registrationError(response) {
|
|
181
|
+
const error = await readError(response);
|
|
182
|
+
if (error.code === "credential_scope" || error.message.includes("predates execution context permissions")) {
|
|
183
|
+
return new ExecutionContextApiError(
|
|
184
|
+
error.message.includes("kody login") ? error.message : `${error.message.trim()} ${reloginHint}`,
|
|
185
|
+
error.status,
|
|
186
|
+
error.code
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
return error;
|
|
190
|
+
}
|
|
191
|
+
async function requestConnectTicket(input) {
|
|
192
|
+
const response = await signedFetch({
|
|
193
|
+
...input,
|
|
194
|
+
method: "POST",
|
|
195
|
+
pathAndQuery: `${executionContextsPath}/connect-ticket`,
|
|
196
|
+
body: "{}",
|
|
197
|
+
headers: { "content-type": "application/json" }
|
|
198
|
+
});
|
|
199
|
+
if (!response.ok) throw await readError(response);
|
|
200
|
+
return await response.json();
|
|
201
|
+
}
|
|
202
|
+
async function fetchServerKeys(input) {
|
|
203
|
+
const response = await (input.fetchFn ?? fetch)(
|
|
204
|
+
new URL(`${executionContextsPath}/server-keys`, input.apiUrl)
|
|
205
|
+
);
|
|
206
|
+
if (!response.ok) throw await readError(response);
|
|
207
|
+
const set = await verifyServerKeySet({ document: await response.json() });
|
|
208
|
+
if (!set) {
|
|
209
|
+
throw new Error(
|
|
210
|
+
"Kody server keys failed root signature verification. Refusing to connect."
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
const now = input.now ?? Date.now();
|
|
214
|
+
return set.keys.filter((key) => key.notAfter > now);
|
|
215
|
+
}
|
|
216
|
+
async function apiJson(input) {
|
|
217
|
+
const url = new URL(input.path, input.apiUrl);
|
|
218
|
+
if (input.org) url.searchParams.set("org", input.org);
|
|
219
|
+
const response = await (input.fetchFn ?? fetch)(url, {
|
|
220
|
+
method: input.method,
|
|
221
|
+
headers: {
|
|
222
|
+
authorization: `Bearer ${input.token}`,
|
|
223
|
+
...input.body === void 0 ? {} : { "content-type": "application/json" }
|
|
224
|
+
},
|
|
225
|
+
...input.body === void 0 ? {} : { body: JSON.stringify(input.body) }
|
|
226
|
+
});
|
|
227
|
+
if (!response.ok) throw await readError(response);
|
|
228
|
+
return await response.json();
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// src/execution-context/daemon.ts
|
|
232
|
+
function runScopedFetch(input) {
|
|
233
|
+
const apiOrigin = new URL(input.apiUrl).origin;
|
|
234
|
+
const base = input.fetchFn ?? fetch;
|
|
235
|
+
return async (resource, init) => {
|
|
236
|
+
const request = new Request(resource, init);
|
|
237
|
+
const url = new URL(request.url);
|
|
238
|
+
if (url.origin !== apiOrigin) return base(request);
|
|
239
|
+
const body = new Uint8Array(await request.arrayBuffer());
|
|
240
|
+
const headers = {};
|
|
241
|
+
request.headers.forEach((value, name) => {
|
|
242
|
+
if (name !== "authorization") headers[name] = value;
|
|
243
|
+
});
|
|
244
|
+
return signedFetch({
|
|
245
|
+
apiUrl: input.apiUrl,
|
|
246
|
+
ecid: input.ecid,
|
|
247
|
+
privateKey: input.privateKey,
|
|
248
|
+
method: request.method,
|
|
249
|
+
pathAndQuery: `${url.pathname}${url.search}`,
|
|
250
|
+
body,
|
|
251
|
+
runId: input.runId,
|
|
252
|
+
headers,
|
|
253
|
+
fetchFn: base
|
|
254
|
+
});
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
function originOf(url) {
|
|
258
|
+
try {
|
|
259
|
+
return new URL(url).origin;
|
|
260
|
+
} catch {
|
|
261
|
+
return null;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
function runRequestRefusal(request, apiUrl, now = Date.now()) {
|
|
265
|
+
const origin = originOf(request.apiUrl);
|
|
266
|
+
if (!origin || origin !== originOf(apiUrl)) return "grant_mismatch";
|
|
267
|
+
if (now > request.acceptBy) return "deadline_passed";
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
function grantFsOf(grant) {
|
|
271
|
+
const fs = grant?.fs;
|
|
272
|
+
if (!Array.isArray(fs)) return [];
|
|
273
|
+
return fs.filter(
|
|
274
|
+
(entry) => typeof entry?.path === "string" && typeof entry?.mode === "string"
|
|
275
|
+
);
|
|
276
|
+
}
|
|
277
|
+
var layerLabel = {
|
|
278
|
+
server_grant: "server grant",
|
|
279
|
+
local_policy: "local policy"
|
|
280
|
+
};
|
|
281
|
+
var welcomeTimeoutMs = 15e3;
|
|
282
|
+
var welcomeTimeoutCloseCode = 4e3;
|
|
283
|
+
var closeSettleMs = 5e3;
|
|
284
|
+
var defaultPingMs = 3e4;
|
|
285
|
+
var defaultPongTimeoutMs = 1e4;
|
|
286
|
+
var heartbeatTimeoutCloseCode = 4001;
|
|
287
|
+
var frameRejectedCloseCode = 4008;
|
|
288
|
+
function heartbeatSetting(value, fallback) {
|
|
289
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 1e3 && value <= 3e5 ? value : fallback;
|
|
290
|
+
}
|
|
291
|
+
async function runDaemonConnection(input) {
|
|
292
|
+
const Socket = input.WebSocketImpl ?? globalThis.WebSocket;
|
|
293
|
+
if (!Socket) {
|
|
294
|
+
throw new Error(
|
|
295
|
+
"This Node.js has no global WebSocket. Use Node 22 or newer."
|
|
296
|
+
);
|
|
297
|
+
}
|
|
298
|
+
const { ticket } = await requestConnectTicket(input);
|
|
299
|
+
if (input.signal?.aborted) return { code: 1e3, reason: "shutdown" };
|
|
300
|
+
const url = new URL(`${executionContextsPath}/connect`, input.apiUrl);
|
|
301
|
+
url.protocol = url.protocol === "http:" ? "ws:" : "wss:";
|
|
302
|
+
url.searchParams.set("ticket", ticket);
|
|
303
|
+
const ws = new Socket(url.toString());
|
|
304
|
+
let welcomed = false;
|
|
305
|
+
let grantFs = [];
|
|
306
|
+
let hostFs = emptyEffectiveFs;
|
|
307
|
+
const effectiveFsNow = async () => {
|
|
308
|
+
if (!input.fs) return emptyEffectiveFs;
|
|
309
|
+
try {
|
|
310
|
+
return await input.fs.effective(grantFs);
|
|
311
|
+
} catch (error) {
|
|
312
|
+
input.log(
|
|
313
|
+
`Host folders are off: ${error instanceof Error ? error.message : String(error)}`
|
|
314
|
+
);
|
|
315
|
+
return emptyEffectiveFs;
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
const capabilities = () => {
|
|
319
|
+
const base = Array.isArray(input.capabilities.features) ? input.capabilities.features : [];
|
|
320
|
+
return {
|
|
321
|
+
...input.capabilities,
|
|
322
|
+
maxConcurrent,
|
|
323
|
+
features: [
|
|
324
|
+
...base.filter((feature) => feature !== "fs"),
|
|
325
|
+
...fsFeatures(hostFs)
|
|
326
|
+
]
|
|
327
|
+
};
|
|
328
|
+
};
|
|
329
|
+
const applyFs = async () => {
|
|
330
|
+
if (!input.fs) return;
|
|
331
|
+
hostFs = await effectiveFsNow();
|
|
332
|
+
for (const mount of hostFs.mounts) {
|
|
333
|
+
input.log(
|
|
334
|
+
`Host folder ${mount.path} is available to runs (${mount.mode}).`
|
|
335
|
+
);
|
|
336
|
+
}
|
|
337
|
+
for (const refusal of hostFs.refused) {
|
|
338
|
+
input.log(
|
|
339
|
+
`Host folder ${refusal.path} is not available: ${refusal.reason} (${layerLabel[refusal.layer]}).`
|
|
340
|
+
);
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
const refreshFs = async (before = JSON.stringify(capabilities())) => {
|
|
344
|
+
await applyFs();
|
|
345
|
+
const next = capabilities();
|
|
346
|
+
if (welcomed && JSON.stringify(next) !== before) {
|
|
347
|
+
await send("capabilities.update", { capabilities: next });
|
|
348
|
+
}
|
|
349
|
+
};
|
|
350
|
+
const unsubscribeFs = input.fs?.onChange?.(() => {
|
|
351
|
+
if (welcomed) void refreshFs().catch(() => {
|
|
352
|
+
});
|
|
353
|
+
});
|
|
354
|
+
const serverKeys = new Map(input.serverKeys.map((key) => [key.kid, key]));
|
|
355
|
+
let sid = "";
|
|
356
|
+
let inSeq = 0;
|
|
357
|
+
let outSeq = 0;
|
|
358
|
+
const runs = /* @__PURE__ */ new Map();
|
|
359
|
+
let maxConcurrent = input.maxConcurrent;
|
|
360
|
+
const applyLimits = (grant) => {
|
|
361
|
+
const limit = grant?.limits?.maxConcurrent;
|
|
362
|
+
const previous = maxConcurrent;
|
|
363
|
+
maxConcurrent = typeof limit === "number" && limit >= 1 ? Math.min(input.maxConcurrent, Math.floor(limit)) : input.maxConcurrent;
|
|
364
|
+
return maxConcurrent !== previous;
|
|
365
|
+
};
|
|
366
|
+
let outbound = Promise.resolve();
|
|
367
|
+
let outboundFailed = false;
|
|
368
|
+
const send = (t, body, re) => {
|
|
369
|
+
const sent = outbound.then(async () => {
|
|
370
|
+
if (outboundFailed) throw new Error("This connection already failed.");
|
|
371
|
+
outSeq += 1;
|
|
372
|
+
const payload = {
|
|
373
|
+
v: 1,
|
|
374
|
+
t,
|
|
375
|
+
ec: input.ecid,
|
|
376
|
+
sid,
|
|
377
|
+
seq: outSeq,
|
|
378
|
+
ts: Date.now(),
|
|
379
|
+
...re === void 0 ? {} : { re },
|
|
380
|
+
body
|
|
381
|
+
};
|
|
382
|
+
ws.send(
|
|
383
|
+
await signFrame({
|
|
384
|
+
privateKey: input.privateKey,
|
|
385
|
+
kid: ecpContextKeyId,
|
|
386
|
+
payload
|
|
387
|
+
})
|
|
388
|
+
);
|
|
389
|
+
});
|
|
390
|
+
outbound = sent.catch(() => {
|
|
391
|
+
if (outboundFailed) return;
|
|
392
|
+
outboundFailed = true;
|
|
393
|
+
try {
|
|
394
|
+
ws.close(4e3, "send failed");
|
|
395
|
+
} catch {
|
|
396
|
+
}
|
|
397
|
+
});
|
|
398
|
+
return sent;
|
|
399
|
+
};
|
|
400
|
+
let grantEgress = ecpDefaultGrant.egress;
|
|
401
|
+
const applyGrant = (grant) => {
|
|
402
|
+
const egress = grant?.egress;
|
|
403
|
+
if (egress && typeof egress.mode === "string") grantEgress = egress;
|
|
404
|
+
};
|
|
405
|
+
let rearmHeartbeat = null;
|
|
406
|
+
const status = () => ({
|
|
407
|
+
running: runs.size,
|
|
408
|
+
maxConcurrent,
|
|
409
|
+
acceptingRuns: !input.drainSignal?.aborted && runs.size < maxConcurrent
|
|
410
|
+
});
|
|
411
|
+
let closeWhenDrained = () => {
|
|
412
|
+
};
|
|
413
|
+
const startRun = async (run) => {
|
|
414
|
+
const startedAt = Date.now();
|
|
415
|
+
const committedAt = run.committedAt ?? startedAt;
|
|
416
|
+
let deadlineHit = false;
|
|
417
|
+
const timer = setTimeout(
|
|
418
|
+
() => {
|
|
419
|
+
deadlineHit = true;
|
|
420
|
+
run.abort.abort();
|
|
421
|
+
},
|
|
422
|
+
Math.max(0, run.request.deadline - Date.now())
|
|
423
|
+
);
|
|
424
|
+
let result;
|
|
425
|
+
try {
|
|
426
|
+
if (input.fs) hostFs = await effectiveFsNow();
|
|
427
|
+
result = await input.execute({
|
|
428
|
+
request: run.request,
|
|
429
|
+
// A getter, so a grant.update or policy change narrows runs already in flight.
|
|
430
|
+
...input.fs ? { hostFs: () => hostFs } : {},
|
|
431
|
+
signal: run.abort.signal,
|
|
432
|
+
egress: grantEgress,
|
|
433
|
+
fetchFn: runScopedFetch({
|
|
434
|
+
apiUrl: input.apiUrl,
|
|
435
|
+
ecid: input.ecid,
|
|
436
|
+
runId: run.request.runId,
|
|
437
|
+
privateKey: input.privateKey,
|
|
438
|
+
...input.fetchFn ? { fetchFn: input.fetchFn } : {}
|
|
439
|
+
})
|
|
440
|
+
});
|
|
441
|
+
} catch (error) {
|
|
442
|
+
result = {
|
|
443
|
+
isError: true,
|
|
444
|
+
content: [
|
|
445
|
+
{
|
|
446
|
+
type: "text",
|
|
447
|
+
text: error instanceof Error ? error.message : String(error)
|
|
448
|
+
}
|
|
449
|
+
]
|
|
450
|
+
};
|
|
451
|
+
} finally {
|
|
452
|
+
clearTimeout(timer);
|
|
453
|
+
}
|
|
454
|
+
const endedAt = Date.now();
|
|
455
|
+
const { timing: executorTiming, ...outcome } = result;
|
|
456
|
+
const resultBytes = new TextEncoder().encode(
|
|
457
|
+
JSON.stringify(outcome)
|
|
458
|
+
).byteLength;
|
|
459
|
+
const timing = {
|
|
460
|
+
queueMs: startedAt - committedAt,
|
|
461
|
+
setupMs: executorTiming?.setupMs ?? 0,
|
|
462
|
+
...executorTiming?.packageGraphMs !== void 0 ? {
|
|
463
|
+
packageGraphMs: executorTiming.packageGraphMs,
|
|
464
|
+
packageGraphCached: executorTiming.packageGraphCached === true
|
|
465
|
+
} : {},
|
|
466
|
+
executeMs: executorTiming?.executeMs ?? endedAt - startedAt,
|
|
467
|
+
daemonMs: endedAt - committedAt
|
|
468
|
+
};
|
|
469
|
+
runs.delete(run.request.runId);
|
|
470
|
+
await send("run.result", {
|
|
471
|
+
runId: run.request.runId,
|
|
472
|
+
...outcome,
|
|
473
|
+
// The local deadline stopped it: a cancel, not a code error.
|
|
474
|
+
...deadlineHit && result.isError ? { cancelReason: "deadline" } : {},
|
|
475
|
+
startedAt,
|
|
476
|
+
endedAt,
|
|
477
|
+
resultBytes,
|
|
478
|
+
timing
|
|
479
|
+
});
|
|
480
|
+
await send("status", status());
|
|
481
|
+
closeWhenDrained();
|
|
482
|
+
};
|
|
483
|
+
const handle = async (frame) => {
|
|
484
|
+
const body = frame.body;
|
|
485
|
+
const runId = typeof body.runId === "string" ? body.runId : "";
|
|
486
|
+
switch (frame.t) {
|
|
487
|
+
case "welcome":
|
|
488
|
+
clearTimeout(welcomeTimer);
|
|
489
|
+
applyGrant(body.grant);
|
|
490
|
+
applyLimits(body.grant);
|
|
491
|
+
if (input.pingMs === void 0 && input.pongTimeoutMs === void 0) {
|
|
492
|
+
rearmHeartbeat?.(
|
|
493
|
+
heartbeatSetting(body.pingMs, defaultPingMs),
|
|
494
|
+
heartbeatSetting(body.pongTimeoutMs, defaultPongTimeoutMs)
|
|
495
|
+
);
|
|
496
|
+
}
|
|
497
|
+
grantFs = grantFsOf(body.grant);
|
|
498
|
+
await applyFs();
|
|
499
|
+
welcomed = true;
|
|
500
|
+
await send("hello", {
|
|
501
|
+
protocol: { min: ecpProtocolVersion, max: ecpProtocolVersion },
|
|
502
|
+
client: input.client,
|
|
503
|
+
capabilities: capabilities(),
|
|
504
|
+
grantVersion: body.grantVersion,
|
|
505
|
+
status: status(),
|
|
506
|
+
// Kody ends committed runs this daemon no longer holds right away.
|
|
507
|
+
heldRuns: [...runs.values()].filter((run) => run.committed).map((run) => run.request.runId),
|
|
508
|
+
pendingResults: []
|
|
509
|
+
});
|
|
510
|
+
input.log("Connected. Waiting for runs.");
|
|
511
|
+
return;
|
|
512
|
+
case "run.request": {
|
|
513
|
+
const request = body;
|
|
514
|
+
if (input.drainSignal?.aborted || runs.size >= maxConcurrent) {
|
|
515
|
+
await send("run.reject", { runId, code: "busy" }, frame.seq);
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
const refusal = runRequestRefusal(request, input.apiUrl);
|
|
519
|
+
if (refusal) {
|
|
520
|
+
await send("run.reject", { runId, code: refusal }, frame.seq);
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
runs.set(runId, {
|
|
524
|
+
request,
|
|
525
|
+
abort: new AbortController(),
|
|
526
|
+
committed: false
|
|
527
|
+
});
|
|
528
|
+
await send("run.accept", { runId }, frame.seq);
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
case "run.commit": {
|
|
532
|
+
const run = runs.get(runId);
|
|
533
|
+
if (!run || run.committed) return;
|
|
534
|
+
run.committed = true;
|
|
535
|
+
run.committedAt = Date.now();
|
|
536
|
+
input.log(
|
|
537
|
+
`Running ${runId} for ${run.request.requestedBy.handle ?? run.request.requestedBy.userId}.`
|
|
538
|
+
);
|
|
539
|
+
void startRun(run);
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
case "run.abort":
|
|
543
|
+
case "run.cancel": {
|
|
544
|
+
const run = runs.get(runId);
|
|
545
|
+
run?.abort.abort();
|
|
546
|
+
if (!run?.committed) runs.delete(runId);
|
|
547
|
+
if (frame.t === "run.cancel")
|
|
548
|
+
await send("run.cancel.ack", { runId }, frame.seq);
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
case "grant.update": {
|
|
552
|
+
applyGrant(body.grant);
|
|
553
|
+
grantFs = grantFsOf(body.grant);
|
|
554
|
+
const before = JSON.stringify(capabilities());
|
|
555
|
+
const limitsChanged = applyLimits(body.grant);
|
|
556
|
+
await refreshFs(before);
|
|
557
|
+
await send("grant.ack", { grantVersion: body.grantVersion }, frame.seq);
|
|
558
|
+
if (limitsChanged) await send("status", status());
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
case "revoke":
|
|
562
|
+
input.log(
|
|
563
|
+
`This context was revoked (${String(body.reason ?? "revoked")}).`
|
|
564
|
+
);
|
|
565
|
+
ws.close(1e3, "revoked");
|
|
566
|
+
return;
|
|
567
|
+
case "error":
|
|
568
|
+
input.log(`Kody: ${String(body.code)} ${String(body.message ?? "")}`);
|
|
569
|
+
return;
|
|
570
|
+
default:
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
};
|
|
574
|
+
const timeoutMs = input.welcomeTimeoutMs ?? welcomeTimeoutMs;
|
|
575
|
+
let welcomeTimer;
|
|
576
|
+
return await new Promise((resolve) => {
|
|
577
|
+
let lastInboundAt = Date.now();
|
|
578
|
+
let ping;
|
|
579
|
+
let pongTimer;
|
|
580
|
+
const armHeartbeat = (pingMs, pongTimeoutMs) => {
|
|
581
|
+
clearInterval(ping);
|
|
582
|
+
ping = setInterval(() => {
|
|
583
|
+
if (ws.readyState !== ws.OPEN || pongTimer) return;
|
|
584
|
+
const sentAt = Date.now();
|
|
585
|
+
ws.send(ecpPingFrame);
|
|
586
|
+
pongTimer = setTimeout(() => {
|
|
587
|
+
pongTimer = void 0;
|
|
588
|
+
if (lastInboundAt >= sentAt) return;
|
|
589
|
+
input.log(
|
|
590
|
+
`Kody did not answer a ping within ${Math.round(pongTimeoutMs / 1e3)}s, so the connection is dead. Closing and reconnecting.`
|
|
591
|
+
);
|
|
592
|
+
closeAndSettle(heartbeatTimeoutCloseCode, "heartbeat timeout");
|
|
593
|
+
}, pongTimeoutMs);
|
|
594
|
+
}, pingMs);
|
|
595
|
+
};
|
|
596
|
+
rearmHeartbeat = armHeartbeat;
|
|
597
|
+
armHeartbeat(
|
|
598
|
+
input.pingMs ?? defaultPingMs,
|
|
599
|
+
input.pongTimeoutMs ?? defaultPongTimeoutMs
|
|
600
|
+
);
|
|
601
|
+
let settled = false;
|
|
602
|
+
let settleTimer;
|
|
603
|
+
const finish = (code, reason) => {
|
|
604
|
+
if (settled) return;
|
|
605
|
+
settled = true;
|
|
606
|
+
clearInterval(ping);
|
|
607
|
+
clearTimeout(pongTimer);
|
|
608
|
+
clearTimeout(welcomeTimer);
|
|
609
|
+
clearTimeout(settleTimer);
|
|
610
|
+
unsubscribeFs?.();
|
|
611
|
+
input.signal?.removeEventListener("abort", shutdown);
|
|
612
|
+
input.drainSignal?.removeEventListener("abort", drain);
|
|
613
|
+
for (const run of runs.values()) run.abort.abort();
|
|
614
|
+
resolve({ code, reason });
|
|
615
|
+
};
|
|
616
|
+
const closeAndSettle = (code, reason) => {
|
|
617
|
+
try {
|
|
618
|
+
ws.close(code, reason);
|
|
619
|
+
} catch {
|
|
620
|
+
}
|
|
621
|
+
settleTimer ??= setTimeout(
|
|
622
|
+
() => finish(code, reason),
|
|
623
|
+
input.closeSettleMs ?? closeSettleMs
|
|
624
|
+
);
|
|
625
|
+
};
|
|
626
|
+
welcomeTimer = setTimeout(() => {
|
|
627
|
+
input.log(
|
|
628
|
+
`Kody did not send a welcome frame within ${Math.round(timeoutMs / 1e3)}s, so this context cannot come online. Closing and retrying.`
|
|
629
|
+
);
|
|
630
|
+
closeAndSettle(welcomeTimeoutCloseCode, "welcome timeout");
|
|
631
|
+
}, timeoutMs);
|
|
632
|
+
const shutdown = () => closeAndSettle(1e3, "shutdown");
|
|
633
|
+
if (input.signal?.aborted) shutdown();
|
|
634
|
+
input.signal?.addEventListener("abort", shutdown, { once: true });
|
|
635
|
+
closeWhenDrained = () => {
|
|
636
|
+
if (!input.drainSignal?.aborted) return;
|
|
637
|
+
if ([...runs.values()].some((run) => run.committed)) return;
|
|
638
|
+
closeAndSettle(1e3, "shutdown");
|
|
639
|
+
};
|
|
640
|
+
const drain = () => {
|
|
641
|
+
input.log(
|
|
642
|
+
runs.size > 0 ? `Stopping after ${runs.size} run(s) in flight finish. New runs go to the next context in the chain.` : "Stopping."
|
|
643
|
+
);
|
|
644
|
+
if (welcomed) void send("status", status()).catch(() => {
|
|
645
|
+
});
|
|
646
|
+
closeWhenDrained();
|
|
647
|
+
};
|
|
648
|
+
if (input.drainSignal?.aborted) drain();
|
|
649
|
+
else input.drainSignal?.addEventListener("abort", drain, { once: true });
|
|
650
|
+
const rejectFrame = (code) => {
|
|
651
|
+
input.log(
|
|
652
|
+
`Kody sent a frame that failed verification (${code}). Closing and reconnecting.`
|
|
653
|
+
);
|
|
654
|
+
closeAndSettle(frameRejectedCloseCode, code);
|
|
655
|
+
};
|
|
656
|
+
let inbound = Promise.resolve();
|
|
657
|
+
ws.addEventListener("message", (event) => {
|
|
658
|
+
lastInboundAt = Date.now();
|
|
659
|
+
const text = typeof event.data === "string" ? event.data : "";
|
|
660
|
+
inbound = inbound.then(() => onMessage(text)).catch((error) => input.log(`Frame error: ${String(error)}`));
|
|
661
|
+
});
|
|
662
|
+
const onMessage = async (text) => {
|
|
663
|
+
if (settled || settleTimer) return;
|
|
664
|
+
const classified = classifyFrameText(text);
|
|
665
|
+
if (classified.kind !== "frame") return;
|
|
666
|
+
const key = serverKeys.get(classified.envelope.k);
|
|
667
|
+
if (!key) {
|
|
668
|
+
rejectFrame("unknown_server_key");
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
if (!sid) {
|
|
672
|
+
sid = peekSid(classified.envelope.p);
|
|
673
|
+
}
|
|
674
|
+
const verified = await verifyFrame({
|
|
675
|
+
envelope: classified.envelope,
|
|
676
|
+
publicKey: await importEd25519PublicKey(publishedKeyJwk(key)),
|
|
677
|
+
expect: { ec: input.ecid, sid, lastSeq: inSeq },
|
|
678
|
+
now: Date.now()
|
|
679
|
+
});
|
|
680
|
+
if (!verified.ok) {
|
|
681
|
+
rejectFrame(verified.code);
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
inSeq = verified.frame.seq;
|
|
685
|
+
await handle(verified.frame);
|
|
686
|
+
};
|
|
687
|
+
ws.addEventListener("close", (event) => finish(event.code, event.reason));
|
|
688
|
+
});
|
|
689
|
+
}
|
|
690
|
+
function peekSid(p) {
|
|
691
|
+
try {
|
|
692
|
+
const decoded = decodeEnvelopePayload(p);
|
|
693
|
+
return decoded?.t === "welcome" && typeof decoded.body?.sid === "string" ? decoded.body.sid : "";
|
|
694
|
+
} catch {
|
|
695
|
+
return "";
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
async function runDaemon(input) {
|
|
699
|
+
let attempt = 0;
|
|
700
|
+
const stopping = () => input.signal?.aborted || input.drainSignal?.aborted;
|
|
701
|
+
while (!stopping()) {
|
|
702
|
+
const startedAt = Date.now();
|
|
703
|
+
try {
|
|
704
|
+
const closed = await runDaemonConnection(input);
|
|
705
|
+
if (closed.reason === "revoked") return "revoked";
|
|
706
|
+
if (stopping()) return "shutdown";
|
|
707
|
+
input.log(
|
|
708
|
+
`Disconnected (${closed.code}${closed.reason ? ` ${closed.reason}` : ""}). Reconnecting.`
|
|
709
|
+
);
|
|
710
|
+
} catch (error) {
|
|
711
|
+
if (stopping()) return "shutdown";
|
|
712
|
+
if (isExperimentOffError(error)) throw experimentOffError(input.apiUrl);
|
|
713
|
+
if (isPermanentContextRefusal(error)) {
|
|
714
|
+
input.log(
|
|
715
|
+
`Kody refused this context: ${error instanceof Error ? error.message : String(error)} Stopping for good.`
|
|
716
|
+
);
|
|
717
|
+
return error.reason === "revoked" ? "revoked" : "unknown_context";
|
|
718
|
+
}
|
|
719
|
+
input.log(
|
|
720
|
+
`Connect failed: ${error instanceof Error ? error.message : String(error)}`
|
|
721
|
+
);
|
|
722
|
+
}
|
|
723
|
+
if (Date.now() - startedAt > 6e4) attempt = 0;
|
|
724
|
+
attempt += 1;
|
|
725
|
+
const delay = Math.min(6e4, 1e3 * 2 ** Math.min(attempt, 6));
|
|
726
|
+
await abortableDelay(
|
|
727
|
+
delay * (0.5 + Math.random() / 2),
|
|
728
|
+
input.drainSignal ? AbortSignal.any(
|
|
729
|
+
[input.signal, input.drainSignal].filter(
|
|
730
|
+
(signal) => signal !== void 0
|
|
731
|
+
)
|
|
732
|
+
) : input.signal
|
|
733
|
+
);
|
|
734
|
+
}
|
|
735
|
+
return "shutdown";
|
|
736
|
+
}
|
|
737
|
+
function abortableDelay(ms, signal) {
|
|
738
|
+
return new Promise((resolve) => {
|
|
739
|
+
if (signal?.aborted) return resolve();
|
|
740
|
+
const done = () => {
|
|
741
|
+
clearTimeout(timer);
|
|
742
|
+
signal?.removeEventListener("abort", done);
|
|
743
|
+
resolve();
|
|
744
|
+
};
|
|
745
|
+
const timer = setTimeout(done, ms);
|
|
746
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// src/execution-context/keystore.ts
|
|
751
|
+
import {
|
|
752
|
+
createCipheriv,
|
|
753
|
+
createDecipheriv,
|
|
754
|
+
randomBytes,
|
|
755
|
+
scryptSync
|
|
756
|
+
} from "node:crypto";
|
|
757
|
+
import {
|
|
758
|
+
chmodSync,
|
|
759
|
+
existsSync,
|
|
760
|
+
mkdirSync,
|
|
761
|
+
readFileSync,
|
|
762
|
+
renameSync,
|
|
763
|
+
writeFileSync
|
|
764
|
+
} from "node:fs";
|
|
765
|
+
import { dirname, join } from "node:path";
|
|
766
|
+
import { Entry } from "@napi-rs/keyring";
|
|
767
|
+
var contextKeyPassphraseEnvVar = "KODY_CONTEXT_KEY_PASSPHRASE";
|
|
768
|
+
function contextsDir(apiUrl) {
|
|
769
|
+
return join(dirname(apiTokenFileStorePath(apiUrl)), "contexts");
|
|
770
|
+
}
|
|
771
|
+
function contextDir(apiUrl, ecid) {
|
|
772
|
+
if (!/^ec_[A-Za-z0-9_-]+$/.test(ecid)) {
|
|
773
|
+
throw new Error(`Not an execution context id: ${ecid}`);
|
|
774
|
+
}
|
|
775
|
+
return join(contextsDir(apiUrl), ecid);
|
|
776
|
+
}
|
|
777
|
+
function contextWorkersDir(apiUrl, ecid) {
|
|
778
|
+
return join(contextDir(apiUrl, ecid), "workers");
|
|
779
|
+
}
|
|
780
|
+
function resolveWrappingKey(input) {
|
|
781
|
+
const env = input.env ?? process.env;
|
|
782
|
+
const passphrase = env[contextKeyPassphraseEnvVar];
|
|
783
|
+
if (passphrase) {
|
|
784
|
+
return {
|
|
785
|
+
kind: "passphrase",
|
|
786
|
+
key: (salt) => scryptSync(passphrase, salt ?? Buffer.alloc(16), 32, {
|
|
787
|
+
N: 1 << 15,
|
|
788
|
+
r: 8,
|
|
789
|
+
p: 1,
|
|
790
|
+
maxmem: 64 * 1024 * 1024
|
|
791
|
+
})
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
const account = `execution-context:${input.ecid}`;
|
|
795
|
+
let entry;
|
|
796
|
+
try {
|
|
797
|
+
entry = input.keyringFactory ? input.keyringFactory(account) : new Entry(keyringService, account, secretServiceKeyringOptions);
|
|
798
|
+
} catch {
|
|
799
|
+
throw noWrappingKeyError();
|
|
800
|
+
}
|
|
801
|
+
return {
|
|
802
|
+
kind: "keyring",
|
|
803
|
+
key: () => {
|
|
804
|
+
let stored = null;
|
|
805
|
+
try {
|
|
806
|
+
stored = entry.getPassword();
|
|
807
|
+
} catch {
|
|
808
|
+
stored = null;
|
|
809
|
+
}
|
|
810
|
+
if (stored) return Buffer.from(stored, "base64url");
|
|
811
|
+
if (!input.create) {
|
|
812
|
+
throw new Error(
|
|
813
|
+
"The key for this execution context is missing from the OS keyring. Re-register the machine with `kody context register`."
|
|
814
|
+
);
|
|
815
|
+
}
|
|
816
|
+
const fresh = randomBytes(32);
|
|
817
|
+
try {
|
|
818
|
+
entry.setPassword(fresh.toString("base64url"));
|
|
819
|
+
} catch {
|
|
820
|
+
throw noWrappingKeyError();
|
|
821
|
+
}
|
|
822
|
+
return fresh;
|
|
823
|
+
}
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
function fileWrappingKeyPath(apiUrl, ecid) {
|
|
827
|
+
return join(contextDir(apiUrl, ecid), "wrapping-key");
|
|
828
|
+
}
|
|
829
|
+
function fileWrappingKey(input) {
|
|
830
|
+
const path = fileWrappingKeyPath(input.apiUrl, input.ecid);
|
|
831
|
+
return {
|
|
832
|
+
kind: "file",
|
|
833
|
+
key: () => {
|
|
834
|
+
if (existsSync(path)) {
|
|
835
|
+
return Buffer.from(readFileSync(path, "utf8").trim(), "base64url");
|
|
836
|
+
}
|
|
837
|
+
if (!input.create) {
|
|
838
|
+
throw new Error(
|
|
839
|
+
`The file key for this execution context is missing (${path}). Re-register the machine with \`kody connect\`.`
|
|
840
|
+
);
|
|
841
|
+
}
|
|
842
|
+
const fresh = randomBytes(32);
|
|
843
|
+
mkdirSync(dirname(path), { recursive: true, mode: 448 });
|
|
844
|
+
writeFileSync(path, `${fresh.toString("base64url")}
|
|
845
|
+
`, { mode: 384 });
|
|
846
|
+
chmodSync(path, 384);
|
|
847
|
+
return fresh;
|
|
848
|
+
}
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
function storedKeyWrap(apiUrl, ecid) {
|
|
852
|
+
try {
|
|
853
|
+
const file = JSON.parse(
|
|
854
|
+
readFileSync(join(contextDir(apiUrl, ecid), "key.enc"), "utf8")
|
|
855
|
+
);
|
|
856
|
+
return file.wrap;
|
|
857
|
+
} catch {
|
|
858
|
+
return null;
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
function wrappingKeyForStoredContext(input) {
|
|
862
|
+
return storedKeyWrap(input.apiUrl, input.ecid) === "file" ? fileWrappingKey({ ...input, create: false }) : resolveWrappingKey({
|
|
863
|
+
ecid: input.ecid,
|
|
864
|
+
create: false,
|
|
865
|
+
...input.env ? { env: input.env } : {}
|
|
866
|
+
});
|
|
867
|
+
}
|
|
868
|
+
function rewrapContextKey(input) {
|
|
869
|
+
const dir = contextDir(input.apiUrl, input.ecid);
|
|
870
|
+
const keyPath = join(dir, "key.enc");
|
|
871
|
+
const file = JSON.parse(readFileSync(keyPath, "utf8"));
|
|
872
|
+
const privateJwk = decryptPrivateKey(file, input.from);
|
|
873
|
+
const next = `${keyPath}.next`;
|
|
874
|
+
writeFileSync(next, JSON.stringify(encryptPrivateKey(privateJwk, input.to)), {
|
|
875
|
+
mode: 384
|
|
876
|
+
});
|
|
877
|
+
chmodSync(next, 384);
|
|
878
|
+
renameSync(next, keyPath);
|
|
879
|
+
}
|
|
880
|
+
function noWrappingKeyError() {
|
|
881
|
+
return new Error(
|
|
882
|
+
`No OS keyring is available to protect this machine's execution context key. Set ${contextKeyPassphraseEnvVar} to a strong passphrase and retry.`
|
|
883
|
+
);
|
|
884
|
+
}
|
|
885
|
+
function encryptPrivateKey(privateJwk, wrapping) {
|
|
886
|
+
const salt = wrapping.kind === "passphrase" ? randomBytes(16) : null;
|
|
887
|
+
const key = wrapping.key(salt);
|
|
888
|
+
const iv = randomBytes(12);
|
|
889
|
+
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
890
|
+
const data = Buffer.concat([
|
|
891
|
+
cipher.update(JSON.stringify(privateJwk), "utf8"),
|
|
892
|
+
cipher.final()
|
|
893
|
+
]);
|
|
894
|
+
return {
|
|
895
|
+
version: 1,
|
|
896
|
+
wrap: wrapping.kind,
|
|
897
|
+
...salt ? { salt: salt.toString("base64url") } : {},
|
|
898
|
+
iv: iv.toString("base64url"),
|
|
899
|
+
tag: cipher.getAuthTag().toString("base64url"),
|
|
900
|
+
data: data.toString("base64url")
|
|
901
|
+
};
|
|
902
|
+
}
|
|
903
|
+
function decryptPrivateKey(file, wrapping) {
|
|
904
|
+
if (file.wrap !== wrapping.kind) {
|
|
905
|
+
throw new Error(
|
|
906
|
+
file.wrap === "passphrase" ? `This context key is protected by a passphrase. Set ${contextKeyPassphraseEnvVar}.` : file.wrap === "file" ? "This context key is protected by a file key." : `This context key is protected by the OS keyring. Unset ${contextKeyPassphraseEnvVar}.`
|
|
907
|
+
);
|
|
908
|
+
}
|
|
909
|
+
const key = wrapping.key(
|
|
910
|
+
file.salt ? Buffer.from(file.salt, "base64url") : null
|
|
911
|
+
);
|
|
912
|
+
const decipher = createDecipheriv(
|
|
913
|
+
"aes-256-gcm",
|
|
914
|
+
key,
|
|
915
|
+
Buffer.from(file.iv, "base64url")
|
|
916
|
+
);
|
|
917
|
+
decipher.setAuthTag(Buffer.from(file.tag, "base64url"));
|
|
918
|
+
try {
|
|
919
|
+
const plain = Buffer.concat([
|
|
920
|
+
decipher.update(Buffer.from(file.data, "base64url")),
|
|
921
|
+
decipher.final()
|
|
922
|
+
]);
|
|
923
|
+
return JSON.parse(plain.toString("utf8"));
|
|
924
|
+
} catch {
|
|
925
|
+
throw new Error(
|
|
926
|
+
"Could not decrypt the execution context key. The passphrase, keyring entry, or file key does not match."
|
|
927
|
+
);
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
function saveContext(input) {
|
|
931
|
+
const dir = contextDir(input.context.apiUrl, input.context.ecid);
|
|
932
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
933
|
+
const keyPath = join(dir, "key.enc");
|
|
934
|
+
writeFileSync(
|
|
935
|
+
keyPath,
|
|
936
|
+
JSON.stringify(encryptPrivateKey(input.privateJwk, input.wrapping)),
|
|
937
|
+
{ mode: 384 }
|
|
938
|
+
);
|
|
939
|
+
chmodSync(keyPath, 384);
|
|
940
|
+
writeFileSync(
|
|
941
|
+
join(dir, "context.json"),
|
|
942
|
+
`${JSON.stringify(input.context, null, 2)}
|
|
943
|
+
`,
|
|
944
|
+
{ mode: 384 }
|
|
945
|
+
);
|
|
946
|
+
}
|
|
947
|
+
function readStoredContext(apiUrl, ecid) {
|
|
948
|
+
try {
|
|
949
|
+
return JSON.parse(
|
|
950
|
+
readFileSync(join(contextDir(apiUrl, ecid), "context.json"), "utf8")
|
|
951
|
+
);
|
|
952
|
+
} catch {
|
|
953
|
+
return null;
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
function loadContext(input) {
|
|
957
|
+
const dir = contextDir(input.apiUrl, input.ecid);
|
|
958
|
+
const context = JSON.parse(
|
|
959
|
+
readFileSync(join(dir, "context.json"), "utf8")
|
|
960
|
+
);
|
|
961
|
+
const file = JSON.parse(readFileSync(join(dir, "key.enc"), "utf8"));
|
|
962
|
+
return { context, privateJwk: decryptPrivateKey(file, input.wrapping) };
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
// src/execution-context/service-commands.ts
|
|
966
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
967
|
+
import { existsSync as existsSync3, readFileSync as readFileSync3, readdirSync } from "node:fs";
|
|
968
|
+
import { createInterface } from "node:readline";
|
|
969
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
970
|
+
|
|
971
|
+
// src/execution-context/service.ts
|
|
972
|
+
import { execFileSync } from "node:child_process";
|
|
973
|
+
import {
|
|
974
|
+
existsSync as existsSync2,
|
|
975
|
+
mkdirSync as mkdirSync2,
|
|
976
|
+
readFileSync as readFileSync2,
|
|
977
|
+
realpathSync,
|
|
978
|
+
rmSync,
|
|
979
|
+
writeFileSync as writeFileSync2
|
|
980
|
+
} from "node:fs";
|
|
981
|
+
import { homedir, tmpdir, userInfo } from "node:os";
|
|
982
|
+
import { delimiter, dirname as dirname2, join as join2, sep } from "node:path";
|
|
983
|
+
var serviceEnvVar = "KODY_DAEMON_SERVICE";
|
|
984
|
+
var stayStoppedExitCode = 0;
|
|
985
|
+
function serviceManagerFor(platform2 = process.platform) {
|
|
986
|
+
if (platform2 === "linux") return "systemd";
|
|
987
|
+
if (platform2 === "darwin") return "launchd";
|
|
988
|
+
return null;
|
|
989
|
+
}
|
|
990
|
+
var unsupportedPlatformMessage = "Running kody daemon as a background service is supported on Linux (systemd) and macOS (launchd). Windows is not supported yet: keep `kody daemon` running in a terminal instead.";
|
|
991
|
+
function serviceName(ecid) {
|
|
992
|
+
return `kody-daemon-${ecid}`;
|
|
993
|
+
}
|
|
994
|
+
function launchdLabel(ecid) {
|
|
995
|
+
return `codes.kody.daemon.${ecid}`;
|
|
996
|
+
}
|
|
997
|
+
function servicePaths(input) {
|
|
998
|
+
const home = input.home ?? homedir();
|
|
999
|
+
const env = input.env ?? process.env;
|
|
1000
|
+
const dir = contextDir(input.apiUrl, input.ecid);
|
|
1001
|
+
return {
|
|
1002
|
+
manager: input.manager,
|
|
1003
|
+
unitPath: input.manager === "systemd" ? join2(
|
|
1004
|
+
env.XDG_CONFIG_HOME || join2(home, ".config"),
|
|
1005
|
+
"systemd",
|
|
1006
|
+
"user",
|
|
1007
|
+
`${serviceName(input.ecid)}.service`
|
|
1008
|
+
) : join2(
|
|
1009
|
+
home,
|
|
1010
|
+
"Library",
|
|
1011
|
+
"LaunchAgents",
|
|
1012
|
+
`${launchdLabel(input.ecid)}.plist`
|
|
1013
|
+
),
|
|
1014
|
+
logPath: join2(dir, "daemon.log"),
|
|
1015
|
+
statePath: join2(dir, "daemon.json"),
|
|
1016
|
+
stoppedPath: join2(dir, "stopped.json"),
|
|
1017
|
+
workingDir: dir
|
|
1018
|
+
};
|
|
1019
|
+
}
|
|
1020
|
+
function ephemeralRuntimeReason(entryPath, tmp = tmpdir()) {
|
|
1021
|
+
const parts = entryPath.split(/[\\/]+/);
|
|
1022
|
+
if (parts.includes("_npx")) return "npx";
|
|
1023
|
+
if (parts.some((part) => part === "dlx" || part.startsWith("dlx-"))) {
|
|
1024
|
+
return "pnpm dlx";
|
|
1025
|
+
}
|
|
1026
|
+
if (parts.some((part) => part.startsWith("bunx-"))) return "bunx";
|
|
1027
|
+
if (tmp && entryPath.startsWith(tmp + sep)) return "a temporary directory";
|
|
1028
|
+
return null;
|
|
1029
|
+
}
|
|
1030
|
+
var npxRefusal = (how) => `This kody CLI is running from ${how}, which is deleted after the command ends, so a background service could not start it again. Install the CLI globally first:
|
|
1031
|
+
npm install -g @kodycodes/cli
|
|
1032
|
+
then run:
|
|
1033
|
+
kody daemon install`;
|
|
1034
|
+
function currentProgram(version) {
|
|
1035
|
+
const entry = process.argv[1] ?? "";
|
|
1036
|
+
let resolved = entry;
|
|
1037
|
+
try {
|
|
1038
|
+
resolved = realpathSync(entry);
|
|
1039
|
+
} catch {
|
|
1040
|
+
}
|
|
1041
|
+
return { node: process.execPath, entry: resolved, version };
|
|
1042
|
+
}
|
|
1043
|
+
function daemonArgs(input) {
|
|
1044
|
+
return [
|
|
1045
|
+
input.program.entry,
|
|
1046
|
+
"daemon",
|
|
1047
|
+
"--context",
|
|
1048
|
+
input.ecid,
|
|
1049
|
+
"--api-url",
|
|
1050
|
+
input.apiUrl,
|
|
1051
|
+
...input.maxConcurrent === void 0 ? [] : ["--max-concurrent", String(input.maxConcurrent)]
|
|
1052
|
+
];
|
|
1053
|
+
}
|
|
1054
|
+
function servicePath(input) {
|
|
1055
|
+
const platform2 = input.platform ?? process.platform;
|
|
1056
|
+
const dirs = [
|
|
1057
|
+
dirname2(input.node),
|
|
1058
|
+
...platform2 === "darwin" ? ["/opt/homebrew/bin"] : [],
|
|
1059
|
+
"/usr/local/bin",
|
|
1060
|
+
"/usr/bin",
|
|
1061
|
+
"/bin",
|
|
1062
|
+
"/usr/sbin",
|
|
1063
|
+
"/sbin"
|
|
1064
|
+
];
|
|
1065
|
+
return [...new Set(dirs)].join(platform2 === "win32" ? ";" : delimiter);
|
|
1066
|
+
}
|
|
1067
|
+
function serviceEnvironment(input) {
|
|
1068
|
+
const env = input.env ?? process.env;
|
|
1069
|
+
return {
|
|
1070
|
+
PATH: servicePath({
|
|
1071
|
+
node: input.program.node,
|
|
1072
|
+
...input.platform ? { platform: input.platform } : {}
|
|
1073
|
+
}),
|
|
1074
|
+
[serviceEnvVar]: input.paths.manager,
|
|
1075
|
+
...env.XDG_CONFIG_HOME ? { XDG_CONFIG_HOME: env.XDG_CONFIG_HOME } : {}
|
|
1076
|
+
};
|
|
1077
|
+
}
|
|
1078
|
+
function systemdQuote(value) {
|
|
1079
|
+
return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`;
|
|
1080
|
+
}
|
|
1081
|
+
function systemdPath(value) {
|
|
1082
|
+
return value.replace(/[\n\r]/g, "").replace(/%/g, "%%");
|
|
1083
|
+
}
|
|
1084
|
+
function systemdUnit(input) {
|
|
1085
|
+
const env = serviceEnvironment(input);
|
|
1086
|
+
return [
|
|
1087
|
+
"# Written by `kody daemon install`. Re-run it to repair; remove with `kody daemon uninstall`.",
|
|
1088
|
+
"[Unit]",
|
|
1089
|
+
`Description=Kody execution context ${input.contextName.replace(/[\n\r]/g, " ")} (${input.ecid})`,
|
|
1090
|
+
"Documentation=https://kody.codes/docs/use/execution-contexts",
|
|
1091
|
+
"StartLimitIntervalSec=300",
|
|
1092
|
+
"StartLimitBurst=5",
|
|
1093
|
+
"",
|
|
1094
|
+
"[Service]",
|
|
1095
|
+
"Type=simple",
|
|
1096
|
+
`ExecStart=${[input.program.node, ...daemonArgs(input)].map(systemdQuote).join(" ")}`,
|
|
1097
|
+
`WorkingDirectory=${systemdPath(input.paths.workingDir)}`,
|
|
1098
|
+
...Object.entries(env).map(
|
|
1099
|
+
([key, value]) => `Environment=${systemdQuote(`${key}=${value}`)}`
|
|
1100
|
+
),
|
|
1101
|
+
"Restart=always",
|
|
1102
|
+
"RestartSec=10",
|
|
1103
|
+
`RestartPreventExitStatus=${stayStoppedExitCode}`,
|
|
1104
|
+
"TimeoutStopSec=90",
|
|
1105
|
+
`StandardOutput=append:${systemdPath(input.paths.logPath)}`,
|
|
1106
|
+
`StandardError=append:${systemdPath(input.paths.logPath)}`,
|
|
1107
|
+
"",
|
|
1108
|
+
"[Install]",
|
|
1109
|
+
"WantedBy=default.target",
|
|
1110
|
+
""
|
|
1111
|
+
].join("\n");
|
|
1112
|
+
}
|
|
1113
|
+
function xml(value) {
|
|
1114
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
1115
|
+
}
|
|
1116
|
+
function launchdPlist(input) {
|
|
1117
|
+
const env = serviceEnvironment(input);
|
|
1118
|
+
const strings = (values) => values.map((value) => ` <string>${xml(value)}</string>`).join("\n");
|
|
1119
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
1120
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
1121
|
+
<!-- Written by \`kody daemon install\`. Re-run it to repair; remove with \`kody daemon uninstall\`. -->
|
|
1122
|
+
<plist version="1.0">
|
|
1123
|
+
<dict>
|
|
1124
|
+
<key>Label</key>
|
|
1125
|
+
<string>${xml(launchdLabel(input.ecid))}</string>
|
|
1126
|
+
<key>ProgramArguments</key>
|
|
1127
|
+
<array>
|
|
1128
|
+
${strings([input.program.node, ...daemonArgs(input)])}
|
|
1129
|
+
</array>
|
|
1130
|
+
<key>EnvironmentVariables</key>
|
|
1131
|
+
<dict>
|
|
1132
|
+
${Object.entries(env).map(
|
|
1133
|
+
([key, value]) => ` <key>${xml(key)}</key>
|
|
1134
|
+
<string>${xml(value)}</string>`
|
|
1135
|
+
).join("\n")}
|
|
1136
|
+
</dict>
|
|
1137
|
+
<key>WorkingDirectory</key>
|
|
1138
|
+
<string>${xml(input.paths.workingDir)}</string>
|
|
1139
|
+
<key>RunAtLoad</key>
|
|
1140
|
+
<true/>
|
|
1141
|
+
<key>KeepAlive</key>
|
|
1142
|
+
<dict>
|
|
1143
|
+
<key>SuccessfulExit</key>
|
|
1144
|
+
<false/>
|
|
1145
|
+
</dict>
|
|
1146
|
+
<key>ThrottleInterval</key>
|
|
1147
|
+
<integer>10</integer>
|
|
1148
|
+
<key>ExitTimeOut</key>
|
|
1149
|
+
<integer>90</integer>
|
|
1150
|
+
<key>ProcessType</key>
|
|
1151
|
+
<string>Background</string>
|
|
1152
|
+
<key>StandardOutPath</key>
|
|
1153
|
+
<string>${xml(input.paths.logPath)}</string>
|
|
1154
|
+
<key>StandardErrorPath</key>
|
|
1155
|
+
<string>${xml(input.paths.logPath)}</string>
|
|
1156
|
+
</dict>
|
|
1157
|
+
</plist>
|
|
1158
|
+
`;
|
|
1159
|
+
}
|
|
1160
|
+
function unitFor(input) {
|
|
1161
|
+
return input.paths.manager === "systemd" ? systemdUnit(input) : launchdPlist(input);
|
|
1162
|
+
}
|
|
1163
|
+
function programInUnit(text, manager) {
|
|
1164
|
+
if (manager === "systemd") {
|
|
1165
|
+
const line = text.split("\n").find((l) => l.startsWith("ExecStart="));
|
|
1166
|
+
const quoted = [...(line ?? "").matchAll(/"((?:[^"\\]|\\.)*)"/g)].map(
|
|
1167
|
+
(match) => match[1].replace(/\\(.)/g, "$1").replace(/%%/g, "%")
|
|
1168
|
+
);
|
|
1169
|
+
return { node: quoted[0] ?? null, entry: quoted[1] ?? null };
|
|
1170
|
+
}
|
|
1171
|
+
const args = text.match(
|
|
1172
|
+
/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/
|
|
1173
|
+
);
|
|
1174
|
+
const values = [
|
|
1175
|
+
...(args?.[1] ?? "").matchAll(/<string>([^<]*)<\/string>/g)
|
|
1176
|
+
].map(
|
|
1177
|
+
(match) => match[1].replace(/"/g, '"').replace(/>/g, ">").replace(/</g, "<").replace(/&/g, "&")
|
|
1178
|
+
);
|
|
1179
|
+
return { node: values[0] ?? null, entry: values[1] ?? null };
|
|
1180
|
+
}
|
|
1181
|
+
var runCommand = (command, args) => {
|
|
1182
|
+
try {
|
|
1183
|
+
const stdout = execFileSync(command, args, {
|
|
1184
|
+
encoding: "utf8",
|
|
1185
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1186
|
+
timeout: 3e4
|
|
1187
|
+
});
|
|
1188
|
+
return { ok: true, stdout, stderr: "" };
|
|
1189
|
+
} catch (error) {
|
|
1190
|
+
const failed = error;
|
|
1191
|
+
return {
|
|
1192
|
+
ok: false,
|
|
1193
|
+
stdout: String(failed.stdout ?? ""),
|
|
1194
|
+
stderr: String(failed.stderr ?? failed.message ?? "")
|
|
1195
|
+
};
|
|
1196
|
+
}
|
|
1197
|
+
};
|
|
1198
|
+
function uid() {
|
|
1199
|
+
return process.getuid?.() ?? userInfo().uid;
|
|
1200
|
+
}
|
|
1201
|
+
function launchdTarget(ecid) {
|
|
1202
|
+
return `gui/${uid()}/${launchdLabel(ecid)}`;
|
|
1203
|
+
}
|
|
1204
|
+
function readJson(path) {
|
|
1205
|
+
try {
|
|
1206
|
+
return JSON.parse(readFileSync2(path, "utf8"));
|
|
1207
|
+
} catch {
|
|
1208
|
+
return null;
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
function writeJson(path, value) {
|
|
1212
|
+
mkdirSync2(dirname2(path), { recursive: true, mode: 448 });
|
|
1213
|
+
writeFileSync2(path, `${JSON.stringify(value, null, 2)}
|
|
1214
|
+
`, { mode: 384 });
|
|
1215
|
+
}
|
|
1216
|
+
function lingerCommand(user = userInfo().username) {
|
|
1217
|
+
return `sudo loginctl enable-linger ${user}`;
|
|
1218
|
+
}
|
|
1219
|
+
function managerState(input) {
|
|
1220
|
+
if (input.manager === "systemd") {
|
|
1221
|
+
const unit = `${serviceName(input.ecid)}.service`;
|
|
1222
|
+
const shown = input.run("systemctl", [
|
|
1223
|
+
"--user",
|
|
1224
|
+
"show",
|
|
1225
|
+
unit,
|
|
1226
|
+
"--property=ActiveState,UnitFileState,MainPID"
|
|
1227
|
+
]);
|
|
1228
|
+
const props = Object.fromEntries(
|
|
1229
|
+
shown.stdout.split("\n").filter(Boolean).map((line) => [
|
|
1230
|
+
line.slice(0, line.indexOf("=")),
|
|
1231
|
+
line.slice(line.indexOf("=") + 1)
|
|
1232
|
+
])
|
|
1233
|
+
);
|
|
1234
|
+
const pid2 = Number(props.MainPID);
|
|
1235
|
+
return {
|
|
1236
|
+
reachable: shown.ok,
|
|
1237
|
+
enabled: props.UnitFileState === "enabled",
|
|
1238
|
+
running: props.ActiveState === "active" || props.ActiveState === "activating",
|
|
1239
|
+
pid: Number.isInteger(pid2) && pid2 > 0 ? pid2 : null
|
|
1240
|
+
};
|
|
1241
|
+
}
|
|
1242
|
+
const printed = input.run("launchctl", ["print", launchdTarget(input.ecid)]);
|
|
1243
|
+
const disabled = input.run("launchctl", ["print-disabled", `gui/${uid()}`]);
|
|
1244
|
+
const pid = Number(printed.stdout.match(/\bpid = (\d+)/)?.[1]);
|
|
1245
|
+
return {
|
|
1246
|
+
reachable: true,
|
|
1247
|
+
enabled: printed.ok && !new RegExp(
|
|
1248
|
+
`"${launchdLabel(input.ecid).replace(/\./g, "\\.")}" => (true|disabled)`
|
|
1249
|
+
).test(disabled.stdout),
|
|
1250
|
+
running: /\bstate = running\b/.test(printed.stdout),
|
|
1251
|
+
pid: Number.isInteger(pid) && pid > 0 ? pid : null
|
|
1252
|
+
};
|
|
1253
|
+
}
|
|
1254
|
+
function serviceStatus(input) {
|
|
1255
|
+
const run = input.run ?? runCommand;
|
|
1256
|
+
const exists = input.fileExists ?? existsSync2;
|
|
1257
|
+
const readText2 = input.readText ?? ((path) => {
|
|
1258
|
+
try {
|
|
1259
|
+
return readFileSync2(path, "utf8");
|
|
1260
|
+
} catch {
|
|
1261
|
+
return null;
|
|
1262
|
+
}
|
|
1263
|
+
});
|
|
1264
|
+
const manager = serviceManagerFor(input.platform);
|
|
1265
|
+
const base = {
|
|
1266
|
+
supported: manager !== null,
|
|
1267
|
+
manager,
|
|
1268
|
+
ecid: input.ecid,
|
|
1269
|
+
installed: false,
|
|
1270
|
+
enabled: null,
|
|
1271
|
+
running: false,
|
|
1272
|
+
pid: null,
|
|
1273
|
+
runningVersion: null,
|
|
1274
|
+
cliVersion: input.cliVersion,
|
|
1275
|
+
unitPath: null,
|
|
1276
|
+
logPath: null,
|
|
1277
|
+
stopped: null,
|
|
1278
|
+
problems: []
|
|
1279
|
+
};
|
|
1280
|
+
if (!manager) {
|
|
1281
|
+
base.problems.push({
|
|
1282
|
+
code: "unsupported-platform",
|
|
1283
|
+
message: unsupportedPlatformMessage,
|
|
1284
|
+
fix: "kody daemon"
|
|
1285
|
+
});
|
|
1286
|
+
return base;
|
|
1287
|
+
}
|
|
1288
|
+
if (input.isRoot ?? uid() === 0) {
|
|
1289
|
+
base.problems.push({
|
|
1290
|
+
code: "running-as-root",
|
|
1291
|
+
message: "You are running kody as root. Install the service as the user whose account should run the code, not root.",
|
|
1292
|
+
fix: null
|
|
1293
|
+
});
|
|
1294
|
+
}
|
|
1295
|
+
if (!input.ecid) {
|
|
1296
|
+
base.problems.push({
|
|
1297
|
+
code: "context-missing",
|
|
1298
|
+
message: "This machine has no registered execution context.",
|
|
1299
|
+
fix: "kody connect --name <name>"
|
|
1300
|
+
});
|
|
1301
|
+
return base;
|
|
1302
|
+
}
|
|
1303
|
+
const paths = servicePaths({
|
|
1304
|
+
apiUrl: input.apiUrl,
|
|
1305
|
+
ecid: input.ecid,
|
|
1306
|
+
manager
|
|
1307
|
+
});
|
|
1308
|
+
base.unitPath = paths.unitPath;
|
|
1309
|
+
base.logPath = paths.logPath;
|
|
1310
|
+
base.stopped = readJson(paths.stoppedPath);
|
|
1311
|
+
const unitText = readText2(paths.unitPath);
|
|
1312
|
+
base.installed = unitText !== null;
|
|
1313
|
+
if (base.stopped) {
|
|
1314
|
+
base.problems.push({
|
|
1315
|
+
code: "context-stopped",
|
|
1316
|
+
message: `The daemon stopped for good: ${base.stopped.reason} (${base.stopped.at}). Kody will not accept this machine key again.`,
|
|
1317
|
+
fix: "kody daemon uninstall, then kody connect --name <name>"
|
|
1318
|
+
});
|
|
1319
|
+
}
|
|
1320
|
+
if (input.keyWrap === "passphrase") {
|
|
1321
|
+
base.problems.push({
|
|
1322
|
+
code: "key-needs-passphrase",
|
|
1323
|
+
message: "This context key is protected by a passphrase, which a background service cannot type. Switch it to a file key (600 permissions) for the service.",
|
|
1324
|
+
fix: "kody daemon install --key-storage file"
|
|
1325
|
+
});
|
|
1326
|
+
}
|
|
1327
|
+
if (!base.installed) {
|
|
1328
|
+
base.problems.push({
|
|
1329
|
+
code: "not-installed",
|
|
1330
|
+
message: "The background service is not installed, so the daemon stops with your terminal and does not start after a reboot.",
|
|
1331
|
+
fix: "kody daemon install"
|
|
1332
|
+
});
|
|
1333
|
+
return base;
|
|
1334
|
+
}
|
|
1335
|
+
const program2 = programInUnit(unitText, manager);
|
|
1336
|
+
const missing = [program2.node, program2.entry].filter(
|
|
1337
|
+
(path) => !path || !exists(path)
|
|
1338
|
+
);
|
|
1339
|
+
if (missing.length > 0) {
|
|
1340
|
+
base.problems.push({
|
|
1341
|
+
code: "program-missing",
|
|
1342
|
+
message: `The service starts a program that no longer exists (${missing.join(", ") || "unreadable unit"}), for example after a Node.js upgrade.`,
|
|
1343
|
+
fix: "kody daemon install"
|
|
1344
|
+
});
|
|
1345
|
+
}
|
|
1346
|
+
const ephemeral2 = program2.entry ? ephemeralRuntimeReason(program2.entry, input.tmpDir) : null;
|
|
1347
|
+
if (ephemeral2) {
|
|
1348
|
+
base.problems.push({
|
|
1349
|
+
code: "ephemeral-program",
|
|
1350
|
+
message: `The service starts kody from ${ephemeral2}, which does not survive.`,
|
|
1351
|
+
fix: "npm install -g @kodycodes/cli && kody daemon install"
|
|
1352
|
+
});
|
|
1353
|
+
}
|
|
1354
|
+
if (input.expectedUnit && input.expectedUnit !== unitText) {
|
|
1355
|
+
base.problems.push({
|
|
1356
|
+
code: "unit-outdated",
|
|
1357
|
+
message: `The service file differs from what this kody ${input.cliVersion} writes.`,
|
|
1358
|
+
fix: "kody daemon install"
|
|
1359
|
+
});
|
|
1360
|
+
}
|
|
1361
|
+
const state = managerState({ manager, ecid: input.ecid, run });
|
|
1362
|
+
if (manager === "systemd") {
|
|
1363
|
+
if (!state.reachable) {
|
|
1364
|
+
base.problems.push({
|
|
1365
|
+
code: "user-manager-unavailable",
|
|
1366
|
+
message: "systemctl --user is not reachable. The service needs a systemd user manager (log in once as this user, or enable lingering).",
|
|
1367
|
+
fix: lingerCommand()
|
|
1368
|
+
});
|
|
1369
|
+
}
|
|
1370
|
+
const linger = run("loginctl", [
|
|
1371
|
+
"show-user",
|
|
1372
|
+
userInfo().username,
|
|
1373
|
+
"--property=Linger",
|
|
1374
|
+
"--value"
|
|
1375
|
+
]);
|
|
1376
|
+
const value = linger.stdout.trim();
|
|
1377
|
+
if (value === "no") {
|
|
1378
|
+
base.problems.push({
|
|
1379
|
+
code: "linger-disabled",
|
|
1380
|
+
message: "Lingering is off: the daemon stops when you log out and does not start at boot until you log in. An administrator can turn it on (do not run kody itself with sudo).",
|
|
1381
|
+
fix: lingerCommand()
|
|
1382
|
+
});
|
|
1383
|
+
} else if (value !== "yes") {
|
|
1384
|
+
base.problems.push({
|
|
1385
|
+
code: "linger-unknown",
|
|
1386
|
+
message: "Could not read whether lingering is on (loginctl failed).",
|
|
1387
|
+
fix: `loginctl show-user ${userInfo().username} --property=Linger`
|
|
1388
|
+
});
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
base.enabled = state.enabled;
|
|
1392
|
+
base.running = state.running;
|
|
1393
|
+
base.pid = state.pid;
|
|
1394
|
+
if (!state.enabled && !base.stopped) {
|
|
1395
|
+
base.problems.push({
|
|
1396
|
+
code: "not-enabled",
|
|
1397
|
+
message: "The service is installed but not enabled, so it will not start at boot or login.",
|
|
1398
|
+
fix: "kody daemon install"
|
|
1399
|
+
});
|
|
1400
|
+
}
|
|
1401
|
+
if (!state.running && !base.stopped) {
|
|
1402
|
+
base.problems.push({
|
|
1403
|
+
code: "not-running",
|
|
1404
|
+
message: "The service is not running.",
|
|
1405
|
+
fix: "kody daemon restart (and kody daemon logs to see why it stopped)"
|
|
1406
|
+
});
|
|
1407
|
+
}
|
|
1408
|
+
const runtime = readJson(paths.statePath);
|
|
1409
|
+
if (state.running && runtime && (state.pid === null || runtime.pid === state.pid)) {
|
|
1410
|
+
base.runningVersion = runtime.version;
|
|
1411
|
+
if (runtime.version !== input.cliVersion) {
|
|
1412
|
+
base.problems.push({
|
|
1413
|
+
code: "restart-pending",
|
|
1414
|
+
message: `The service runs kody ${runtime.version}; this CLI is ${input.cliVersion}.`,
|
|
1415
|
+
fix: "kody daemon install"
|
|
1416
|
+
});
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
return base;
|
|
1420
|
+
}
|
|
1421
|
+
function formatServiceStatus(status, contextName) {
|
|
1422
|
+
const lines = [
|
|
1423
|
+
`Kody daemon service${contextName ? ` for ${contextName}` : ""}${status.ecid ? ` (${status.ecid})` : ""}`
|
|
1424
|
+
];
|
|
1425
|
+
if (status.supported) {
|
|
1426
|
+
lines.push(
|
|
1427
|
+
` Status: ${!status.installed ? "not installed" : status.running ? `running${status.pid ? ` (pid ${status.pid})` : ""}${status.runningVersion ? `, kody ${status.runningVersion}` : ""}` : status.stopped ? "stopped for good" : "not running"}`
|
|
1428
|
+
);
|
|
1429
|
+
if (status.installed) {
|
|
1430
|
+
lines.push(
|
|
1431
|
+
` Manager: ${status.manager}${status.enabled ? ", starts at boot/login" : ""}`
|
|
1432
|
+
);
|
|
1433
|
+
}
|
|
1434
|
+
if (status.unitPath && status.installed)
|
|
1435
|
+
lines.push(` Unit: ${status.unitPath}`);
|
|
1436
|
+
if (status.logPath && status.installed)
|
|
1437
|
+
lines.push(` Logs: ${status.logPath} (kody daemon logs)`);
|
|
1438
|
+
}
|
|
1439
|
+
if (status.problems.length === 0) lines.push(" No problems found.");
|
|
1440
|
+
for (const problem of status.problems) {
|
|
1441
|
+
lines.push(` [${problem.code}] ${problem.message}`);
|
|
1442
|
+
if (problem.fix) lines.push(` Fix: ${problem.fix}`);
|
|
1443
|
+
}
|
|
1444
|
+
return lines.join("\n");
|
|
1445
|
+
}
|
|
1446
|
+
function installService(input) {
|
|
1447
|
+
const run = input.run ?? runCommand;
|
|
1448
|
+
const warnings = [];
|
|
1449
|
+
let previous = null;
|
|
1450
|
+
try {
|
|
1451
|
+
previous = readFileSync2(input.paths.unitPath, "utf8");
|
|
1452
|
+
} catch {
|
|
1453
|
+
}
|
|
1454
|
+
const changed = previous !== input.unit;
|
|
1455
|
+
mkdirSync2(dirname2(input.paths.unitPath), { recursive: true });
|
|
1456
|
+
mkdirSync2(input.paths.workingDir, { recursive: true, mode: 448 });
|
|
1457
|
+
if (changed) writeFileSync2(input.paths.unitPath, input.unit, { mode: 420 });
|
|
1458
|
+
rmSync(input.paths.stoppedPath, { force: true });
|
|
1459
|
+
const must = (command, args, what) => {
|
|
1460
|
+
const result = run(command, args);
|
|
1461
|
+
if (!result.ok) {
|
|
1462
|
+
throw new Error(
|
|
1463
|
+
`Could not ${what}: ${command} ${args.join(" ")} failed. ${result.stderr.trim()}`
|
|
1464
|
+
);
|
|
1465
|
+
}
|
|
1466
|
+
return result;
|
|
1467
|
+
};
|
|
1468
|
+
if (input.paths.manager === "systemd") {
|
|
1469
|
+
const unit = `${serviceName(input.ecid)}.service`;
|
|
1470
|
+
must("systemctl", ["--user", "daemon-reload"], "reload systemd");
|
|
1471
|
+
must("systemctl", ["--user", "enable", unit], "enable the service");
|
|
1472
|
+
run("systemctl", ["--user", "reset-failed", unit]);
|
|
1473
|
+
const active = run("systemctl", ["--user", "is-active", unit]).stdout.trim() === "active";
|
|
1474
|
+
if (!active)
|
|
1475
|
+
must("systemctl", ["--user", "start", unit], "start the service");
|
|
1476
|
+
else if (changed || input.restart)
|
|
1477
|
+
must("systemctl", ["--user", "restart", unit], "restart the service");
|
|
1478
|
+
return {
|
|
1479
|
+
changed,
|
|
1480
|
+
restarted: active && (changed || input.restart),
|
|
1481
|
+
warnings
|
|
1482
|
+
};
|
|
1483
|
+
}
|
|
1484
|
+
const target = launchdTarget(input.ecid);
|
|
1485
|
+
const loaded = run("launchctl", ["print", target]).ok;
|
|
1486
|
+
run("launchctl", ["enable", target]);
|
|
1487
|
+
if (loaded && !changed) {
|
|
1488
|
+
if (input.restart)
|
|
1489
|
+
must("launchctl", ["kickstart", "-k", target], "restart the service");
|
|
1490
|
+
return { changed, restarted: input.restart, warnings };
|
|
1491
|
+
}
|
|
1492
|
+
if (loaded) run("launchctl", ["bootout", target]);
|
|
1493
|
+
const booted = run("launchctl", [
|
|
1494
|
+
"bootstrap",
|
|
1495
|
+
`gui/${uid()}`,
|
|
1496
|
+
input.paths.unitPath
|
|
1497
|
+
]);
|
|
1498
|
+
if (!booted.ok) {
|
|
1499
|
+
warnings.push(
|
|
1500
|
+
`launchctl bootstrap failed (${booted.stderr.trim()}). Over SSH with nobody logged in at the Mac, the service starts at the next login.`
|
|
1501
|
+
);
|
|
1502
|
+
}
|
|
1503
|
+
return { changed, restarted: loaded, warnings };
|
|
1504
|
+
}
|
|
1505
|
+
function restartService(input) {
|
|
1506
|
+
const run = input.run ?? runCommand;
|
|
1507
|
+
const result = input.manager === "systemd" ? (run("systemctl", [
|
|
1508
|
+
"--user",
|
|
1509
|
+
"reset-failed",
|
|
1510
|
+
`${serviceName(input.ecid)}.service`
|
|
1511
|
+
]), run("systemctl", [
|
|
1512
|
+
"--user",
|
|
1513
|
+
"restart",
|
|
1514
|
+
`${serviceName(input.ecid)}.service`
|
|
1515
|
+
])) : run("launchctl", ["kickstart", "-k", launchdTarget(input.ecid)]);
|
|
1516
|
+
if (!result.ok)
|
|
1517
|
+
throw new Error(`Could not restart the service: ${result.stderr.trim()}`);
|
|
1518
|
+
}
|
|
1519
|
+
function uninstallService(input) {
|
|
1520
|
+
const run = input.run ?? runCommand;
|
|
1521
|
+
if (input.paths.manager === "systemd") {
|
|
1522
|
+
const unit = `${serviceName(input.ecid)}.service`;
|
|
1523
|
+
run("systemctl", ["--user", "disable", "--now", unit]);
|
|
1524
|
+
rmSync(input.paths.unitPath, { force: true });
|
|
1525
|
+
run("systemctl", ["--user", "daemon-reload"]);
|
|
1526
|
+
run("systemctl", ["--user", "reset-failed", unit]);
|
|
1527
|
+
} else {
|
|
1528
|
+
run("launchctl", ["bootout", launchdTarget(input.ecid)]);
|
|
1529
|
+
rmSync(input.paths.unitPath, { force: true });
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
function disableOwnService(input) {
|
|
1533
|
+
const run = input.run ?? runCommand;
|
|
1534
|
+
if (input.manager === "systemd") {
|
|
1535
|
+
run("systemctl", [
|
|
1536
|
+
"--user",
|
|
1537
|
+
"disable",
|
|
1538
|
+
`${serviceName(input.ecid)}.service`
|
|
1539
|
+
]);
|
|
1540
|
+
} else {
|
|
1541
|
+
run("launchctl", ["disable", launchdTarget(input.ecid)]);
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
function rotateLog(path, maxBytes = 10 * 1024 * 1024) {
|
|
1545
|
+
try {
|
|
1546
|
+
const text = readFileSync2(path);
|
|
1547
|
+
if (text.byteLength <= maxBytes) return;
|
|
1548
|
+
writeFileSync2(`${path}.1`, text, { mode: 384 });
|
|
1549
|
+
writeFileSync2(path, "", { mode: 384 });
|
|
1550
|
+
} catch {
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
// src/execution-context/service-commands.ts
|
|
1555
|
+
function terminalConfirm() {
|
|
1556
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) return null;
|
|
1557
|
+
return async (question, defaultYes) => {
|
|
1558
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
1559
|
+
try {
|
|
1560
|
+
const answer = await new Promise(
|
|
1561
|
+
(resolve) => rl.question(
|
|
1562
|
+
`${question} ${defaultYes ? "[Y/n]" : "[y/N]"} `,
|
|
1563
|
+
(line) => resolve(line.trim().toLowerCase())
|
|
1564
|
+
)
|
|
1565
|
+
);
|
|
1566
|
+
if (!answer) return defaultYes;
|
|
1567
|
+
return answer === "y" || answer === "yes";
|
|
1568
|
+
} finally {
|
|
1569
|
+
rl.close();
|
|
1570
|
+
}
|
|
1571
|
+
};
|
|
1572
|
+
}
|
|
1573
|
+
function storedContextIds(apiUrl) {
|
|
1574
|
+
try {
|
|
1575
|
+
return readdirSync(contextsDir(apiUrl)).filter((entry) => entry.startsWith("ec_")).sort();
|
|
1576
|
+
} catch {
|
|
1577
|
+
return [];
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
function localContextId(apiUrl, ref) {
|
|
1581
|
+
const ids = storedContextIds(apiUrl);
|
|
1582
|
+
if (!ref) return ids[0] ?? null;
|
|
1583
|
+
if (ids.includes(ref)) return ref;
|
|
1584
|
+
return ids.find((id) => readStoredContext(apiUrl, id)?.name === ref) ?? null;
|
|
1585
|
+
}
|
|
1586
|
+
function program(env) {
|
|
1587
|
+
const current = currentProgram(env.clientVersion);
|
|
1588
|
+
return {
|
|
1589
|
+
...current,
|
|
1590
|
+
...env.entryPath ? { entry: env.entryPath } : {},
|
|
1591
|
+
...env.nodePath ? { node: env.nodePath } : {}
|
|
1592
|
+
};
|
|
1593
|
+
}
|
|
1594
|
+
function ephemeral(env) {
|
|
1595
|
+
return ephemeralRuntimeReason(
|
|
1596
|
+
program(env).entry,
|
|
1597
|
+
...env.tmpDir === void 0 ? [] : [env.tmpDir]
|
|
1598
|
+
);
|
|
1599
|
+
}
|
|
1600
|
+
function isRoot(env) {
|
|
1601
|
+
return env.isRoot ?? process.getuid?.() === 0;
|
|
1602
|
+
}
|
|
1603
|
+
function maxConcurrentInUnit(text) {
|
|
1604
|
+
const match = text?.match(
|
|
1605
|
+
/--max-concurrent(?:"?\s+"?|<\/string>\s*<string>)(\d+)/
|
|
1606
|
+
);
|
|
1607
|
+
return match ? Number(match[1]) : void 0;
|
|
1608
|
+
}
|
|
1609
|
+
function readText(path) {
|
|
1610
|
+
try {
|
|
1611
|
+
return readFileSync3(path, "utf8");
|
|
1612
|
+
} catch {
|
|
1613
|
+
return null;
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
function expectedUnit(env, ecid, manager, maxConcurrent) {
|
|
1617
|
+
const paths = servicePaths({ apiUrl: env.apiUrl, ecid, manager });
|
|
1618
|
+
const existing = readText(paths.unitPath);
|
|
1619
|
+
const context = readStoredContext(env.apiUrl, ecid);
|
|
1620
|
+
const concurrent = maxConcurrent ?? maxConcurrentInUnit(existing);
|
|
1621
|
+
return {
|
|
1622
|
+
paths,
|
|
1623
|
+
existing,
|
|
1624
|
+
unit: unitFor({
|
|
1625
|
+
ecid,
|
|
1626
|
+
contextName: context?.name ?? ecid,
|
|
1627
|
+
apiUrl: env.apiUrl,
|
|
1628
|
+
program: program(env),
|
|
1629
|
+
paths,
|
|
1630
|
+
...concurrent === void 0 ? {} : { maxConcurrent: concurrent },
|
|
1631
|
+
...env.platform ? { platform: env.platform } : {}
|
|
1632
|
+
})
|
|
1633
|
+
};
|
|
1634
|
+
}
|
|
1635
|
+
function runtimeState(path) {
|
|
1636
|
+
try {
|
|
1637
|
+
return JSON.parse(readFileSync3(path, "utf8"));
|
|
1638
|
+
} catch {
|
|
1639
|
+
return null;
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
async function ensureServiceKey(env, ecid, keyStorage) {
|
|
1643
|
+
const wrap = storedKeyWrap(env.apiUrl, ecid);
|
|
1644
|
+
if (wrap === "file") return;
|
|
1645
|
+
if (wrap === "passphrase" && keyStorage === "keyring") {
|
|
1646
|
+
throw new Error(
|
|
1647
|
+
"A passphrase-protected context cannot run as a service with --key-storage keyring. Re-run with --key-storage file."
|
|
1648
|
+
);
|
|
1649
|
+
}
|
|
1650
|
+
if (keyStorage !== void 0 && keyStorage !== "file" && keyStorage !== "keyring") {
|
|
1651
|
+
throw new Error("--key-storage must be keyring or file.");
|
|
1652
|
+
}
|
|
1653
|
+
let current;
|
|
1654
|
+
try {
|
|
1655
|
+
current = wrappingKeyForStoredContext({ apiUrl: env.apiUrl, ecid });
|
|
1656
|
+
loadContext({ apiUrl: env.apiUrl, ecid, wrapping: current });
|
|
1657
|
+
} catch (error) {
|
|
1658
|
+
throw new Error(
|
|
1659
|
+
`Could not unlock this machine's execution context key: ${error instanceof Error ? error.message : String(error)}`
|
|
1660
|
+
);
|
|
1661
|
+
}
|
|
1662
|
+
const linux = (env.platform ?? process.platform) === "linux";
|
|
1663
|
+
let toFile = keyStorage === "file";
|
|
1664
|
+
if (!toFile && keyStorage !== "keyring" && (wrap === "passphrase" || linux)) {
|
|
1665
|
+
const why = wrap === "passphrase" ? "This context key is protected by a passphrase, which a background service cannot type." : "On Linux the login keyring is usually locked until you log in, so after a reboot the service could not unlock its key.";
|
|
1666
|
+
const question = `${why}
|
|
1667
|
+
Store a separate file key instead (only readable by your user, 600 permissions, in the kody state directory)?`;
|
|
1668
|
+
toFile = env.yes ? wrap === "passphrase" : env.confirm ? await env.confirm(question, true) : wrap === "passphrase";
|
|
1669
|
+
if (!toFile && wrap === "passphrase") {
|
|
1670
|
+
throw new Error(
|
|
1671
|
+
`${why} Re-run with --key-storage file, or keep running \`kody daemon\` in a terminal.`
|
|
1672
|
+
);
|
|
1673
|
+
}
|
|
1674
|
+
if (!toFile) {
|
|
1675
|
+
env.write(
|
|
1676
|
+
"Keeping the OS keyring. If the service cannot unlock it after a reboot, run: kody daemon install --key-storage file\n"
|
|
1677
|
+
);
|
|
1678
|
+
}
|
|
1679
|
+
}
|
|
1680
|
+
if (!toFile) return;
|
|
1681
|
+
rewrapContextKey({
|
|
1682
|
+
apiUrl: env.apiUrl,
|
|
1683
|
+
ecid,
|
|
1684
|
+
from: current,
|
|
1685
|
+
to: fileWrappingKey({ apiUrl: env.apiUrl, ecid, create: true })
|
|
1686
|
+
});
|
|
1687
|
+
env.write(
|
|
1688
|
+
"Moved the context key to a file key (600 permissions) the service can read.\n"
|
|
1689
|
+
);
|
|
1690
|
+
}
|
|
1691
|
+
async function installDaemonService(env, input) {
|
|
1692
|
+
const manager = serviceManagerFor(env.platform);
|
|
1693
|
+
if (!manager) throw new Error(unsupportedPlatformMessage);
|
|
1694
|
+
if (isRoot(env)) {
|
|
1695
|
+
throw new Error(
|
|
1696
|
+
"Refusing to install the kody daemon service as root. Run `kody daemon install` as the user whose account should run the code, without sudo."
|
|
1697
|
+
);
|
|
1698
|
+
}
|
|
1699
|
+
const how = ephemeral(env);
|
|
1700
|
+
if (how) throw new Error(npxRefusal(how));
|
|
1701
|
+
if (!readStoredContext(env.apiUrl, input.ecid)) {
|
|
1702
|
+
throw new Error(
|
|
1703
|
+
`No execution context ${input.ecid} is registered on this machine. Run \`kody connect --name <name>\`.`
|
|
1704
|
+
);
|
|
1705
|
+
}
|
|
1706
|
+
await ensureServiceKey(env, input.ecid, input.keyStorage);
|
|
1707
|
+
const { paths, unit } = expectedUnit(
|
|
1708
|
+
env,
|
|
1709
|
+
input.ecid,
|
|
1710
|
+
manager,
|
|
1711
|
+
input.maxConcurrent
|
|
1712
|
+
);
|
|
1713
|
+
const before = runtimeState(paths.statePath);
|
|
1714
|
+
const result = installService({
|
|
1715
|
+
unit,
|
|
1716
|
+
paths,
|
|
1717
|
+
ecid: input.ecid,
|
|
1718
|
+
restart: before !== null && before.version !== env.clientVersion,
|
|
1719
|
+
...env.run ? { run: env.run } : {}
|
|
1720
|
+
});
|
|
1721
|
+
for (const warning of result.warnings) env.write(`${warning}
|
|
1722
|
+
`);
|
|
1723
|
+
const started = await waitForStart(env, paths.statePath, before);
|
|
1724
|
+
const status = serviceStatus({
|
|
1725
|
+
apiUrl: env.apiUrl,
|
|
1726
|
+
ecid: input.ecid,
|
|
1727
|
+
cliVersion: env.clientVersion,
|
|
1728
|
+
expectedUnit: unit,
|
|
1729
|
+
keyWrap: storedKeyWrap(env.apiUrl, input.ecid),
|
|
1730
|
+
...env.run ? { run: env.run } : {},
|
|
1731
|
+
...env.platform ? { platform: env.platform } : {},
|
|
1732
|
+
isRoot: false,
|
|
1733
|
+
...env.tmpDir === void 0 ? {} : { tmpDir: env.tmpDir }
|
|
1734
|
+
});
|
|
1735
|
+
const name = readStoredContext(env.apiUrl, input.ecid)?.name;
|
|
1736
|
+
env.write(
|
|
1737
|
+
`${result.changed ? "Installed" : "Checked"} the kody daemon service for ${name ?? input.ecid} (${manager}).${result.restarted ? " Restarted it onto this version." : ""}
|
|
1738
|
+
`
|
|
1739
|
+
);
|
|
1740
|
+
if (!started) {
|
|
1741
|
+
env.write(
|
|
1742
|
+
`The service has not reported in yet. Recent log lines (${paths.logPath}):
|
|
1743
|
+
${tail(paths.logPath, 15) || " (empty)"}
|
|
1744
|
+
`
|
|
1745
|
+
);
|
|
1746
|
+
}
|
|
1747
|
+
env.write(`${formatServiceStatus(status, name)}
|
|
1748
|
+
`);
|
|
1749
|
+
return { ...status, started, ok: started && status.running };
|
|
1750
|
+
}
|
|
1751
|
+
async function waitForStart(env, statePath, before) {
|
|
1752
|
+
const deadline = Date.now() + (env.startupWaitMs ?? 1e4);
|
|
1753
|
+
while (Date.now() < deadline) {
|
|
1754
|
+
const state = runtimeState(statePath);
|
|
1755
|
+
if (state && state.version === env.clientVersion && (!before || state.pid !== before.pid || state.startedAt !== before.startedAt)) {
|
|
1756
|
+
return true;
|
|
1757
|
+
}
|
|
1758
|
+
await sleep(250);
|
|
1759
|
+
}
|
|
1760
|
+
return env.startupWaitMs === 0;
|
|
1761
|
+
}
|
|
1762
|
+
function tail(path, lines) {
|
|
1763
|
+
const text = readText(path);
|
|
1764
|
+
if (!text) return "";
|
|
1765
|
+
return text.trimEnd().split("\n").slice(-lines).join("\n");
|
|
1766
|
+
}
|
|
1767
|
+
async function runDaemonServiceCommand(env, input) {
|
|
1768
|
+
const ecid = localContextId(env.apiUrl, input.context);
|
|
1769
|
+
const manager = serviceManagerFor(env.platform);
|
|
1770
|
+
if (input.sub === "status") {
|
|
1771
|
+
const status = serviceStatus({
|
|
1772
|
+
apiUrl: env.apiUrl,
|
|
1773
|
+
ecid,
|
|
1774
|
+
cliVersion: env.clientVersion,
|
|
1775
|
+
expectedUnit: ecid && manager && !ephemeral(env) ? expectedUnit(env, ecid, manager).unit : null,
|
|
1776
|
+
keyWrap: ecid ? storedKeyWrap(env.apiUrl, ecid) : null,
|
|
1777
|
+
...env.run ? { run: env.run } : {},
|
|
1778
|
+
...env.platform ? { platform: env.platform } : {},
|
|
1779
|
+
isRoot: isRoot(env),
|
|
1780
|
+
...env.tmpDir === void 0 ? {} : { tmpDir: env.tmpDir }
|
|
1781
|
+
});
|
|
1782
|
+
const name = ecid ? readStoredContext(env.apiUrl, ecid)?.name : void 0;
|
|
1783
|
+
env.write(
|
|
1784
|
+
env.json ? `${JSON.stringify({ ...status, contextName: name ?? null }, null, 2)}
|
|
1785
|
+
` : `${formatServiceStatus(status, name)}
|
|
1786
|
+
`
|
|
1787
|
+
);
|
|
1788
|
+
return status.problems.length === 0 ? 0 : 1;
|
|
1789
|
+
}
|
|
1790
|
+
if (!manager) throw new Error(unsupportedPlatformMessage);
|
|
1791
|
+
if (!ecid) {
|
|
1792
|
+
throw new Error(
|
|
1793
|
+
input.context ? `No execution context ${input.context} is registered on this machine.` : "This machine has no registered execution context. Run `kody connect --name <name>`."
|
|
1794
|
+
);
|
|
1795
|
+
}
|
|
1796
|
+
const paths = servicePaths({ apiUrl: env.apiUrl, ecid, manager });
|
|
1797
|
+
if (input.sub === "install") {
|
|
1798
|
+
const status = await installDaemonService(env, {
|
|
1799
|
+
ecid,
|
|
1800
|
+
...input.maxConcurrent === void 0 ? {} : { maxConcurrent: input.maxConcurrent },
|
|
1801
|
+
...input.keyStorage ? { keyStorage: input.keyStorage } : {}
|
|
1802
|
+
});
|
|
1803
|
+
return status.ok ? 0 : 1;
|
|
1804
|
+
}
|
|
1805
|
+
if (input.sub === "logs") {
|
|
1806
|
+
if (!existsSync3(paths.logPath)) {
|
|
1807
|
+
env.write(
|
|
1808
|
+
`No service log yet at ${paths.logPath}. Install the service with: kody daemon install
|
|
1809
|
+
`
|
|
1810
|
+
);
|
|
1811
|
+
return 1;
|
|
1812
|
+
}
|
|
1813
|
+
const lines = input.lines ? Number(input.lines) : 100;
|
|
1814
|
+
if (!Number.isInteger(lines) || lines < 1)
|
|
1815
|
+
throw new Error("--lines must be a positive whole number.");
|
|
1816
|
+
if (input.follow) {
|
|
1817
|
+
const child = spawn("tail", ["-n", String(lines), "-F", paths.logPath], {
|
|
1818
|
+
stdio: "inherit"
|
|
1819
|
+
});
|
|
1820
|
+
return await new Promise((resolve) => {
|
|
1821
|
+
const stop = () => child.kill("SIGTERM");
|
|
1822
|
+
process.once("SIGINT", stop);
|
|
1823
|
+
child.on("exit", () => resolve(0));
|
|
1824
|
+
});
|
|
1825
|
+
}
|
|
1826
|
+
env.write(`${tail(paths.logPath, lines)}
|
|
1827
|
+
`);
|
|
1828
|
+
return 0;
|
|
1829
|
+
}
|
|
1830
|
+
if (!existsSync3(paths.unitPath)) {
|
|
1831
|
+
throw new Error(
|
|
1832
|
+
"The kody daemon service is not installed. Install it with: kody daemon install"
|
|
1833
|
+
);
|
|
1834
|
+
}
|
|
1835
|
+
if (input.sub === "restart") {
|
|
1836
|
+
const before = runtimeState(paths.statePath);
|
|
1837
|
+
restartService({ manager, ecid, ...env.run ? { run: env.run } : {} });
|
|
1838
|
+
env.write(
|
|
1839
|
+
"Restarting the kody daemon service. Runs in flight finish first.\n"
|
|
1840
|
+
);
|
|
1841
|
+
if (await waitForStart(
|
|
1842
|
+
{ ...env, clientVersion: before?.version ?? env.clientVersion },
|
|
1843
|
+
paths.statePath,
|
|
1844
|
+
before
|
|
1845
|
+
)) {
|
|
1846
|
+
env.write("The service is back up.\n");
|
|
1847
|
+
}
|
|
1848
|
+
return 0;
|
|
1849
|
+
}
|
|
1850
|
+
if (input.sub === "uninstall") {
|
|
1851
|
+
uninstallService({ paths, ecid, ...env.run ? { run: env.run } : {} });
|
|
1852
|
+
env.write(
|
|
1853
|
+
`Removed the kody daemon service for ${ecid}. The context stays registered.
|
|
1854
|
+
`
|
|
1855
|
+
);
|
|
1856
|
+
const unregister = input.unregister ?? (env.confirm ? await env.confirm(
|
|
1857
|
+
`Also revoke ${ecid} in Kody so this machine can no longer run code?`,
|
|
1858
|
+
false
|
|
1859
|
+
) : false);
|
|
1860
|
+
if (unregister) {
|
|
1861
|
+
await input.revoke(ecid);
|
|
1862
|
+
env.write(
|
|
1863
|
+
`Revoked ${ecid}. Delete it for good with: kody context delete ${ecid}
|
|
1864
|
+
`
|
|
1865
|
+
);
|
|
1866
|
+
} else {
|
|
1867
|
+
env.write(
|
|
1868
|
+
`To stop Kody from routing runs here, revoke it with: kody context revoke ${ecid}
|
|
1869
|
+
`
|
|
1870
|
+
);
|
|
1871
|
+
}
|
|
1872
|
+
return 0;
|
|
1873
|
+
}
|
|
1874
|
+
throw new Error(
|
|
1875
|
+
"Usage: kody daemon [install | status [--json] | logs [--lines <n>] [--follow] | restart | uninstall [--unregister]]"
|
|
1876
|
+
);
|
|
1877
|
+
}
|
|
1878
|
+
async function offerInstall(env, input) {
|
|
1879
|
+
const manager = serviceManagerFor(env.platform);
|
|
1880
|
+
if (input.install === false) return false;
|
|
1881
|
+
if (!manager || ephemeral(env) || isRoot(env)) {
|
|
1882
|
+
if (input.install) {
|
|
1883
|
+
if (!manager) throw new Error(unsupportedPlatformMessage);
|
|
1884
|
+
const how = ephemeral(env);
|
|
1885
|
+
if (how) throw new Error(npxRefusal(how));
|
|
1886
|
+
throw new Error("Refusing to install the kody daemon service as root.");
|
|
1887
|
+
}
|
|
1888
|
+
if (!manager) env.write(`${unsupportedPlatformMessage}
|
|
1889
|
+
`);
|
|
1890
|
+
else if (!isRoot(env)) {
|
|
1891
|
+
env.write(
|
|
1892
|
+
"To keep it running after reboots, install the CLI globally (npm install -g @kodycodes/cli) and run: kody daemon install\n"
|
|
1893
|
+
);
|
|
1894
|
+
}
|
|
1895
|
+
return false;
|
|
1896
|
+
}
|
|
1897
|
+
const yes = input.install ?? (env.yes ? true : env.confirm ? await env.confirm(
|
|
1898
|
+
"Run it as a background service that starts at boot and restarts after crashes?",
|
|
1899
|
+
true
|
|
1900
|
+
) : false);
|
|
1901
|
+
if (!yes) {
|
|
1902
|
+
env.write(
|
|
1903
|
+
"Start it with: kody daemon (or keep it running with: kody daemon install)\n"
|
|
1904
|
+
);
|
|
1905
|
+
return false;
|
|
1906
|
+
}
|
|
1907
|
+
const status = await installDaemonService(env, {
|
|
1908
|
+
ecid: input.ecid,
|
|
1909
|
+
...input.keyStorage ? { keyStorage: input.keyStorage } : {},
|
|
1910
|
+
...input.maxConcurrent === void 0 ? {} : { maxConcurrent: input.maxConcurrent }
|
|
1911
|
+
});
|
|
1912
|
+
return status.ok;
|
|
1913
|
+
}
|
|
1914
|
+
async function offerUninstallAfterRevoke(env, input) {
|
|
1915
|
+
const manager = serviceManagerFor(env.platform);
|
|
1916
|
+
if (!manager) return;
|
|
1917
|
+
const ecid = input.ecid ?? localContextId(env.apiUrl, input.ref);
|
|
1918
|
+
if (!ecid) return;
|
|
1919
|
+
const paths = servicePaths({ apiUrl: env.apiUrl, ecid, manager });
|
|
1920
|
+
if (!existsSync3(paths.unitPath)) return;
|
|
1921
|
+
const yes = env.yes ? true : env.confirm ? await env.confirm(
|
|
1922
|
+
"This machine runs it as a background service. Remove the service?",
|
|
1923
|
+
true
|
|
1924
|
+
) : true;
|
|
1925
|
+
if (!yes) {
|
|
1926
|
+
env.write(
|
|
1927
|
+
"The service will stop on its own and stay stopped. Remove it later with: kody daemon uninstall\n"
|
|
1928
|
+
);
|
|
1929
|
+
return;
|
|
1930
|
+
}
|
|
1931
|
+
uninstallService({ paths, ecid, ...env.run ? { run: env.run } : {} });
|
|
1932
|
+
env.write(`Removed the kody daemon service for ${ecid}.
|
|
1933
|
+
`);
|
|
1934
|
+
}
|
|
1935
|
+
async function runUpdate(env) {
|
|
1936
|
+
const how = ephemeral(env);
|
|
1937
|
+
if (how) {
|
|
1938
|
+
env.write(
|
|
1939
|
+
`This kody runs from ${how}, which always fetches the latest version. For a background service, install it globally:
|
|
1940
|
+
npm install -g @kodycodes/cli
|
|
1941
|
+
`
|
|
1942
|
+
);
|
|
1943
|
+
return 0;
|
|
1944
|
+
}
|
|
1945
|
+
env.write("Installing the latest @kodycodes/cli globally...\n");
|
|
1946
|
+
const npm = process.platform === "win32" ? "npm.cmd" : "npm";
|
|
1947
|
+
const installed = spawnSync(npm, ["install", "-g", "@kodycodes/cli@latest"], {
|
|
1948
|
+
stdio: "inherit",
|
|
1949
|
+
shell: process.platform === "win32"
|
|
1950
|
+
});
|
|
1951
|
+
if (installed.status !== 0) {
|
|
1952
|
+
throw new Error(
|
|
1953
|
+
`npm install -g @kodycodes/cli@latest failed${installed.error ? ` (${installed.error.message})` : ""}. Fix the npm error above and run \`kody update\` again.`
|
|
1954
|
+
);
|
|
1955
|
+
}
|
|
1956
|
+
const manager = serviceManagerFor(env.platform);
|
|
1957
|
+
const services = manager ? storedContextIds(env.apiUrl).filter(
|
|
1958
|
+
(ecid) => existsSync3(
|
|
1959
|
+
servicePaths({ apiUrl: env.apiUrl, ecid, manager }).unitPath
|
|
1960
|
+
)
|
|
1961
|
+
) : [];
|
|
1962
|
+
let restarted = 0;
|
|
1963
|
+
for (const ecid of services) {
|
|
1964
|
+
const repaired = spawnSync(
|
|
1965
|
+
process.execPath,
|
|
1966
|
+
[
|
|
1967
|
+
program(env).entry,
|
|
1968
|
+
"daemon",
|
|
1969
|
+
"install",
|
|
1970
|
+
"--context",
|
|
1971
|
+
ecid,
|
|
1972
|
+
"--api-url",
|
|
1973
|
+
env.apiUrl,
|
|
1974
|
+
"--yes"
|
|
1975
|
+
],
|
|
1976
|
+
{ stdio: "inherit" }
|
|
1977
|
+
);
|
|
1978
|
+
if (repaired.status === 0) restarted++;
|
|
1979
|
+
else
|
|
1980
|
+
env.write(
|
|
1981
|
+
`Could not restart the service for ${ecid}. Check it with: kody daemon status --context ${ecid}
|
|
1982
|
+
`
|
|
1983
|
+
);
|
|
1984
|
+
}
|
|
1985
|
+
const version = spawnSync(process.execPath, [program(env).entry, "version"], {
|
|
1986
|
+
encoding: "utf8"
|
|
1987
|
+
}).stdout.trim();
|
|
1988
|
+
env.write(
|
|
1989
|
+
`kody is now ${version || "up to date"}.${restarted === 0 ? "" : ` Restarted ${restarted} service(s) onto it.`}
|
|
1990
|
+
`
|
|
1991
|
+
);
|
|
1992
|
+
return restarted === services.length ? 0 : 1;
|
|
1993
|
+
}
|
|
1994
|
+
|
|
1995
|
+
// src/execution-context/commands.ts
|
|
1996
|
+
var defaultMaxConcurrentRuns = 2;
|
|
1997
|
+
function maxConcurrentRuns(value = process.env.KODY_CONTEXT_MAX_CONCURRENT) {
|
|
1998
|
+
if (value === void 0 || value === "") return defaultMaxConcurrentRuns;
|
|
1999
|
+
const parsed = Number(value);
|
|
2000
|
+
if (!Number.isInteger(parsed) || parsed < 1 || parsed > ecpMaxConcurrentRunsCap) {
|
|
2001
|
+
throw new Error(
|
|
2002
|
+
`--max-concurrent (or KODY_CONTEXT_MAX_CONCURRENT) must be a whole number from 1 to ${ecpMaxConcurrentRunsCap}; got ${value}.`
|
|
2003
|
+
);
|
|
2004
|
+
}
|
|
2005
|
+
return parsed;
|
|
2006
|
+
}
|
|
2007
|
+
function localCapabilities(maxConcurrent = defaultMaxConcurrentRuns) {
|
|
2008
|
+
return {
|
|
2009
|
+
runtime: "workerd",
|
|
2010
|
+
node: process.versions.node,
|
|
2011
|
+
os: platform(),
|
|
2012
|
+
cpuCount: cpus().length,
|
|
2013
|
+
memoryMb: Math.round(totalmem() / (1024 * 1024)),
|
|
2014
|
+
maxConcurrent,
|
|
2015
|
+
features: []
|
|
2016
|
+
};
|
|
2017
|
+
}
|
|
2018
|
+
function out(input, value, text) {
|
|
2019
|
+
input.write(
|
|
2020
|
+
input.values.json ? `${JSON.stringify(value, null, 2)}
|
|
2021
|
+
` : `${text}
|
|
2022
|
+
`
|
|
2023
|
+
);
|
|
2024
|
+
}
|
|
2025
|
+
async function runExecutionContextCommand(input) {
|
|
2026
|
+
try {
|
|
2027
|
+
return await runCommand2(input);
|
|
2028
|
+
} catch (error) {
|
|
2029
|
+
if (isExperimentOffError(error)) throw experimentOffError(input.apiUrl);
|
|
2030
|
+
throw error;
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
async function runCommand2(input) {
|
|
2034
|
+
const [sub, ...rest] = input.positionals;
|
|
2035
|
+
const base = {
|
|
2036
|
+
apiUrl: input.apiUrl,
|
|
2037
|
+
...input.org ? { org: input.org } : {},
|
|
2038
|
+
...input.fetchFn ? { fetchFn: input.fetchFn } : {}
|
|
2039
|
+
};
|
|
2040
|
+
if (input.command === "context" && sub === "policy") {
|
|
2041
|
+
return await runPolicyCommand(input, rest);
|
|
2042
|
+
}
|
|
2043
|
+
const serviceEnv = {
|
|
2044
|
+
apiUrl: input.apiUrl,
|
|
2045
|
+
clientVersion: input.clientVersion,
|
|
2046
|
+
write: input.write,
|
|
2047
|
+
...input.values.json ? { json: true } : {},
|
|
2048
|
+
...input.values.yes ? { yes: true } : {},
|
|
2049
|
+
confirm: input.values.json ? null : terminalConfirm(),
|
|
2050
|
+
...input.service
|
|
2051
|
+
};
|
|
2052
|
+
const maxConcurrentFlag = () => {
|
|
2053
|
+
if (input.values.maxConcurrent === "") {
|
|
2054
|
+
throw new Error("--max-concurrent needs a value.");
|
|
2055
|
+
}
|
|
2056
|
+
return input.values.maxConcurrent === void 0 ? void 0 : maxConcurrentRuns(input.values.maxConcurrent);
|
|
2057
|
+
};
|
|
2058
|
+
if (input.command === "update") return await runUpdate(serviceEnv);
|
|
2059
|
+
if (input.command === "daemon" && sub !== void 0) {
|
|
2060
|
+
const maxConcurrent = maxConcurrentFlag();
|
|
2061
|
+
return await runDaemonServiceCommand(serviceEnv, {
|
|
2062
|
+
sub,
|
|
2063
|
+
...input.values.context ? { context: input.values.context } : {},
|
|
2064
|
+
...maxConcurrent === void 0 ? {} : { maxConcurrent },
|
|
2065
|
+
...input.values.keyStorage ? { keyStorage: input.values.keyStorage } : {},
|
|
2066
|
+
...input.values.lines ? { lines: input.values.lines } : {},
|
|
2067
|
+
...input.values.follow ? { follow: true } : {},
|
|
2068
|
+
...input.values.unregister === void 0 ? {} : { unregister: input.values.unregister },
|
|
2069
|
+
revoke: async (ecid) => {
|
|
2070
|
+
await apiJson({
|
|
2071
|
+
...base,
|
|
2072
|
+
token: await input.token(),
|
|
2073
|
+
method: "DELETE",
|
|
2074
|
+
path: `/v1/execution-contexts/${encodeURIComponent(ecid)}`
|
|
2075
|
+
});
|
|
2076
|
+
}
|
|
2077
|
+
});
|
|
2078
|
+
}
|
|
2079
|
+
if (input.command === "connect" && !input.values.name && !sub && localContextId(input.apiUrl, input.values.context)) {
|
|
2080
|
+
const ecid = localContextId(input.apiUrl, input.values.context);
|
|
2081
|
+
input.write(`This machine is already registered as ${ecid}.
|
|
2082
|
+
`);
|
|
2083
|
+
const maxConcurrent = maxConcurrentFlag();
|
|
2084
|
+
await offerInstall(serviceEnv, {
|
|
2085
|
+
ecid,
|
|
2086
|
+
install: input.values.install ?? true,
|
|
2087
|
+
...input.values.keyStorage ? { keyStorage: input.values.keyStorage } : {},
|
|
2088
|
+
...maxConcurrent === void 0 ? {} : { maxConcurrent }
|
|
2089
|
+
});
|
|
2090
|
+
return 0;
|
|
2091
|
+
}
|
|
2092
|
+
if (input.command === "context" && sub === "register" || input.command === "connect") {
|
|
2093
|
+
const connect = input.command === "connect";
|
|
2094
|
+
const name = input.values.name ?? (connect ? sub : rest[0]);
|
|
2095
|
+
if (!name) throw new Error("Pass --name <name> for this machine.");
|
|
2096
|
+
const maxConcurrent = maxConcurrentFlag();
|
|
2097
|
+
if (input.values.keyStorage !== void 0 && input.values.keyStorage !== "file" && input.values.keyStorage !== "keyring") {
|
|
2098
|
+
throw new Error("--key-storage must be keyring or file.");
|
|
2099
|
+
}
|
|
2100
|
+
const wrappingFor = async (ecid) => {
|
|
2101
|
+
if (input.values.keyStorage === "file") {
|
|
2102
|
+
return fileWrappingKey({ apiUrl: input.apiUrl, ecid, create: true });
|
|
2103
|
+
}
|
|
2104
|
+
try {
|
|
2105
|
+
const source = resolveWrappingKey({ ecid, create: true });
|
|
2106
|
+
if (source.kind === "keyring") source.key(Buffer.alloc(16));
|
|
2107
|
+
return source;
|
|
2108
|
+
} catch (error) {
|
|
2109
|
+
if (input.values.keyStorage === "keyring") throw error;
|
|
2110
|
+
const question = `No unlocked OS keyring is available (${error instanceof Error ? error.message : String(error)}).
|
|
2111
|
+
Store the machine key wrapping key in a file instead (only readable by your user, 600 permissions, in the kody state directory)?`;
|
|
2112
|
+
const useFile = serviceEnv.yes ? true : serviceEnv.confirm ? await serviceEnv.confirm(question, true) : false;
|
|
2113
|
+
if (!useFile) {
|
|
2114
|
+
throw new Error(
|
|
2115
|
+
`${error instanceof Error ? error.message : String(error)} Or re-run with --key-storage file.`
|
|
2116
|
+
);
|
|
2117
|
+
}
|
|
2118
|
+
return fileWrappingKey({ apiUrl: input.apiUrl, ecid, create: true });
|
|
2119
|
+
}
|
|
2120
|
+
};
|
|
2121
|
+
const { publicKeyJwk, privateKeyJwk } = await generateContextKey();
|
|
2122
|
+
const privateKey = await importContextKey(privateKeyJwk);
|
|
2123
|
+
const thumbprint = await ed25519JwkThumbprint(publicKeyJwk);
|
|
2124
|
+
const registered = await registerContext({
|
|
2125
|
+
...base,
|
|
2126
|
+
token: await input.token(),
|
|
2127
|
+
name,
|
|
2128
|
+
publicKeyJwk,
|
|
2129
|
+
privateKey,
|
|
2130
|
+
thumbprint,
|
|
2131
|
+
capabilities: localCapabilities(),
|
|
2132
|
+
client: { name: "kody-cli", version: input.clientVersion }
|
|
2133
|
+
});
|
|
2134
|
+
let wrapping;
|
|
2135
|
+
try {
|
|
2136
|
+
wrapping = await wrappingFor(registered.ecid);
|
|
2137
|
+
} catch (error) {
|
|
2138
|
+
const path = `/v1/execution-contexts/${encodeURIComponent(registered.ecid)}`;
|
|
2139
|
+
const token = await input.token();
|
|
2140
|
+
await apiJson({ ...base, token, method: "DELETE", path }).then(
|
|
2141
|
+
() => apiJson({ ...base, token, method: "POST", path: `${path}/delete` })
|
|
2142
|
+
).catch(() => {
|
|
2143
|
+
});
|
|
2144
|
+
throw error;
|
|
2145
|
+
}
|
|
2146
|
+
saveContext({
|
|
2147
|
+
context: {
|
|
2148
|
+
version: 1,
|
|
2149
|
+
ecid: registered.ecid,
|
|
2150
|
+
name: registered.name,
|
|
2151
|
+
apiUrl: input.apiUrl,
|
|
2152
|
+
orgSlug: registered.owner.orgSlug,
|
|
2153
|
+
publicKeyJwk
|
|
2154
|
+
},
|
|
2155
|
+
privateJwk: privateKeyJwk,
|
|
2156
|
+
wrapping
|
|
2157
|
+
});
|
|
2158
|
+
const steps = (registered.nextSteps ?? []).map(
|
|
2159
|
+
(step) => ` ${step.text ?? ""}${step.cli ? `
|
|
2160
|
+
${step.cli}` : ""}`
|
|
2161
|
+
).join("\n");
|
|
2162
|
+
out(
|
|
2163
|
+
input,
|
|
2164
|
+
registered,
|
|
2165
|
+
[
|
|
2166
|
+
registered.notice ?? `Registered ${registered.name} (${registered.ecid}).`,
|
|
2167
|
+
steps ? `Next steps:
|
|
2168
|
+
${steps}` : ""
|
|
2169
|
+
].filter(Boolean).join("\n")
|
|
2170
|
+
);
|
|
2171
|
+
if (input.values.json && input.values.install === void 0) return 0;
|
|
2172
|
+
const install = {
|
|
2173
|
+
ecid: registered.ecid,
|
|
2174
|
+
...input.values.install !== void 0 ? { install: input.values.install } : connect && !serviceEnv.confirm ? { install: true } : {},
|
|
2175
|
+
...maxConcurrent === void 0 ? {} : { maxConcurrent }
|
|
2176
|
+
};
|
|
2177
|
+
if (input.values.install === true) {
|
|
2178
|
+
const installEnv = input.values.json ? {
|
|
2179
|
+
...serviceEnv,
|
|
2180
|
+
write: (text) => {
|
|
2181
|
+
process.stderr.write(text);
|
|
2182
|
+
}
|
|
2183
|
+
} : serviceEnv;
|
|
2184
|
+
return await offerInstall(installEnv, install) ? 0 : 1;
|
|
2185
|
+
}
|
|
2186
|
+
try {
|
|
2187
|
+
await offerInstall(serviceEnv, install);
|
|
2188
|
+
} catch (error) {
|
|
2189
|
+
input.write(
|
|
2190
|
+
`Registered, but the background service was not installed: ${error instanceof Error ? error.message : String(error)}
|
|
2191
|
+
Run \`kody daemon\` in a terminal, or fix that and run: kody daemon install --context ${registered.ecid}
|
|
2192
|
+
`
|
|
2193
|
+
);
|
|
2194
|
+
}
|
|
2195
|
+
return 0;
|
|
2196
|
+
}
|
|
2197
|
+
if (input.command === "context" && (sub === "list" || sub === void 0)) {
|
|
2198
|
+
const body = await apiJson({
|
|
2199
|
+
...base,
|
|
2200
|
+
token: await input.token(),
|
|
2201
|
+
method: "GET",
|
|
2202
|
+
path: "/v1/execution-contexts"
|
|
2203
|
+
});
|
|
2204
|
+
const contexts = body.contexts ?? [];
|
|
2205
|
+
out(
|
|
2206
|
+
input,
|
|
2207
|
+
body,
|
|
2208
|
+
contexts.length === 0 ? "No execution contexts yet. Register this machine with `kody context register --name <name>`." : contexts.map(
|
|
2209
|
+
(c) => `${c.name} (${c.id}) ${c.status}${c.usable ? "" : `, not usable: ${c.unusableReason}`}`
|
|
2210
|
+
).join("\n")
|
|
2211
|
+
);
|
|
2212
|
+
return 0;
|
|
2213
|
+
}
|
|
2214
|
+
if (input.command === "context" && (sub === "revoke" || sub === "delete")) {
|
|
2215
|
+
const ref = rest[0];
|
|
2216
|
+
if (!ref) throw new Error(`Usage: kody context ${sub} <name|ec id>`);
|
|
2217
|
+
const id = encodeURIComponent(ref);
|
|
2218
|
+
const body = await apiJson({
|
|
2219
|
+
...base,
|
|
2220
|
+
token: await input.token(),
|
|
2221
|
+
...sub === "revoke" ? { method: "DELETE", path: `/v1/execution-contexts/${id}` } : { method: "POST", path: `/v1/execution-contexts/${id}/delete` }
|
|
2222
|
+
});
|
|
2223
|
+
out(
|
|
2224
|
+
input,
|
|
2225
|
+
body,
|
|
2226
|
+
sub === "revoke" ? `Revoked ${ref}. Delete it for good with: kody context delete ${ref}` : `Deleted ${ref}.`
|
|
2227
|
+
);
|
|
2228
|
+
const revokedId = typeof body.id === "string" ? body.id : typeof body.context?.id === "string" ? body.context.id : null;
|
|
2229
|
+
await offerUninstallAfterRevoke(
|
|
2230
|
+
input.values.json ? { ...serviceEnv, write: () => {
|
|
2231
|
+
} } : serviceEnv,
|
|
2232
|
+
{
|
|
2233
|
+
ref,
|
|
2234
|
+
ecid: revokedId && localContextId(input.apiUrl, revokedId) ? revokedId : null
|
|
2235
|
+
}
|
|
2236
|
+
);
|
|
2237
|
+
return 0;
|
|
2238
|
+
}
|
|
2239
|
+
if (input.command === "chain") {
|
|
2240
|
+
const token = await input.token();
|
|
2241
|
+
const read = await apiJson({
|
|
2242
|
+
...base,
|
|
2243
|
+
token,
|
|
2244
|
+
method: "GET",
|
|
2245
|
+
path: "/v1/execution-chain"
|
|
2246
|
+
});
|
|
2247
|
+
const current = chainOf(read);
|
|
2248
|
+
const contexts = async () => contextsById(
|
|
2249
|
+
await apiJson({
|
|
2250
|
+
...base,
|
|
2251
|
+
token,
|
|
2252
|
+
method: "GET",
|
|
2253
|
+
path: "/v1/execution-contexts"
|
|
2254
|
+
})
|
|
2255
|
+
);
|
|
2256
|
+
const contextMetadata = async () => {
|
|
2257
|
+
if (input.values.json) return /* @__PURE__ */ new Map();
|
|
2258
|
+
try {
|
|
2259
|
+
return await contexts();
|
|
2260
|
+
} catch {
|
|
2261
|
+
return /* @__PURE__ */ new Map();
|
|
2262
|
+
}
|
|
2263
|
+
};
|
|
2264
|
+
if (sub === "show" || sub === void 0) {
|
|
2265
|
+
out(input, read, describeChain(current, await contextMetadata()));
|
|
2266
|
+
return 0;
|
|
2267
|
+
}
|
|
2268
|
+
if (sub !== "add" && sub !== "remove") {
|
|
2269
|
+
throw new Error("Usage: kody chain show | add <name> | remove <name>");
|
|
2270
|
+
}
|
|
2271
|
+
const ref = rest[0];
|
|
2272
|
+
if (!ref) throw new Error(`Pass the context name: kody chain ${sub} <name>`);
|
|
2273
|
+
const id = await resolveContextId({
|
|
2274
|
+
...base,
|
|
2275
|
+
token,
|
|
2276
|
+
ref
|
|
2277
|
+
});
|
|
2278
|
+
const entries = (current.entries ?? []).map(
|
|
2279
|
+
(entry) => entry.kind === "cloud" ? { kind: "cloud" } : { kind: "context", id: entry.id }
|
|
2280
|
+
).filter((entry) => !(entry.kind === "context" && entry.id === id));
|
|
2281
|
+
if (sub === "add") {
|
|
2282
|
+
if (entries.length === 0) entries.push({ kind: "cloud" });
|
|
2283
|
+
const cloudAt = entries.findIndex((entry) => entry.kind === "cloud");
|
|
2284
|
+
entries.splice(cloudAt === -1 ? entries.length : cloudAt, 0, {
|
|
2285
|
+
kind: "context",
|
|
2286
|
+
id
|
|
2287
|
+
});
|
|
2288
|
+
}
|
|
2289
|
+
const updated = await apiJson({
|
|
2290
|
+
...base,
|
|
2291
|
+
token,
|
|
2292
|
+
method: "PUT",
|
|
2293
|
+
path: "/v1/execution-chain",
|
|
2294
|
+
body: {
|
|
2295
|
+
entries,
|
|
2296
|
+
strict: !entries.some((entry) => entry.kind === "cloud"),
|
|
2297
|
+
ifMatch: current.updatedAt ?? null
|
|
2298
|
+
}
|
|
2299
|
+
});
|
|
2300
|
+
out(
|
|
2301
|
+
input,
|
|
2302
|
+
updated,
|
|
2303
|
+
describeChain(chainOf(updated), await contextMetadata())
|
|
2304
|
+
);
|
|
2305
|
+
return 0;
|
|
2306
|
+
}
|
|
2307
|
+
if (input.command === "daemon") {
|
|
2308
|
+
if (input.values.maxConcurrent === "") {
|
|
2309
|
+
throw new Error("--max-concurrent needs a value.");
|
|
2310
|
+
}
|
|
2311
|
+
const maxConcurrent = maxConcurrentRuns(input.values.maxConcurrent);
|
|
2312
|
+
const ecid = input.values.context ? localContextId(input.apiUrl, input.values.context) ?? input.values.context : storedContextIds(input.apiUrl)[0];
|
|
2313
|
+
if (!ecid) {
|
|
2314
|
+
throw new Error(
|
|
2315
|
+
"This machine has no registered execution context. Run `kody connect --name <name>` first."
|
|
2316
|
+
);
|
|
2317
|
+
}
|
|
2318
|
+
const asService = process.env[serviceEnvVar];
|
|
2319
|
+
const manager = asService === "systemd" || asService === "launchd" ? asService : null;
|
|
2320
|
+
const paths = manager ? servicePaths({ apiUrl: input.apiUrl, ecid, manager }) : null;
|
|
2321
|
+
if (paths) rotateLog(paths.logPath);
|
|
2322
|
+
const { context, privateJwk } = loadContext({
|
|
2323
|
+
apiUrl: input.apiUrl,
|
|
2324
|
+
ecid,
|
|
2325
|
+
wrapping: wrappingKeyForStoredContext({ apiUrl: input.apiUrl, ecid })
|
|
2326
|
+
});
|
|
2327
|
+
const privateKey = await importContextKey(privateJwk);
|
|
2328
|
+
const serverKeys = await fetchServerKeys({ apiUrl: input.apiUrl });
|
|
2329
|
+
const { runContextRun } = await import("./run-executor-7CL5RXNG.js");
|
|
2330
|
+
const abort = new AbortController();
|
|
2331
|
+
const drain = new AbortController();
|
|
2332
|
+
let hardStop;
|
|
2333
|
+
const onSignal = () => {
|
|
2334
|
+
if (drain.signal.aborted) return abort.abort();
|
|
2335
|
+
drain.abort();
|
|
2336
|
+
hardStop = setTimeout(() => abort.abort(), 8e4);
|
|
2337
|
+
hardStop.unref();
|
|
2338
|
+
};
|
|
2339
|
+
process.on("SIGINT", onSignal);
|
|
2340
|
+
process.on("SIGTERM", onSignal);
|
|
2341
|
+
input.write(
|
|
2342
|
+
`Starting ${context.name} (${context.ecid}) against ${input.apiUrl}${manager ? ` as a ${manager} service` : ""}.
|
|
2343
|
+
`
|
|
2344
|
+
);
|
|
2345
|
+
if (!manager && serviceManagerFor()) {
|
|
2346
|
+
input.write(
|
|
2347
|
+
"Tip: keep it running after reboots and crashes with: kody daemon install\n"
|
|
2348
|
+
);
|
|
2349
|
+
}
|
|
2350
|
+
const statePath = servicePaths({
|
|
2351
|
+
apiUrl: input.apiUrl,
|
|
2352
|
+
ecid,
|
|
2353
|
+
manager: serviceManagerFor() ?? "systemd"
|
|
2354
|
+
}).statePath;
|
|
2355
|
+
writeJson(statePath, {
|
|
2356
|
+
pid: process.pid,
|
|
2357
|
+
version: input.clientVersion,
|
|
2358
|
+
service: manager,
|
|
2359
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2360
|
+
});
|
|
2361
|
+
const workersDir = contextWorkersDir(input.apiUrl, context.ecid);
|
|
2362
|
+
const reaped = reapLeftoverWorkers(workersDir);
|
|
2363
|
+
if (reaped.length > 0) {
|
|
2364
|
+
input.write(
|
|
2365
|
+
`Stopped ${reaped.length} local worker(s) left running by an earlier daemon for this context.
|
|
2366
|
+
`
|
|
2367
|
+
);
|
|
2368
|
+
}
|
|
2369
|
+
const workerTracker = createLocalWorkerTracker(workersDir);
|
|
2370
|
+
const packageGraphCache = createPackageGraphCache();
|
|
2371
|
+
let stop = "shutdown";
|
|
2372
|
+
try {
|
|
2373
|
+
stop = await runDaemon({
|
|
2374
|
+
apiUrl: input.apiUrl,
|
|
2375
|
+
ecid: context.ecid,
|
|
2376
|
+
privateKey,
|
|
2377
|
+
serverKeys,
|
|
2378
|
+
maxConcurrent,
|
|
2379
|
+
client: { name: "kody-cli", version: input.clientVersion },
|
|
2380
|
+
capabilities: {
|
|
2381
|
+
...localCapabilities(maxConcurrent),
|
|
2382
|
+
...manager ? { service: manager } : {}
|
|
2383
|
+
},
|
|
2384
|
+
execute: (run) => runContextRun({
|
|
2385
|
+
...run,
|
|
2386
|
+
apiUrl: input.apiUrl,
|
|
2387
|
+
workerTracker,
|
|
2388
|
+
packageGraphCache
|
|
2389
|
+
}),
|
|
2390
|
+
fs: {
|
|
2391
|
+
effective: async (grantFs) => await effectiveFs(grantFs, (await readLocalPolicy()).fs),
|
|
2392
|
+
onChange: (listener) => {
|
|
2393
|
+
const path = localPolicyPath();
|
|
2394
|
+
watchFile(path, { interval: 2e3 }, listener);
|
|
2395
|
+
return () => unwatchFile(path, listener);
|
|
2396
|
+
}
|
|
2397
|
+
},
|
|
2398
|
+
log: (line) => input.write(`${line}
|
|
2399
|
+
`),
|
|
2400
|
+
signal: abort.signal,
|
|
2401
|
+
drainSignal: drain.signal
|
|
2402
|
+
});
|
|
2403
|
+
} finally {
|
|
2404
|
+
workerTracker.killAll();
|
|
2405
|
+
workerTracker.dispose();
|
|
2406
|
+
if (hardStop) clearTimeout(hardStop);
|
|
2407
|
+
process.off("SIGINT", onSignal);
|
|
2408
|
+
process.off("SIGTERM", onSignal);
|
|
2409
|
+
rmSync2(statePath, { force: true });
|
|
2410
|
+
}
|
|
2411
|
+
if (stop !== "shutdown") {
|
|
2412
|
+
const reason = stop === "revoked" ? "Kody revoked this context" : "Kody no longer knows this context (deleted)";
|
|
2413
|
+
writeJson(
|
|
2414
|
+
servicePaths({
|
|
2415
|
+
apiUrl: input.apiUrl,
|
|
2416
|
+
ecid,
|
|
2417
|
+
manager: serviceManagerFor() ?? "systemd"
|
|
2418
|
+
}).stoppedPath,
|
|
2419
|
+
{ reason, at: (/* @__PURE__ */ new Date()).toISOString() }
|
|
2420
|
+
);
|
|
2421
|
+
if (manager) disableOwnService({ manager, ecid });
|
|
2422
|
+
input.write(
|
|
2423
|
+
`${reason}. Stopping for good${manager ? " and disabling the service" : ""}. Register again with: kody connect --name <name>
|
|
2424
|
+
`
|
|
2425
|
+
);
|
|
2426
|
+
}
|
|
2427
|
+
return stayStoppedExitCode;
|
|
2428
|
+
}
|
|
2429
|
+
throw new Error(
|
|
2430
|
+
"Usage: kody context register --name <name> [--org <slug>] | kody context list | kody context revoke <name> | kody context delete <name> | kody context policy [show | allow <path> [--mode ro|rw] | remove <path>] | kody chain show | add <name> | remove <name> | kody connect --name <name> | kody daemon [--context <ec id>] [--max-concurrent <n>] | kody daemon install | status | logs | restart | uninstall | kody update"
|
|
2431
|
+
);
|
|
2432
|
+
}
|
|
2433
|
+
async function resolveContextId(input) {
|
|
2434
|
+
if (input.ref.startsWith("ec_")) return input.ref;
|
|
2435
|
+
const body = await apiJson({
|
|
2436
|
+
...input,
|
|
2437
|
+
method: "GET",
|
|
2438
|
+
path: "/v1/execution-contexts"
|
|
2439
|
+
});
|
|
2440
|
+
const match = (body.contexts ?? []).find((c) => c.name === input.ref);
|
|
2441
|
+
if (!match)
|
|
2442
|
+
throw new Error(`No execution context named ${input.ref} in this org.`);
|
|
2443
|
+
return match.id;
|
|
2444
|
+
}
|
|
2445
|
+
function chainOf(body) {
|
|
2446
|
+
return body.chain ?? {};
|
|
2447
|
+
}
|
|
2448
|
+
function contextsById(body) {
|
|
2449
|
+
const contexts = body.contexts ?? [];
|
|
2450
|
+
return new Map(contexts.map((context) => [context.id, context]));
|
|
2451
|
+
}
|
|
2452
|
+
function describeChain(chain, contexts = /* @__PURE__ */ new Map()) {
|
|
2453
|
+
const entries = chain.entries ?? [];
|
|
2454
|
+
const lines = entries.map((entry, index) => {
|
|
2455
|
+
if (entry.kind === "cloud") return `${index + 1}. Kody cloud (always last)`;
|
|
2456
|
+
const known = entry.id ? contexts.get(entry.id) : void 0;
|
|
2457
|
+
const name = entry.name ?? known?.name;
|
|
2458
|
+
const label = name ? `${name} (${entry.id})` : String(entry.id);
|
|
2459
|
+
const offline = known?.status && known.status !== "online" ? ` [${known.status}]` : "";
|
|
2460
|
+
const skipped = entry.usable === false ? ` (skipped: ${entry.unusableReason})` : "";
|
|
2461
|
+
return `${index + 1}. ${label}${offline}${skipped}`;
|
|
2462
|
+
});
|
|
2463
|
+
if (chain.strict) lines.push("Strict: Kody cloud is not in this chain.");
|
|
2464
|
+
return lines.join("\n") || "Empty chain.";
|
|
2465
|
+
}
|
|
2466
|
+
function readCodeFile(path) {
|
|
2467
|
+
return readFileSync4(path, "utf8");
|
|
2468
|
+
}
|
|
2469
|
+
var policyUsage = "Usage: kody context policy [show] | kody context policy allow <path> [--mode ro|rw] | kody context policy remove <path>";
|
|
2470
|
+
async function runPolicyCommand(input, [action, path, ...extra]) {
|
|
2471
|
+
const file = localPolicyPath();
|
|
2472
|
+
const describe = (rules) => rules.length === 0 ? `No host folders are allowed on this machine (${file}). Execution-context runs only see their virtual filesystem.` : [
|
|
2473
|
+
`Host folders this machine allows (${file}):`,
|
|
2474
|
+
...rules.map((rule) => ` ${rule.mode} ${rule.path}`),
|
|
2475
|
+
"A run can use a folder only if its context grant (grant.fs) also lists it; the narrower mode wins."
|
|
2476
|
+
].join("\n");
|
|
2477
|
+
if (action === void 0 || action === "show") {
|
|
2478
|
+
const policy = await readLocalPolicy(file);
|
|
2479
|
+
out(input, { path: file, ...policy }, describe(policy.fs));
|
|
2480
|
+
return 0;
|
|
2481
|
+
}
|
|
2482
|
+
if (!path || extra.length > 0) throw new Error(policyUsage);
|
|
2483
|
+
if (action === "allow") {
|
|
2484
|
+
const mode = input.values.mode ?? "ro";
|
|
2485
|
+
if (mode !== "ro" && mode !== "rw") {
|
|
2486
|
+
throw new Error("--mode must be ro (read-only) or rw (read-write).");
|
|
2487
|
+
}
|
|
2488
|
+
const { policy, added } = await allowLocalPath({
|
|
2489
|
+
path,
|
|
2490
|
+
mode,
|
|
2491
|
+
policyPath: file
|
|
2492
|
+
});
|
|
2493
|
+
out(
|
|
2494
|
+
input,
|
|
2495
|
+
{ path: file, ...policy },
|
|
2496
|
+
`Allowed ${added.path} (${added.mode}). Running daemons pick this up within a few seconds.
|
|
2497
|
+
${describe(policy.fs)}`
|
|
2498
|
+
);
|
|
2499
|
+
return 0;
|
|
2500
|
+
}
|
|
2501
|
+
if (action === "remove") {
|
|
2502
|
+
const { policy, removed } = await removeLocalPath({
|
|
2503
|
+
path,
|
|
2504
|
+
policyPath: file
|
|
2505
|
+
});
|
|
2506
|
+
out(
|
|
2507
|
+
input,
|
|
2508
|
+
{ path: file, removed, ...policy },
|
|
2509
|
+
`${removed ? `Removed ${path}.` : `${path} was not in the policy.`}
|
|
2510
|
+
${describe(policy.fs)}`
|
|
2511
|
+
);
|
|
2512
|
+
return 0;
|
|
2513
|
+
}
|
|
2514
|
+
throw new Error(policyUsage);
|
|
2515
|
+
}
|
|
2516
|
+
export {
|
|
2517
|
+
defaultMaxConcurrentRuns,
|
|
2518
|
+
localCapabilities,
|
|
2519
|
+
maxConcurrentRuns,
|
|
2520
|
+
readCodeFile,
|
|
2521
|
+
runExecutionContextCommand
|
|
2522
|
+
};
|
|
2523
|
+
//# sourceMappingURL=commands-LSLLUXHL.js.map
|