@kodycodes/cli 3.37.1 → 3.38.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -11,6 +11,7 @@ import {
11
11
  checkContextLogin,
12
12
  checkForUpdate,
13
13
  classifyFrameText,
14
+ connectionState,
14
15
  contextWorkersDir,
15
16
  decodeEnvelopePayload,
16
17
  describeHolder,
@@ -29,6 +30,7 @@ import {
29
30
  fetchServerKeys,
30
31
  fileWrappingKey,
31
32
  generateContextKey,
33
+ healthWriteMs,
32
34
  importContextKey,
33
35
  importEd25519PublicKey,
34
36
  isExperimentOffError,
@@ -63,6 +65,7 @@ import {
63
65
  signFrame,
64
66
  signedFetch,
65
67
  startDaemonUpdater,
68
+ startLoopWatchdog,
66
69
  startupRefusedExitCode,
67
70
  stayStoppedExitCode,
68
71
  storedContextIds,
@@ -73,8 +76,9 @@ import {
73
76
  verifyFrame,
74
77
  wrappingKeyForStoredContext,
75
78
  writeJson
76
- } from "./chunk-CCMC5Y7V.js";
79
+ } from "./chunk-6RJ6B7S3.js";
77
80
  import {
81
+ MachineCapabilityError,
78
82
  advertisedMachineCapabilities,
79
83
  allowLocalPath,
80
84
  canonicalHostPath,
@@ -94,11 +98,12 @@ import {
94
98
  readLocalPolicy,
95
99
  removeLocalCapability,
96
100
  removeLocalPath,
101
+ resolveMachineCommand,
97
102
  samePath,
98
103
  setLocalAutoUpdateEnabled,
99
104
  setLocalCapability,
100
105
  setLocalCommandsEnabled
101
- } from "./chunk-JWKBLNLH.js";
106
+ } from "./chunk-WXRMBP25.js";
102
107
  import "./chunk-AM2SBW3C.js";
103
108
  import {
104
109
  windowsCommandLine
@@ -157,6 +162,9 @@ function runRequestRefusal(request, apiUrl, now = Date.now()) {
157
162
  if (now > request.acceptBy) return "deadline_passed";
158
163
  return null;
159
164
  }
165
+ function daemonConnection() {
166
+ return { connected: false, since: Date.now(), lastHeardAt: null };
167
+ }
160
168
  var daemonControlFeature = "daemon-control";
161
169
  var DaemonControlError = class extends Error {
162
170
  constructor(code, message) {
@@ -189,6 +197,9 @@ var layerLabel = {
189
197
  var welcomeTimeoutMs = 15e3;
190
198
  var welcomeTimeoutCloseCode = 4e3;
191
199
  var closeSettleMs = 5e3;
200
+ var connectTicketTimeoutMs = 3e4;
201
+ var restartWhenOfflineMs = 30 * 6e4;
202
+ var offlineTurnCapMs = 2 * 6e4;
192
203
  var defaultPingMs = 3e4;
193
204
  var defaultPongTimeoutMs = 1e4;
194
205
  var heartbeatTimeoutCloseCode = 4001;
@@ -202,7 +213,8 @@ function daemonRunState() {
202
213
  results: /* @__PURE__ */ new Map(),
203
214
  hostFs: emptyEffectiveFs,
204
215
  grantFs: [],
205
- report: null
216
+ report: null,
217
+ welcomes: 0
206
218
  };
207
219
  }
208
220
  function pruneResults(state, now = Date.now()) {
@@ -219,8 +231,14 @@ async function runDaemonConnection(input, carried) {
219
231
  "This Node.js has no global WebSocket. Use Node 22 or newer."
220
232
  );
221
233
  }
222
- const { ticket } = await requestConnectTicket(input);
223
- if (input.signal?.aborted) return { code: 1e3, reason: "shutdown" };
234
+ const ticketTimeout = AbortSignal.timeout(connectTicketTimeoutMs);
235
+ const { ticket } = await requestConnectTicket({
236
+ ...input,
237
+ signal: input.signal ? AbortSignal.any([input.signal, ticketTimeout]) : ticketTimeout
238
+ });
239
+ if (input.signal?.aborted) {
240
+ return { code: 1e3, reason: "shutdown" };
241
+ }
224
242
  const url = new URL(`${executionContextsPath}/connect`, input.apiUrl);
225
243
  url.protocol = url.protocol === "http:" ? "ws:" : "wss:";
226
244
  url.searchParams.set("ticket", ticket);
@@ -320,10 +338,7 @@ async function runDaemonConnection(input, carried) {
320
338
  outbound = sent.catch(() => {
321
339
  if (outboundFailed) return;
322
340
  outboundFailed = true;
323
- try {
324
- ws.close(4e3, "send failed");
325
- } catch {
326
- }
341
+ closeSocket(4e3, "send failed");
327
342
  });
328
343
  return sent;
329
344
  };
@@ -347,6 +362,8 @@ async function runDaemonConnection(input, carried) {
347
362
  });
348
363
  let closeWhenDrained = () => {
349
364
  };
365
+ let closeSocket = (_code, _reason) => {
366
+ };
350
367
  const reportResult = (runId) => {
351
368
  const result = state.results.get(runId);
352
369
  if (!result) return;
@@ -449,6 +466,11 @@ async function runDaemonConnection(input, carried) {
449
466
  await applyFs();
450
467
  input.onPaused?.(pauseOf(body.paused));
451
468
  welcomed = true;
469
+ state.welcomes += 1;
470
+ if (input.connection) {
471
+ input.connection.connected = true;
472
+ input.connection.since = Date.now();
473
+ }
452
474
  await send("hello", {
453
475
  protocol: { min: ecpProtocolVersion, max: ecpProtocolVersion },
454
476
  client: input.client,
@@ -565,7 +587,7 @@ async function runDaemonConnection(input, carried) {
565
587
  input.log(
566
588
  `This context was revoked (${String(body.reason ?? "revoked")}).`
567
589
  );
568
- ws.close(1e3, "revoked");
590
+ closeSocket(1e3, "revoked");
569
591
  return;
570
592
  case "error":
571
593
  input.log(`Kody: ${String(body.code)} ${String(body.message ?? "")}`);
@@ -583,7 +605,15 @@ async function runDaemonConnection(input, carried) {
583
605
  const armHeartbeat = (pingMs, pongTimeoutMs) => {
584
606
  clearInterval(ping);
585
607
  const sendPing = () => {
586
- if (ws.readyState !== ws.OPEN || pongTimer) return;
608
+ if (settled || settleTimer || pongTimer) return;
609
+ if (ws.readyState === ws.CONNECTING) return;
610
+ if (ws.readyState !== ws.OPEN) {
611
+ input.log(
612
+ "The connection to Kody stopped without a close event. Closing and reconnecting."
613
+ );
614
+ closeAndSettle(heartbeatTimeoutCloseCode, "socket stalled closing");
615
+ return;
616
+ }
587
617
  const sentAt = Date.now();
588
618
  try {
589
619
  ws.send(ecpPingFrame);
@@ -640,6 +670,10 @@ async function runDaemonConnection(input, carried) {
640
670
  if (!run.committed) runs.delete(runId);
641
671
  }
642
672
  if (input.activity) input.activity.runs = runs.size;
673
+ if (input.connection?.connected) {
674
+ input.connection.connected = false;
675
+ input.connection.since = Date.now();
676
+ }
643
677
  resolve({ code, reason });
644
678
  };
645
679
  const closeAndSettle = (code, reason) => {
@@ -652,6 +686,7 @@ async function runDaemonConnection(input, carried) {
652
686
  input.closeSettleMs ?? closeSettleMs
653
687
  );
654
688
  };
689
+ closeSocket = closeAndSettle;
655
690
  welcomeTimer = setTimeout(() => {
656
691
  input.log(
657
692
  `Kody did not send a welcome frame within ${Math.round(timeoutMs / 1e3)}s, so this context cannot come online. Closing and retrying.`
@@ -694,6 +729,7 @@ async function runDaemonConnection(input, carried) {
694
729
  let inbound = Promise.resolve();
695
730
  ws.addEventListener("message", (event) => {
696
731
  lastInboundAt = Date.now();
732
+ if (input.connection) input.connection.lastHeardAt = lastInboundAt;
697
733
  const text = typeof event.data === "string" ? event.data : "";
698
734
  inbound = inbound.then(() => onMessage(text)).catch((error) => input.log(`Frame error: ${String(error)}`));
699
735
  });
@@ -755,10 +791,13 @@ async function runDaemon(input) {
755
791
  }
756
792
  async function reconnectLoop(input, state) {
757
793
  let attempt = 0;
794
+ let offlineMs = 0;
795
+ const maxOfflineMs = input.maxOfflineMs ?? Number.POSITIVE_INFINITY;
758
796
  const holding = () => state.runs.size > 0 || pruneResults(state) > 0;
759
797
  const stopping = () => input.signal?.aborted || input.drainSignal?.aborted && !holding();
760
798
  while (!stopping()) {
761
799
  const startedAt = Date.now();
800
+ const welcomesBefore = state.welcomes;
762
801
  try {
763
802
  const closed = await runDaemonConnection(input, state);
764
803
  if (closed.reason === "revoked") return "revoked";
@@ -792,9 +831,16 @@ async function reconnectLoop(input, state) {
792
831
  }
793
832
  if (Date.now() - startedAt > 6e4) attempt = 0;
794
833
  attempt += 1;
795
- const delay = Math.min(6e4, 1e3 * 2 ** Math.min(attempt, 6));
834
+ const delay = Math.min(6e4, 1e3 * 2 ** Math.min(attempt, 6)) * (0.5 + Math.random() / 2);
835
+ offlineMs = state.welcomes > welcomesBefore ? 0 : offlineMs + Math.min(offlineTurnCapMs, Date.now() - startedAt) + delay;
836
+ if (offlineMs >= maxOfflineMs && !holding()) {
837
+ input.log(
838
+ `No working connection to Kody for about ${Math.round(offlineMs / 6e4)} minutes. Exiting so the service manager or container restarts kody.`
839
+ );
840
+ return "unreachable";
841
+ }
796
842
  await abortableDelay(
797
- delay * (0.5 + Math.random() / 2),
843
+ delay,
798
844
  input.drainSignal && !holding() ? AbortSignal.any(
799
845
  [input.signal, input.drainSignal].filter(
800
846
  (signal) => signal !== void 0
@@ -1022,6 +1068,16 @@ function stoppedOutcome(outcome, stoppedByKody) {
1022
1068
  if (!stoppedByKody || process.platform !== "win32") return outcome;
1023
1069
  return { ...outcome, code: null, signal: outcome.signal ?? "SIGKILL" };
1024
1070
  }
1071
+ var namedCommandFields = /* @__PURE__ */ new Set([
1072
+ "capability",
1073
+ "args",
1074
+ "timeoutMs",
1075
+ "maxOutputBytes"
1076
+ ]);
1077
+ function namedCapability(input) {
1078
+ const capability = typeof input === "object" && input !== null && !Array.isArray(input) ? input.capability : void 0;
1079
+ return capability === void 0 ? null : { capability };
1080
+ }
1025
1081
  function inheritedCommandEnv(env = process.env) {
1026
1082
  return Object.fromEntries(
1027
1083
  Object.entries(env).filter(([key]) => !/^KODY_/i.test(key))
@@ -1039,7 +1095,9 @@ var HostCommands = class {
1039
1095
  #grantEnabled = false;
1040
1096
  #platform;
1041
1097
  #deniedPaths;
1098
+ #namedCommand;
1042
1099
  constructor(options = {}) {
1100
+ this.#namedCommand = options.namedCommand;
1043
1101
  this.#localEnabled = options.localEnabled === true;
1044
1102
  this.#platform = options.platform ?? process.platform;
1045
1103
  this.#deniedPaths = options.deniedPaths ?? credentialDenylist();
@@ -1048,6 +1106,7 @@ var HostCommands = class {
1048
1106
  get enabled() {
1049
1107
  return this.#localEnabled && this.#grantEnabled;
1050
1108
  }
1109
+ // Turning the shell off ends shell commands. Named commands do not depend on it.
1051
1110
  setLocalEnabled(enabled) {
1052
1111
  this.#localEnabled = enabled;
1053
1112
  if (!enabled) this.killAll("commands_off");
@@ -1083,10 +1142,13 @@ var HostCommands = class {
1083
1142
  }
1084
1143
  /** Dispatches one `kody.command.<name>(args)` call from a run. */
1085
1144
  async call(name, args, run) {
1086
- this.assertAvailable();
1087
- if (name === "status" || name === "output" || name === "kill" || name === "list") {
1088
- await run.authorize({ lifecycle: name });
1145
+ const named = name === "run" || name === "start" ? namedCapability(args) !== null : name === "list" ? true : await this.#authorizeNamedJob(name, args, run);
1146
+ if (!named) {
1089
1147
  this.assertAvailable();
1148
+ if (name === "status" || name === "output" || name === "kill") {
1149
+ await run.authorize({ lifecycle: name });
1150
+ this.assertAvailable();
1151
+ }
1090
1152
  }
1091
1153
  switch (name) {
1092
1154
  case "run":
@@ -1100,7 +1162,7 @@ var HostCommands = class {
1100
1162
  case "kill":
1101
1163
  return this.kill(args, run);
1102
1164
  case "list":
1103
- return this.list(run);
1165
+ return await this.#list(run);
1104
1166
  default:
1105
1167
  throw new HostCommandError(
1106
1168
  "invalid_request",
@@ -1108,7 +1170,149 @@ var HostCommands = class {
1108
1170
  );
1109
1171
  }
1110
1172
  }
1173
+ #ownJobs(run) {
1174
+ return [...this.#jobs.values()].filter(
1175
+ (job) => job.ownerUserId === run.requesterUserId
1176
+ );
1177
+ }
1178
+ /**
1179
+ * A lifecycle call on the caller's own named-command job is authorized
1180
+ * against that command, so it works with the shell off.
1181
+ */
1182
+ async #authorizeNamedJob(name, args, run) {
1183
+ if (name !== "status" && name !== "output" && name !== "kill") return false;
1184
+ const id = typeof args === "string" ? args : args?.commandId;
1185
+ const job = typeof id === "string" ? this.#jobs.get(id) : void 0;
1186
+ if (!job?.capability || job.ownerUserId !== run.requesterUserId) {
1187
+ return false;
1188
+ }
1189
+ await run.authorize({ lifecycle: name, capability: job.capability });
1190
+ return true;
1191
+ }
1192
+ /**
1193
+ * `list` for a caller the shell rules refuse: their named-command jobs,
1194
+ * each command authorized on its own, so a command that was removed or is
1195
+ * no longer granted hides only its own jobs. Null when none is allowed.
1196
+ */
1197
+ async #allowedNamedJobs(run) {
1198
+ const allowed = /* @__PURE__ */ new Set();
1199
+ const capabilities = new Set(
1200
+ this.#ownJobs(run).flatMap(
1201
+ (job) => job.capability ? [job.capability] : []
1202
+ )
1203
+ );
1204
+ for (const capability of capabilities) {
1205
+ await run.authorize({ lifecycle: "list", capability }).then(
1206
+ () => allowed.add(capability),
1207
+ () => {
1208
+ }
1209
+ );
1210
+ }
1211
+ return allowed.size > 0 ? allowed : null;
1212
+ }
1213
+ async #list(run) {
1214
+ try {
1215
+ this.assertAvailable();
1216
+ await run.authorize({ lifecycle: "list" });
1217
+ this.assertAvailable();
1218
+ } catch (error) {
1219
+ const allowed = await this.#allowedNamedJobs(run);
1220
+ if (!allowed) throw error;
1221
+ return this.list(run, { capabilities: allowed });
1222
+ }
1223
+ return this.list(run);
1224
+ }
1225
+ async #prepareNamed(spec, background) {
1226
+ const name = spec.capability;
1227
+ if (typeof name !== "string" || name.length === 0) {
1228
+ throw new HostCommandError(
1229
+ "invalid_request",
1230
+ "`capability` is the name of a command this machine defines."
1231
+ );
1232
+ }
1233
+ const extra = Object.keys(spec).filter(
1234
+ (key) => !namedCommandFields.has(key)
1235
+ );
1236
+ if (extra.length > 0) {
1237
+ throw new HostCommandError(
1238
+ "invalid_request",
1239
+ `A named command takes \`args\`, \`timeoutMs\` and \`maxOutputBytes\` only. The machine's definition sets the rest, so remove ${extra.map((key) => `\`${key}\``).join(", ")}.`
1240
+ );
1241
+ }
1242
+ const definition = await this.#namedCommand?.(name);
1243
+ if (!definition) {
1244
+ throw new HostCommandError(
1245
+ "machine_capability_off",
1246
+ `This machine defines no command named "${name}". Its owner defines one on the machine with \`kody context capability add command <file.json>\`; \`kody context capability list\` shows what is defined.`
1247
+ );
1248
+ }
1249
+ const args = spec.args ?? [];
1250
+ let resolved;
1251
+ try {
1252
+ resolved = resolveMachineCommand(definition, args);
1253
+ } catch (error) {
1254
+ if (error instanceof MachineCapabilityError) {
1255
+ throw new HostCommandError(
1256
+ error.code === "machine_command_args_refused" ? error.code : "invalid_request",
1257
+ error.message
1258
+ );
1259
+ }
1260
+ throw error;
1261
+ }
1262
+ if (background && !resolved.background) {
1263
+ throw new HostCommandError(
1264
+ "invalid_request",
1265
+ `Command "${name}" does not run in the background on this machine. Use kody.command.run.`
1266
+ );
1267
+ }
1268
+ const cwd = resolved.cwd ?? homedir();
1269
+ const cwdStat = await stat(cwd).catch(() => null);
1270
+ if (!cwdStat?.isDirectory()) {
1271
+ throw new HostCommandError(
1272
+ "invalid_request",
1273
+ `The folder command "${name}" runs in is missing on this machine. Its owner fixes the definition's "cwd".`
1274
+ );
1275
+ }
1276
+ const maxTimeoutMs = Math.min(
1277
+ resolved.timeoutMs,
1278
+ background ? hostCommandLimits.backgroundMaxTimeoutMs : hostCommandLimits.foregroundMaxTimeoutMs
1279
+ );
1280
+ const env = inheritedCommandEnv();
1281
+ const launch = this.#platform !== "win32" ? { file: resolved.file, argv: resolved.args, verbatim: false } : windowsFileLaunch(resolved.file, resolved.args, env);
1282
+ const callerArgs = args;
1283
+ return {
1284
+ // The name and the caller's arguments: the executable path stays here.
1285
+ display: [name, ...callerArgs].join(" "),
1286
+ cwd,
1287
+ shownCwd: "",
1288
+ named: { capability: name, args: callerArgs },
1289
+ env,
1290
+ envKeys: [],
1291
+ stdin: void 0,
1292
+ timeoutMs: clampInt(
1293
+ spec.timeoutMs,
1294
+ maxTimeoutMs,
1295
+ maxTimeoutMs,
1296
+ Math.min(background ? 1e3 : 100, maxTimeoutMs)
1297
+ ),
1298
+ maxOutputBytes: clampInt(
1299
+ spec.maxOutputBytes,
1300
+ hostCommandLimits.defaultOutputBytes,
1301
+ hostCommandLimits.maxOutputBytes,
1302
+ 1024
1303
+ ),
1304
+ file: launch.file,
1305
+ argv: launch.argv,
1306
+ verbatim: launch.verbatim
1307
+ };
1308
+ }
1111
1309
  async #prepare(input, background) {
1310
+ if (namedCapability(input)) {
1311
+ return await this.#prepareNamed(
1312
+ input,
1313
+ background
1314
+ );
1315
+ }
1112
1316
  const raw = typeof input === "string" ? { command: input } : input;
1113
1317
  const spec = raw ?? {};
1114
1318
  if (typeof spec !== "object" || Array.isArray(spec)) {
@@ -1217,6 +1421,7 @@ var HostCommands = class {
1217
1421
  return {
1218
1422
  display,
1219
1423
  cwd,
1424
+ shownCwd: cwd,
1220
1425
  env,
1221
1426
  envKeys: Object.keys(extraEnv).sort(),
1222
1427
  stdin: spec.stdin,
@@ -1263,15 +1468,19 @@ var HostCommands = class {
1263
1468
  await run.authorize({
1264
1469
  commandId,
1265
1470
  command: prepared.display,
1266
- cwd: prepared.cwd,
1471
+ cwd: prepared.shownCwd,
1267
1472
  envKeys: prepared.envKeys,
1268
- background: false
1473
+ background: false,
1474
+ ...prepared.named
1269
1475
  });
1270
- this.assertAvailable();
1476
+ if (!prepared.named) this.assertAvailable();
1271
1477
  const startedAt = Date.now();
1272
1478
  const stdout = new OutputBuffer(prepared.maxOutputBytes);
1273
1479
  const stderr = new OutputBuffer(prepared.maxOutputBytes);
1274
- const ended = { reason: "exited" };
1480
+ const ended = {
1481
+ reason: "exited",
1482
+ named: prepared.named !== void 0
1483
+ };
1275
1484
  const child = this.#spawn(prepared);
1276
1485
  this.#foreground.set(child, ended);
1277
1486
  child.stdout?.on("data", (chunk) => stdout.write(chunk));
@@ -1303,7 +1512,7 @@ var HostCommands = class {
1303
1512
  commandId,
1304
1513
  runId: run.runId,
1305
1514
  command: prepared.display,
1306
- cwd: prepared.cwd,
1515
+ cwd: prepared.shownCwd,
1307
1516
  exitCode: outcome.code,
1308
1517
  signal: outcome.signal,
1309
1518
  durationMs,
@@ -1349,11 +1558,12 @@ var HostCommands = class {
1349
1558
  await run.authorize({
1350
1559
  commandId,
1351
1560
  command: prepared.display,
1352
- cwd: prepared.cwd,
1561
+ cwd: prepared.shownCwd,
1353
1562
  envKeys: prepared.envKeys,
1354
- background: true
1563
+ background: true,
1564
+ ...prepared.named
1355
1565
  });
1356
- this.assertAvailable();
1566
+ if (!prepared.named) this.assertAvailable();
1357
1567
  child = this.#spawn(prepared);
1358
1568
  } finally {
1359
1569
  this.#pendingStarts--;
@@ -1363,7 +1573,8 @@ var HostCommands = class {
1363
1573
  runId: run.runId,
1364
1574
  ownerUserId: run.requesterUserId,
1365
1575
  command: prepared.display,
1366
- cwd: prepared.cwd,
1576
+ cwd: prepared.shownCwd,
1577
+ ...prepared.named ? { capability: prepared.named.capability } : {},
1367
1578
  child,
1368
1579
  pid: child.pid,
1369
1580
  startedAt: Date.now(),
@@ -1454,6 +1665,7 @@ var HostCommands = class {
1454
1665
  durationMs: (job.endedAt ?? Date.now()) - job.startedAt,
1455
1666
  stdoutBytes: job.stdout.total,
1456
1667
  stderrBytes: job.stderr.total,
1668
+ ...job.capability ? { capability: job.capability } : {},
1457
1669
  ...job.error && job.state === "failed" ? { error: job.error } : {}
1458
1670
  };
1459
1671
  }
@@ -1504,20 +1716,26 @@ var HostCommands = class {
1504
1716
  }
1505
1717
  return this.#describe(job);
1506
1718
  }
1507
- list(run) {
1719
+ list(run, options = {}) {
1508
1720
  this.#sweep();
1509
1721
  return {
1510
- commands: [...this.#jobs.values()].filter((job) => job.ownerUserId === run.requesterUserId).map((job) => this.#describe(job))
1722
+ commands: this.#ownJobs(run).filter(
1723
+ (job) => !options.capabilities || job.capability !== void 0 && options.capabilities.has(job.capability)
1724
+ ).map((job) => this.#describe(job))
1511
1725
  };
1512
1726
  }
1513
1727
  /** Commands were turned off (or the daemon stops): end every background job. */
1514
1728
  killAll(reason) {
1729
+ const spared = (named) => named && reason === "commands_off";
1515
1730
  for (const [child, ended] of this.#foreground) {
1731
+ if (spared(ended.named)) continue;
1516
1732
  ended.reason = reason === "commands_off" ? "commands_off" : "cancelled";
1517
1733
  killTree(child, "SIGKILL");
1518
1734
  }
1519
1735
  for (const job of this.#jobs.values()) {
1520
- if (job.state !== "running") continue;
1736
+ if (job.state !== "running" || spared(job.capability !== void 0)) {
1737
+ continue;
1738
+ }
1521
1739
  nextState(hostCommandState, job.state, { type: "KILL" });
1522
1740
  job.state = "killed";
1523
1741
  job.error = reason === "commands_off" ? "commands_off" : null;
@@ -2055,6 +2273,7 @@ async function runCommand(input) {
2055
2273
  ...maxConcurrent === void 0 ? {} : { maxConcurrent },
2056
2274
  ...input.values.keyStorage ? { keyStorage: input.values.keyStorage } : {},
2057
2275
  ...input.values.lines ? { lines: input.values.lines } : {},
2276
+ ...input.values.maxAge ? { maxAge: input.values.maxAge } : {},
2058
2277
  ...input.values.follow ? { follow: true } : {},
2059
2278
  ...input.values.unregister === void 0 ? {} : { unregister: input.values.unregister },
2060
2279
  revoke: async (ecid) => {
@@ -2393,9 +2612,12 @@ Run \`kody daemon\` in a terminal, or fix that and run: kody daemon install --co
2393
2612
  }
2394
2613
  const { context, privateKey } = started;
2395
2614
  let { serverKeys } = started;
2396
- const { runContextRun } = await import("./run-executor-JT2M5ICX.js");
2615
+ const { runContextRun } = await import("./run-executor-YGO2EYHY.js");
2397
2616
  const hostCommands = new HostCommands({
2398
- localEnabled: await readLocalCommandsEnabled().catch(() => false)
2617
+ localEnabled: await readLocalCommandsEnabled().catch(() => false),
2618
+ namedCommand: async (name) => (await readLocalPolicy()).capabilities?.commands.find(
2619
+ (command) => command.name === name
2620
+ )
2399
2621
  });
2400
2622
  const commandsPolicyPath = localPolicyPath();
2401
2623
  const onCommandsPolicyChange = () => {
@@ -2493,13 +2715,30 @@ Run \`kody daemon\` in a terminal, or fix that and run: kody daemon install --co
2493
2715
  ecid,
2494
2716
  manager: serviceManagerFor() ?? "systemd"
2495
2717
  }).statePath;
2496
- writeJson(statePath, {
2497
- pid: process.pid,
2498
- version: input.clientVersion,
2499
- service: manager,
2500
- startedAt: (/* @__PURE__ */ new Date()).toISOString(),
2501
- ...supervised ? { supervisorPid: process.ppid } : {}
2502
- });
2718
+ const connection = daemonConnection();
2719
+ const writeState = () => {
2720
+ try {
2721
+ writeJson(statePath, {
2722
+ pid: process.pid,
2723
+ version: input.clientVersion,
2724
+ service: manager,
2725
+ startedAt,
2726
+ ...supervised ? { supervisorPid: process.ppid } : {},
2727
+ connection: connectionState(connection)
2728
+ });
2729
+ } catch {
2730
+ }
2731
+ };
2732
+ writeState();
2733
+ const stateTimer = setInterval(writeState, healthWriteMs);
2734
+ stateTimer.unref();
2735
+ const stopWatchdog = startLoopWatchdog();
2736
+ const restarted = Boolean(manager) || process.pid === 1 || supervised && process.ppid === 1 || existsSync("/.dockerenv") || existsSync("/run/.containerenv");
2737
+ if (process.pid === 1) {
2738
+ log(
2739
+ "kody is PID 1 in this container, so it cannot kill itself if it ever freezes. Run the container with an init process (docker run --init, or init: true in compose) and add a healthcheck: kody daemon health"
2740
+ );
2741
+ }
2503
2742
  const workersDir = contextWorkersDir(input.apiUrl, context.ecid);
2504
2743
  const reaped = reapLeftoverWorkers(workersDir);
2505
2744
  if (reaped.length > 0) {
@@ -2603,6 +2842,8 @@ Run \`kody daemon\` in a terminal, or fix that and run: kody daemon install --co
2603
2842
  loginTimer.unref();
2604
2843
  try {
2605
2844
  stop = await runDaemon({
2845
+ connection,
2846
+ ...restarted ? { maxOfflineMs: restartWhenOfflineMs } : {},
2606
2847
  apiUrl: input.apiUrl,
2607
2848
  ecid: context.ecid,
2608
2849
  privateKey,
@@ -2765,6 +3006,8 @@ Run \`kody daemon\` in a terminal, or fix that and run: kody daemon install --co
2765
3006
  });
2766
3007
  } finally {
2767
3008
  clearInterval(loginTimer);
3009
+ clearInterval(stateTimer);
3010
+ stopWatchdog();
2768
3011
  clearTimeout(capabilitiesRetry);
2769
3012
  updater.stop();
2770
3013
  unwatchFile(commandsPolicyPath, onCommandsPolicyChange);
@@ -2785,6 +3028,7 @@ Run \`kody daemon\` in a terminal, or fix that and run: kody daemon install --co
2785
3028
  if (manager) return stayStoppedExitCode;
2786
3029
  return supervised ? startupRefusedExitCode : 1;
2787
3030
  }
3031
+ if (stop === "unreachable") return supervised ? startupRefusedExitCode : 1;
2788
3032
  const target = updateTo;
2789
3033
  if (stop === "shutdown" && restartRequested && !target && !signalled) {
2790
3034
  return relaunchExitCode;
@@ -2820,7 +3064,7 @@ Run \`kody daemon\` in a terminal, or fix that and run: kody daemon install --co
2820
3064
  return stayStoppedExitCode;
2821
3065
  }
2822
3066
  throw new Error(
2823
- "Usage: kody context register --name <name> [--org <slug>] | kody context list | kody context revoke <name> | kody context delete <name> | kody context cancel-run <name> <run id> | kody context policy [show | allow <path> [--mode ro|rw] | remove <path>] | kody context capability [list | add command|lan <file.json> | remove command|lan <name>] | kody context grant [show | allow <path> [--mode ro|rw] | remove <path> | lan on|off] [--context <name>] | kody context commands [status | on | off] [--context <name>] | kody chain show | add <name> | remove <name> | kody connect --name <name> | kody daemon [--context <ec id>] [--max-concurrent <n>] | kody daemon install | status | logs | restart | start | stop | uninstall | auto-update [on | off | status] | kody update"
3067
+ "Usage: kody context register --name <name> [--org <slug>] | kody context list | kody context revoke <name> | kody context delete <name> | kody context cancel-run <name> <run id> | kody context policy [show | allow <path> [--mode ro|rw] | remove <path>] | kody context capability [list | add command|lan <file.json> | remove command|lan <name>] | kody context grant [show | allow <path> [--mode ro|rw] | remove <path> | lan on|off] [--context <name>] | kody context commands [status | on | off] [--context <name>] | kody chain show | add <name> | remove <name> | kody connect --name <name> | kody daemon [--context <ec id>] [--max-concurrent <n>] | kody daemon install | status | health | logs | restart | start | stop | uninstall | auto-update [on | off | status] | kody update"
2824
3068
  );
2825
3069
  }
2826
3070
  async function resolveContextId(input) {
@@ -2988,7 +3232,7 @@ async function runCapabilityCommand(input, [action = "list", kind, target, ...ex
2988
3232
  ...lan.map(
2989
3233
  (entry) => ` lan ${entry.name}${entry.description ? `: ${entry.description}` : ""} (${entry.hosts.join(", ")} ports ${entry.ports.join(", ")})`
2990
3234
  ),
2991
- "Kody knows these by name. No run can use them yet."
3235
+ 'Kody knows these by name. Your runs use a command with kody.command.run({ capability: "<name>", args: [...] }). Local network destinations are not used by runs yet.'
2992
3236
  ].join("\n");
2993
3237
  };
2994
3238
  if (action === "list") {
@@ -3147,4 +3391,4 @@ export {
3147
3391
  maxConcurrentRuns,
3148
3392
  runExecutionContextCommand
3149
3393
  };
3150
- //# sourceMappingURL=commands-WT6T3FPA.js.map
3394
+ //# sourceMappingURL=commands-PMZIPPPC.js.map