@capybara-hq/kernel 0.1.0-rc.89 → 0.1.0-rc.90

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/background/poll.job.d.ts +10 -0
  2. package/dist/background/poll.job.js +41 -10
  3. package/dist/background/stop.d.ts +39 -7
  4. package/dist/background/stop.js +107 -19
  5. package/dist/background/store.d.ts +25 -3
  6. package/dist/background/store.js +32 -2
  7. package/dist/background/tasks.service.d.ts +16 -2
  8. package/dist/background/tasks.service.js +11 -2
  9. package/dist/catalog/marketplaces.service.d.ts +1 -1
  10. package/dist/config/schema.d.ts +1 -0
  11. package/dist/config/schema.js +11 -1
  12. package/dist/conversations/events.d.ts +5 -0
  13. package/dist/conversations/events.js +11 -0
  14. package/dist/db/kernel-schema.d.ts +4 -0
  15. package/dist/device-access/device-access.service.d.ts +4 -1
  16. package/dist/device-access/device-access.service.js +40 -11
  17. package/dist/device-access/viewer.js +3 -2
  18. package/dist/dial-in/gateway.d.ts +7 -0
  19. package/dist/dial-in/gateway.js +43 -4
  20. package/dist/dial-in/relay.d.ts +27 -5
  21. package/dist/dial-in/relay.js +83 -21
  22. package/dist/dial-in/streams.d.ts +13 -5
  23. package/dist/dial-in/streams.js +43 -30
  24. package/dist/overrides.d.ts +4 -0
  25. package/dist/overrides.js +2 -0
  26. package/dist/platform/ops/background.ops.js +5 -2
  27. package/dist/sandbox/device-services.d.ts +4 -2
  28. package/dist/sandbox/device-services.js +9 -7
  29. package/dist/sandbox/review/review.service.d.ts +5 -0
  30. package/dist/sandbox/review/review.service.js +1 -0
  31. package/dist/sandbox/review/rules.js +24 -0
  32. package/dist/sandbox/review/types.d.ts +6 -0
  33. package/dist/sandbox/sandbox.service.d.ts +23 -0
  34. package/dist/sandbox/sandbox.service.js +57 -9
  35. package/dist/tools/builtins/sandbox/common.js +6 -1
  36. package/dist/tools/builtins/sandbox/task-stop.d.ts +2 -1
  37. package/dist/tools/builtins/sandbox/task-stop.js +21 -3
  38. package/dist/tools/call-scope.d.ts +21 -0
  39. package/dist/tools/call-scope.js +25 -0
  40. package/dist/tools/pipeline.d.ts +20 -0
  41. package/dist/tools/pipeline.js +67 -5
  42. package/dist/tools/questions.service.d.ts +6 -0
  43. package/dist/tools/questions.service.js +1 -0
  44. package/dist/tools/registry.d.ts +15 -8
  45. package/dist/tools/registry.js +21 -10
  46. package/package.json +3 -3
  47. package/src/migrations/0184_background_cancel_failure.sql +10 -0
@@ -1074,6 +1074,10 @@ export interface BackgroundTasksTable {
1074
1074
  cancel_attempted_at: ColumnType<Date | null, Date | string | null | undefined, Date | string | null>;
1075
1075
  /** 0153: who asked for a managed task's cancellation (its finish keeps their wake rule). */
1076
1076
  cancel_requested_by: ColumnType<"tool" | "person" | "conversation_deleted" | "subagent_end" | null, "tool" | "person" | "conversation_deleted" | "subagent_end" | null | undefined, "tool" | "person" | "conversation_deleted" | "subagent_end" | null>;
1077
+ /** 0184: why a managed task's owed stop did not settle at its last attempt; null otherwise. */
1078
+ cancel_failure: ColumnType<"unreachable" | "failed" | null, "unreachable" | "failed" | null | undefined, "unreachable" | "failed" | null>;
1079
+ /** 0184: that failure's message, clipped. */
1080
+ cancel_failure_detail: NullableText;
1077
1081
  /** 0157: the exact incarnation a legacy dispatch was admitted for; null on historical rows. */
1078
1082
  legacy_dispatch_provider: NullableText;
1079
1083
  legacy_dispatch_generation: NullableText;
@@ -34,7 +34,9 @@ export interface DeviceAccessCaller {
34
34
  /**
35
35
  * `ctx.deviceAccess` (browser use spec §7): an extension's device services in the conversation's
36
36
  * device, limited to the conversation's owner on their own personal device and to the service
37
- * names the extension's approved manifest declares. A service launch passes the command review
37
+ * names the extension's approved manifest declares. The provider sees each service by its id
38
+ * (`<extension>.<name>`, `deviceServiceId`), so two extensions declaring the same name never
39
+ * reach each other's process; the extension sees only its own names. A service launch passes the command review
38
40
  * (fail closed: only `allow` starts it), once per start; requests ride the provider's request
39
41
  * path; refused hosts land in the call scope for the pipeline's network ask; viewer tickets are
40
42
  * single-use Redis records; the allowlist write and the handoff answer go through the device page's
@@ -64,6 +66,7 @@ export declare class DeviceAccessService {
64
66
  * on the call (the call scope) and a start is audited `device.service_started`.
65
67
  */
66
68
  ensureService(caller: DeviceAccessCaller, call: ToolCallContext, spec: DeviceServiceSpec): Promise<DeviceServiceStatus>;
69
+ private ensureServiceNow;
67
70
  /** One request to the service's socket in the call's device. */
68
71
  request(caller: DeviceAccessCaller, call: ToolCallContext, req: {
69
72
  service: string;
@@ -8,7 +8,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { randomBytes } from "node:crypto";
11
- import { DeviceAccessError, parseToolKey, ToolError, } from "@capybara-hq/plugin-sdk";
11
+ import { DeviceAccessError, deviceServiceId, parseToolKey, ToolError, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { DeviceAccess } from "../devices/access.js";
14
14
  import { ConversationDevices } from "../devices/conversation-devices.js";
@@ -24,7 +24,7 @@ import { rootConversationOf } from "../runtime/subagents/child.js";
24
24
  import { assertServiceSpec, DeviceServices } from "../sandbox/device-services.js";
25
25
  import { DeviceProviders } from "../sandbox/providers.js";
26
26
  import { CommandReviewService } from "../sandbox/review/review.service.js";
27
- import { attachCallScope, callScopeOf } from "../tools/call-scope.js";
27
+ import { attachCallScope, callScopeOf, whileDeviceStarting, } from "../tools/call-scope.js";
28
28
  import { QuestionsService } from "../tools/questions.service.js";
29
29
  /** What every `ctx.deviceAccess` call refuses a run another member triggered with. */
30
30
  export const DEVICE_ACCESS_NOT_OWNER_TEXT = "Browser tools only run for the conversation's owner on their own device.";
@@ -50,16 +50,26 @@ const REFRESH_TIMEOUT_MS = 30_000;
50
50
  */
51
51
  function launchArgv(spec, status) {
52
52
  const env = Object.entries(spec.env ?? {}).map(([k, v]) => `${k}=${v}`);
53
+ return [
54
+ ...(env.length > 0 ? ["env", ...env] : []),
55
+ "node",
56
+ launchEntry(spec, status),
57
+ ...spec.args,
58
+ ];
59
+ }
60
+ /** The absolute entry a launch runs: `<codeDir ?? stateDir>/<entry>`. */
61
+ function launchEntry(spec, status) {
53
62
  const dir = status.codeDir ?? status.stateDir;
54
- const entry = `${dir.replace(/\/+$/, "")}/${spec.entry}`;
55
- return [...(env.length > 0 ? ["env", ...env] : []), "node", entry, ...spec.args];
63
+ return `${dir.replace(/\/+$/, "")}/${spec.entry}`;
56
64
  }
57
65
  /** A POSIX shell word for the review's command text (bare when it needs no quoting). */
58
66
  const shellWord = (s) => /^[A-Za-z0-9_@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
59
67
  /**
60
68
  * `ctx.deviceAccess` (browser use spec §7): an extension's device services in the conversation's
61
69
  * device, limited to the conversation's owner on their own personal device and to the service
62
- * names the extension's approved manifest declares. A service launch passes the command review
70
+ * names the extension's approved manifest declares. The provider sees each service by its id
71
+ * (`<extension>.<name>`, `deviceServiceId`), so two extensions declaring the same name never
72
+ * reach each other's process; the extension sees only its own names. A service launch passes the command review
63
73
  * (fail closed: only `allow` starts it), once per start; requests ride the provider's request
64
74
  * path; refused hosts land in the call scope for the pipeline's network ask; viewer tickets are
65
75
  * single-use Redis records; the allowlist write and the handoff answer go through the device page's
@@ -104,9 +114,19 @@ let DeviceAccessService = class DeviceAccessService {
104
114
  * on the call (the call scope) and a start is audited `device.service_started`.
105
115
  */
106
116
  async ensureService(caller, call, spec) {
117
+ // a timeout while this runs says the device was still starting (the tool pipeline's text)
118
+ return whileDeviceStarting(call, () => this.ensureServiceNow(caller, call, spec));
119
+ }
120
+ async ensureServiceNow(caller, call, spec) {
107
121
  assertDeclared(caller, spec.name);
108
122
  assertCallOwner(call);
109
- assertServiceSpec(spec);
123
+ const name = spec.name;
124
+ // the provider gets the service by its id: the extension's name, namespaced
125
+ const providerSpec = {
126
+ ...spec,
127
+ name: deviceServiceId(caller.extension, name),
128
+ };
129
+ assertServiceSpec(providerSpec);
110
130
  const scope = callScopeOf(call);
111
131
  const facts = scope?.facts;
112
132
  if (scope === null || facts === undefined)
@@ -114,7 +134,7 @@ let DeviceAccessService = class DeviceAccessService {
114
134
  const use = await this.callUse(call, facts.rootConversationId, scope);
115
135
  const ensure = async (ifRunning) => {
116
136
  try {
117
- return await this.services.ensure(use, spec, call.signal, { ifRunning });
137
+ return asNamed(await this.services.ensure(use, providerSpec, call.signal, { ifRunning }), name);
118
138
  }
119
139
  catch (e) {
120
140
  throw refusal(e);
@@ -135,6 +155,8 @@ let DeviceAccessService = class DeviceAccessService {
135
155
  accountId: call.accountId,
136
156
  toolKey: "Bash",
137
157
  input: { command: argv.map(shellWord).join(" ") },
158
+ // the kernel's own fact: this command is the extension's declared service (`allow.service`)
159
+ serviceEntry: launchEntry(spec, found),
138
160
  mode: reviewFacts.mode,
139
161
  // the command runs in the service's state directory
140
162
  workspace: found.stateDir,
@@ -167,7 +189,7 @@ let DeviceAccessService = class DeviceAccessService {
167
189
  scope.review = record;
168
190
  // fail closed: an ask has nobody to answer it here, and a deny is a deny
169
191
  if (!allowed)
170
- throw new ToolError(`The device service ${spec.name} was not started: the command review did not allow its launch (${verdict.reason}). Ask the user to check the device's settings.`);
192
+ throw new ToolError(`The device service ${name} was not started: the command review did not allow its launch (${verdict.reason}). Ask the user to check the device's settings.`);
171
193
  // another call may have started it since the first look (that call audits its own start):
172
194
  // found running now, this call started nothing and audits nothing
173
195
  const raced = await ensure(true);
@@ -185,7 +207,8 @@ let DeviceAccessService = class DeviceAccessService {
185
207
  target: use.deviceId,
186
208
  detail: {
187
209
  extension: caller.extension,
188
- service: spec.name,
210
+ service: name,
211
+ serviceId: providerSpec.name,
189
212
  deviceId: use.deviceId,
190
213
  argv,
191
214
  decision: record.decision,
@@ -201,8 +224,10 @@ let DeviceAccessService = class DeviceAccessService {
201
224
  const scope = callScopeOf(call) ?? attachCallScope(call);
202
225
  const root = scope.facts?.rootConversationId ?? (await this.rootOf(call.conversationId));
203
226
  const use = await this.callUse(call, root, scope);
227
+ // from here the service may act: a timeout of this call never says nothing was sent
228
+ scope.reached = true;
204
229
  try {
205
- return await this.services.request(use, req.service, req.body, req.timeoutMs, call.signal);
230
+ return await this.services.request(use, deviceServiceId(caller.extension, req.service), req.body, req.timeoutMs, call.signal);
206
231
  }
207
232
  catch (e) {
208
233
  throw refusal(e);
@@ -321,7 +346,7 @@ let DeviceAccessService = class DeviceAccessService {
321
346
  };
322
347
  for (const name of caller.services) {
323
348
  try {
324
- await this.services.refresh(use, name, AbortSignal.timeout(REFRESH_TIMEOUT_MS));
349
+ await this.services.refresh(use, deviceServiceId(caller.extension, name), AbortSignal.timeout(REFRESH_TIMEOUT_MS));
325
350
  }
326
351
  catch (err) {
327
352
  this.log.warn("device service not refreshed after an allowlist change", {
@@ -454,6 +479,10 @@ DeviceAccessService = __decorate([
454
479
  __param(11, Inject(ExtensionRegistry))
455
480
  ], DeviceAccessService);
456
481
  export { DeviceAccessService };
482
+ /** A provider's status under the extension's own service name (the provider names the id). */
483
+ function asNamed(status, name) {
484
+ return { ...status, name };
485
+ }
457
486
  function assertDeclared(caller, service) {
458
487
  if (!caller.services.includes(service))
459
488
  throw new DeviceAccessError("service_not_declared", `The device service ${JSON.stringify(service)} is not declared in permissions.deviceAccess.services of ${caller.extension}.`);
@@ -8,7 +8,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { createHmac, timingSafeEqual } from "node:crypto";
11
- import { DeviceAccessError, isDeviceOfflineError, } from "@capybara-hq/plugin-sdk";
11
+ import { DeviceAccessError, deviceServiceId, isDeviceOfflineError, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import WebSocket, {} from "ws";
14
14
  import { DialInGateway } from "../dial-in/gateway.js";
@@ -669,7 +669,8 @@ let DeviceStreamViewers = class DeviceStreamViewers {
669
669
  }
670
670
  let stream;
671
671
  try {
672
- stream = await hold.p.openStream(hold.h, { service: record.service }, hold.signal);
672
+ // the provider knows the service by its id: the ticket's extension and service name
673
+ stream = await hold.p.openStream(hold.h, { service: deviceServiceId(record.extension, record.service) }, hold.signal);
673
674
  }
674
675
  catch (err) {
675
676
  await hold.release();
@@ -94,6 +94,8 @@ declare class DeviceConnection {
94
94
  readonly connectionId: `${string}-${string}-${string}-${string}-${string}`;
95
95
  /** The negotiated capacity: the smaller of the machine's and the kernel's frame limits. */
96
96
  private effectiveCap;
97
+ /** The hello offered binary `stream-data` (the ready agrees): both sides send it binary. */
98
+ private binaryStreamData;
97
99
  /** The program run the hello named (`programRunId`), published with the capacity. */
98
100
  private programRunId;
99
101
  private ready;
@@ -118,6 +120,11 @@ declare class DeviceConnection {
118
120
  private inOrg;
119
121
  start(): void;
120
122
  private arm;
123
+ /**
124
+ * A binary message: only `stream-data`, only after a ready that agreed on binary stream data,
125
+ * within the negotiated capacity. It goes to this socket's stream table like its JSON form.
126
+ */
127
+ private onBinary;
121
128
  private onFrame;
122
129
  /**
123
130
  * The accepted hello: claims the lease, records the program facts, then asks the provider
@@ -9,7 +9,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
9
9
  };
10
10
  import { randomUUID } from "node:crypto";
11
11
  import { hostname } from "node:os";
12
- import { DeviceOfflineError, DIAL_IN_PROTOCOL_RE, DialInStreamElsewhereError, parseDialInMachineFrame, } from "@capybara-hq/plugin-sdk";
12
+ import { DeviceOfflineError, DIAL_IN_PROTOCOL_RE, DialInStreamElsewhereError, decodeDialInStreamData, parseDialInMachineFrame, } from "@capybara-hq/plugin-sdk";
13
13
  import { Inject, Injectable } from "@nestjs/common";
14
14
  import { KernelConfigService } from "../infra/config/kernel-config.service.js";
15
15
  import { asPlatform, withOrgScope, withoutOrgScope } from "../infra/database/org-scope.js";
@@ -200,13 +200,15 @@ class DeviceConnection {
200
200
  this.protocol = protocol;
201
201
  this.localPort = localPort;
202
202
  this.streams = new DialInStreams(identity.deviceId, {
203
- send: (text) => {
203
+ send: (frame) => {
204
204
  if (this.state === "closed" || this.socket.readyState !== this.socket.OPEN)
205
205
  return false;
206
- this.socket.send(text);
206
+ // a Uint8Array goes as a binary message: only binary stream-data, once agreed
207
+ this.socket.send(frame);
207
208
  return true;
208
209
  },
209
210
  maxFrameBytes: () => this.effectiveCap ?? 0,
211
+ binaryStreamData: () => this.binaryStreamData,
210
212
  }, () => this.gw.streamOpenTimeoutMs);
211
213
  }
212
214
  /** This connection's streams (the socket's own state, ended with it). */
@@ -218,6 +220,8 @@ class DeviceConnection {
218
220
  connectionId = randomUUID();
219
221
  /** The negotiated capacity: the smaller of the machine's and the kernel's frame limits. */
220
222
  effectiveCap;
223
+ /** The hello offered binary `stream-data` (the ready agrees): both sides send it binary. */
224
+ binaryStreamData = false;
221
225
  /** The program run the hello named (`programRunId`), published with the capacity. */
222
226
  programRunId;
223
227
  ready = false;
@@ -286,7 +290,7 @@ class DeviceConnection {
286
290
  return;
287
291
  this.traffic();
288
292
  if (isBinary) {
289
- this.close(DEVICE_CLOSE.protocol, "frames are JSON text");
293
+ void this.inOrg(() => this.onBinary(data));
290
294
  return;
291
295
  }
292
296
  const text = Array.isArray(data)
@@ -300,6 +304,39 @@ class DeviceConnection {
300
304
  void this.inOrg(() => this.shutdown());
301
305
  });
302
306
  }
307
+ /**
308
+ * A binary message: only `stream-data`, only after a ready that agreed on binary stream data,
309
+ * within the negotiated capacity. It goes to this socket's stream table like its JSON form.
310
+ */
311
+ async onBinary(data) {
312
+ const bytes = Array.isArray(data)
313
+ ? Buffer.concat(data)
314
+ : Buffer.isBuffer(data)
315
+ ? data
316
+ : Buffer.from(data);
317
+ if (!this.ready || !this.binaryStreamData) {
318
+ this.close(DEVICE_CLOSE.protocol, "frames are JSON text");
319
+ return;
320
+ }
321
+ let decoded;
322
+ try {
323
+ if (this.effectiveCap === undefined || bytes.byteLength > this.effectiveCap)
324
+ throw new Error(`frame exceeds ${this.effectiveCap ?? 0} bytes`);
325
+ // like a JSON frame: a capacity lowered since the hello ends the connection
326
+ if (this.gw.maxFrameBytes() < this.effectiveCap)
327
+ throw new Error("Frame capacity changed; reconnect");
328
+ decoded = decodeDialInStreamData(new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength));
329
+ }
330
+ catch (e) {
331
+ this.gw.log.warn("device sent an invalid frame", {
332
+ deviceId: this.deviceId,
333
+ error: errMsg(e),
334
+ });
335
+ this.close(DEVICE_CLOSE.protocol, "invalid frame");
336
+ return;
337
+ }
338
+ this.streams.onData(decoded.streamId, decoded.data);
339
+ }
303
340
  async onFrame(text) {
304
341
  let frame;
305
342
  try {
@@ -328,6 +365,7 @@ class DeviceConnection {
328
365
  }
329
366
  // the machine's announced limit never raises the kernel's own
330
367
  this.effectiveCap = Math.min(frame.transport.maxFrameBytes, this.gw.maxFrameBytes());
368
+ this.binaryStreamData = frame.transport.binaryStreamData === true;
331
369
  if (this.effectiveCap < 1024 || Buffer.byteLength(text) > this.effectiveCap) {
332
370
  this.close(DEVICE_CLOSE.protocol, "Check frame limits: hello cannot fit");
333
371
  return;
@@ -594,6 +632,7 @@ class DeviceConnection {
594
632
  type: "ready",
595
633
  connectionId: this.connectionId,
596
634
  maxFrameBytes: this.effectiveCap ?? 0,
635
+ ...(this.binaryStreamData && { binaryStreamData: true }),
597
636
  };
598
637
  const raw = JSON.stringify(ready);
599
638
  if (this.effectiveCap === undefined || Buffer.byteLength(raw) > this.effectiveCap)
@@ -23,6 +23,18 @@ export declare class DialInConnectionChangedError extends Error {
23
23
  export declare class DialInFrameTooLargeError extends Error {
24
24
  constructor(maxFrameBytes: number);
25
25
  }
26
+ /**
27
+ * The least a caller waits past the request's deadline while the machine stays connected (the
28
+ * machine answers an elapsed deadline itself; this covers the trip back). Never less than the
29
+ * device lease TTL, so a dead holder's lease cannot end the wait before another replica could
30
+ * take the machine over, and never more than the reconnect grace ({@link answerMarginMs}).
31
+ */
32
+ export declare const RELAY_ANSWER_MARGIN_MS = 10000;
33
+ /**
34
+ * The answer margin for a reconnect grace of `graceMs` and a device lease TTL of `leaseTtlMs`:
35
+ * the larger of {@link RELAY_ANSWER_MARGIN_MS} and the lease TTL, capped at the grace.
36
+ */
37
+ export declare const answerMarginMs: (graceMs: number, leaseTtlMs?: number) => number;
26
38
  /** The longest one lease check of a waiting caller may take before it counts as "unknown". */
27
39
  export declare const LEASE_CHECK_TIMEOUT_MS = 2000;
28
40
  /** How often a waiting caller checks that a replica still holds the machine's connection. */
@@ -62,9 +74,11 @@ export interface DialInRequestOptions {
62
74
  *
63
75
  * The caller subscribes to its result topic before pushing and reads the result key once after,
64
76
  * and once more before giving up (the run-abort pattern; a publish lost while the subscriber
65
- * reconnects is still found). It waits within its own call for at most `timeoutMs` plus
66
- * `devices.dialIn.reconnectGraceSeconds`; when the lease disappears meanwhile (checked every
67
- * {@link HOLDER_POLL_MS}) the wait ends at most one grace later ({@link DeviceOfflineError}), and
77
+ * reconnects is still found). While the machine stays connected it waits within its own call for
78
+ * `timeoutMs` plus a short answer margin ({@link answerMarginMs}; then
79
+ * {@link DialInAnswerTimeoutError}); `devices.dialIn.reconnectGraceSeconds` applies only once the
80
+ * lease disappears (checked every {@link HOLDER_POLL_MS}): the wait then ends at most one grace
81
+ * later ({@link DeviceOfflineError}), never later than `timeoutMs` plus the grace, and
68
82
  * when the machine is connected again as another run of its program (`programRunId`) it ends at
69
83
  * that poll with {@link DeviceProgramRestartedError}: the old run's kept results died with it. A
70
84
  * result produced while the machine was disconnected arrives after it reconnects. Giving up (grace,
@@ -78,7 +92,9 @@ export declare class DialInRelay {
78
92
  private readonly config;
79
93
  private readonly log;
80
94
  private readonly targets;
81
- constructor(redis: Redis, bus: ExtensionContext["bus"], locks: Pick<LockService, "holderOf">, config: Pick<KernelConfigService, "get">, log: Pick<KernelLogger, "warn">, targets: Pick<DeviceTargets, "state" | "current">);
95
+ constructor(redis: Redis, bus: ExtensionContext["bus"], locks: Pick<LockService, "holderOf">, config: Pick<KernelConfigService, "get">, log: Pick<KernelLogger, "warn" | "info">, targets: Pick<DeviceTargets, "state" | "current">);
96
+ /** Test seam: the answer margin in ms instead of {@link answerMarginMs} (null: computed). */
97
+ answerMarginOverrideMs: number | null;
82
98
  /** Whether a gateway replica holds the machine's connection now. */
83
99
  online(deviceId: string): Promise<boolean>;
84
100
  /**
@@ -111,7 +127,8 @@ export declare class DialInRelay {
111
127
  /**
112
128
  * Sends `body` to the device's machine as the body of a `req` and resolves the body of its `res`
113
129
  * (never read here). Throws {@link DeviceOfflineError} when no replica holds the machine at send
114
- * time or when the wait ran out, but `device.forbidden` ({@link machineRevoked}) when the machine
130
+ * time or when it stayed disconnected past the grace, {@link DialInAnswerTimeoutError} when the
131
+ * connected machine did not answer in time, but `device.forbidden` ({@link machineRevoked}) when the machine
115
132
  * was revoked and `device.not_found` when the device was deleted (checked whenever the
116
133
  * connection is missing, ruling R27); {@link DeviceRequestNotSentError} when the request never
117
134
  * reached the machine (its connection changed first), {@link DialInFrameTooLargeError} when it
@@ -129,10 +146,15 @@ export declare class DialInRelay {
129
146
  /** The error of a state that never comes back; undefined for `active` or unknown. */
130
147
  private goneError;
131
148
  private graceMs;
149
+ private marginMs;
132
150
  private push;
133
151
  /** Announces new frames to the holder; a lost nudge is picked up on the holder's next drain. */
134
152
  private nudge;
135
153
  /** Removes the request from the list, or queues a cancel when the machine took it (R15). */
154
+ /**
155
+ * Gives the request up ({@link GIVE_UP}): `removed` when it was still queued (never sent),
156
+ * `cancelled` when the machine had taken it (a cancel queued), `unknown` when Redis failed.
157
+ */
136
158
  private giveUp;
137
159
  /** Runs a side step whose failure must not replace the call's outcome: logged, swallowed. */
138
160
  private quietly;
@@ -8,7 +8,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { randomUUID } from "node:crypto";
11
- import { DeviceOfflineError } from "@capybara-hq/plugin-sdk";
11
+ import { DeviceOfflineError, DialInAnswerTimeoutError, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
13
  import { deviceNotFound, machineRevoked } from "../devices/errors.js";
14
14
  import { ApiError } from "../errors.js";
@@ -41,6 +41,18 @@ export class DialInFrameTooLargeError extends Error {
41
41
  this.name = "DialInFrameTooLargeError";
42
42
  }
43
43
  }
44
+ /**
45
+ * The least a caller waits past the request's deadline while the machine stays connected (the
46
+ * machine answers an elapsed deadline itself; this covers the trip back). Never less than the
47
+ * device lease TTL, so a dead holder's lease cannot end the wait before another replica could
48
+ * take the machine over, and never more than the reconnect grace ({@link answerMarginMs}).
49
+ */
50
+ export const RELAY_ANSWER_MARGIN_MS = 10_000;
51
+ /**
52
+ * The answer margin for a reconnect grace of `graceMs` and a device lease TTL of `leaseTtlMs`:
53
+ * the larger of {@link RELAY_ANSWER_MARGIN_MS} and the lease TTL, capped at the grace.
54
+ */
55
+ export const answerMarginMs = (graceMs, leaseTtlMs = 0) => Math.min(graceMs, Math.max(RELAY_ANSWER_MARGIN_MS, leaseTtlMs));
44
56
  /** The longest one lease check of a waiting caller may take before it counts as "unknown". */
45
57
  export const LEASE_CHECK_TIMEOUT_MS = 2000;
46
58
  /** How often a waiting caller checks that a replica still holds the machine's connection. */
@@ -80,6 +92,7 @@ return 1
80
92
  /** Why a call stopped waiting without a result. */
81
93
  const ABORTED = Symbol("aborted");
82
94
  const GRACE_EXPIRED = Symbol("grace expired");
95
+ const ANSWER_OVERDUE = Symbol("answer overdue");
83
96
  const errMsg = (e) => (e instanceof Error ? e.message : String(e));
84
97
  /**
85
98
  * The caller side of the dial-in relay (environments spec §13.4), for every provider serving its
@@ -93,9 +106,11 @@ const errMsg = (e) => (e instanceof Error ? e.message : String(e));
93
106
  *
94
107
  * The caller subscribes to its result topic before pushing and reads the result key once after,
95
108
  * and once more before giving up (the run-abort pattern; a publish lost while the subscriber
96
- * reconnects is still found). It waits within its own call for at most `timeoutMs` plus
97
- * `devices.dialIn.reconnectGraceSeconds`; when the lease disappears meanwhile (checked every
98
- * {@link HOLDER_POLL_MS}) the wait ends at most one grace later ({@link DeviceOfflineError}), and
109
+ * reconnects is still found). While the machine stays connected it waits within its own call for
110
+ * `timeoutMs` plus a short answer margin ({@link answerMarginMs}; then
111
+ * {@link DialInAnswerTimeoutError}); `devices.dialIn.reconnectGraceSeconds` applies only once the
112
+ * lease disappears (checked every {@link HOLDER_POLL_MS}): the wait then ends at most one grace
113
+ * later ({@link DeviceOfflineError}), never later than `timeoutMs` plus the grace, and
99
114
  * when the machine is connected again as another run of its program (`programRunId`) it ends at
100
115
  * that poll with {@link DeviceProgramRestartedError}: the old run's kept results died with it. A
101
116
  * result produced while the machine was disconnected arrives after it reconnects. Giving up (grace,
@@ -117,6 +132,8 @@ let DialInRelay = class DialInRelay {
117
132
  this.log = log;
118
133
  this.targets = targets;
119
134
  }
135
+ /** Test seam: the answer margin in ms instead of {@link answerMarginMs} (null: computed). */
136
+ answerMarginOverrideMs = null;
120
137
  /** Whether a gateway replica holds the machine's connection now. */
121
138
  async online(deviceId) {
122
139
  return (await this.locks.holderOf(deviceLeaseKey(deviceId))) !== null;
@@ -167,7 +184,8 @@ let DialInRelay = class DialInRelay {
167
184
  /**
168
185
  * Sends `body` to the device's machine as the body of a `req` and resolves the body of its `res`
169
186
  * (never read here). Throws {@link DeviceOfflineError} when no replica holds the machine at send
170
- * time or when the wait ran out, but `device.forbidden` ({@link machineRevoked}) when the machine
187
+ * time or when it stayed disconnected past the grace, {@link DialInAnswerTimeoutError} when the
188
+ * connected machine did not answer in time, but `device.forbidden` ({@link machineRevoked}) when the machine
171
189
  * was revoked and `device.not_found` when the device was deleted (checked whenever the
172
190
  * connection is missing, ruling R27); {@link DeviceRequestNotSentError} when the request never
173
191
  * reached the machine (its connection changed first), {@link DialInFrameTooLargeError} when it
@@ -241,12 +259,18 @@ let DialInRelay = class DialInRelay {
241
259
  await this.push(deviceId, reqJson, listTtlMs);
242
260
  this.nudge(deviceId, id);
243
261
  onStored(await this.redis.get(deviceResKey(id)));
244
- // wait until the result, the abort, or `giveUpAt`. The lease is checked every poll: its loss
245
- // caps `giveUpAt` at one grace from then (never extending it); a reconnect within that grace
246
- // restores the full wait, so a long command whose machine blipped keeps its deadline
247
- const fullGiveUpAt = Date.now() + deadlineMs + graceMs;
248
- let giveUpAt = fullGiveUpAt;
249
- let capped = false;
262
+ // wait until the result, the abort, or `giveUpAt`. While the machine stays connected that is
263
+ // the deadline plus a short answer margin (the machine answers an elapsed deadline itself);
264
+ // the reconnect grace applies only while no replica holds the machine: its loss caps the
265
+ // wait at one grace from then (never extending the old deadline-plus-grace bound), and a
266
+ // reconnect restores the connected bound, at least a margin after the reconnect (a result
267
+ // produced while it was away is delivered then). Checked every poll.
268
+ const startedAt = Date.now();
269
+ const marginMs = this.marginMs();
270
+ const connectedGiveUpAt = startedAt + deadlineMs + marginMs;
271
+ const latestGiveUpAt = startedAt + deadlineMs + graceMs;
272
+ let giveUpAt = connectedGiveUpAt;
273
+ let lostAt = null;
250
274
  const tick = async () => {
251
275
  if (stopped)
252
276
  return;
@@ -275,13 +299,13 @@ let DialInRelay = class DialInRelay {
275
299
  return;
276
300
  }
277
301
  }
278
- if (live === true && capped) {
279
- capped = false;
280
- giveUpAt = fullGiveUpAt;
302
+ if (live === true && lostAt !== null) {
303
+ lostAt = null;
304
+ giveUpAt = Math.max(connectedGiveUpAt, Date.now() + marginMs);
281
305
  }
282
- else if (live === false && !capped) {
283
- capped = true;
284
- giveUpAt = Math.min(giveUpAt, Date.now() + graceMs);
306
+ else if (live === false && lostAt === null) {
307
+ lostAt = Date.now();
308
+ giveUpAt = Math.min(latestGiveUpAt, lostAt + graceMs);
285
309
  }
286
310
  if (live === false) {
287
311
  // a revoked machine or a deleted device never comes back: fail at once
@@ -299,7 +323,8 @@ let DialInRelay = class DialInRelay {
299
323
  return;
300
324
  if (Date.now() >= giveUpAt) {
301
325
  // a last look at the key: the publish may have been lost while the subscriber reconnected
302
- this.redis.get(deviceResKey(id)).then((raw) => (raw !== null ? onStored(raw) : settle({ error: GRACE_EXPIRED })), () => settle({ error: GRACE_EXPIRED }));
326
+ const why = lostAt === null ? ANSWER_OVERDUE : GRACE_EXPIRED;
327
+ this.redis.get(deviceResKey(id)).then((raw) => (raw !== null ? onStored(raw) : settle({ error: why })), () => settle({ error: why }));
303
328
  return;
304
329
  }
305
330
  schedule();
@@ -326,11 +351,35 @@ let DialInRelay = class DialInRelay {
326
351
  // a bad answer: drop it, give the request up, report the error
327
352
  await this.quietly("delete the result", deviceId, () => this.redis.del(deviceResKey(id)));
328
353
  }
329
- await this.giveUp(deviceId, id, reqJson, listTtlMs);
330
- if (r.error === ABORTED)
354
+ const left = await this.giveUp(deviceId, id, reqJson, listTtlMs);
355
+ if (r.error === ABORTED) {
356
+ this.log.info("device relay wait aborted", { deviceId, waitedMs: Date.now() - startedAt });
331
357
  throw signal.reason;
332
- if (r.error === GRACE_EXPIRED)
358
+ }
359
+ if (r.error === GRACE_EXPIRED) {
360
+ this.log.warn("device relay gave up: the machine stayed disconnected past the grace", {
361
+ deviceId,
362
+ waitedMs: Date.now() - startedAt,
363
+ });
333
364
  throw new DeviceOfflineError(deviceId);
365
+ }
366
+ if (r.error === ANSWER_OVERDUE && left === "removed") {
367
+ // still on the list when given up: the machine never took it, nothing ran
368
+ this.log.warn("device relay gave up: the connected machine never took the request", {
369
+ deviceId,
370
+ deadlineMs,
371
+ waitedMs: Date.now() - startedAt,
372
+ });
373
+ throw new DeviceRequestNotSentError("The connected machine did not take the request within its deadline; nothing ran, retry it");
374
+ }
375
+ if (r.error === ANSWER_OVERDUE) {
376
+ this.log.warn("device relay gave up: the connected machine did not answer in time", {
377
+ deviceId,
378
+ deadlineMs,
379
+ waitedMs: Date.now() - startedAt,
380
+ });
381
+ throw new DialInAnswerTimeoutError(deadlineMs);
382
+ }
334
383
  throw r.error;
335
384
  }
336
385
  finally {
@@ -395,6 +444,12 @@ let DialInRelay = class DialInRelay {
395
444
  graceMs() {
396
445
  return this.config.get().devices.dialIn.reconnectGraceSeconds * 1000;
397
446
  }
447
+ marginMs() {
448
+ if (this.answerMarginOverrideMs !== null)
449
+ return this.answerMarginOverrideMs;
450
+ const d = this.config.get().devices.dialIn;
451
+ return answerMarginMs(d.reconnectGraceSeconds * 1000, d.leaseTtlMs ?? 0);
452
+ }
398
453
  async push(deviceId, frame, ttlMs) {
399
454
  await this.redis.eval(PUSH_WITH_TTL, 1, deviceReqKey(deviceId), frame, String(ttlMs));
400
455
  }
@@ -405,13 +460,20 @@ let DialInRelay = class DialInRelay {
405
460
  });
406
461
  }
407
462
  /** Removes the request from the list, or queues a cancel when the machine took it (R15). */
463
+ /**
464
+ * Gives the request up ({@link GIVE_UP}): `removed` when it was still queued (never sent),
465
+ * `cancelled` when the machine had taken it (a cancel queued), `unknown` when Redis failed.
466
+ */
408
467
  async giveUp(deviceId, id, reqJson, ttlMs) {
409
468
  const cancel = { type: "cancel", id };
469
+ let left = "unknown";
410
470
  await this.quietly("give the request up", deviceId, async () => {
411
471
  const queued = await this.redis.eval(GIVE_UP, 1, deviceReqKey(deviceId), reqJson, JSON.stringify(cancel), String(ttlMs));
472
+ left = queued === 1 ? "cancelled" : "removed";
412
473
  if (queued === 1)
413
474
  this.nudge(deviceId, id);
414
475
  });
476
+ return left;
415
477
  }
416
478
  /** Runs a side step whose failure must not replace the call's outcome: logged, swallowed. */
417
479
  async quietly(what, deviceId, fn) {
@@ -1,7 +1,7 @@
1
1
  import { type DeviceStream, type DialInMachineFrame } from "@capybara-hq/plugin-sdk";
2
2
  /**
3
3
  * The `code` of the error a stream's `send` rejects with when a message does not fit one frame
4
- * once base64-encoded (the viewer endpoint answers it with 1009).
4
+ * (base64-encoded, or binary with its header; the viewer endpoint answers it with 1009).
5
5
  */
6
6
  export declare const DEVICE_STREAM_MESSAGE_TOO_BIG = "device.stream_message_too_big";
7
7
  /** The stream frames a machine sends ({@link DialInStreams.onFrame}). */
@@ -12,10 +12,15 @@ export type DialInMachineStreamFrame = Extract<DialInMachineFrame, {
12
12
  export declare function isStreamFrame(frame: DialInMachineFrame): frame is DialInMachineStreamFrame;
13
13
  /** What a connection's stream table needs from its socket. */
14
14
  export interface DialInStreamTransport {
15
- /** Sends one frame's text on the socket; false when the socket is no longer open. */
16
- send(text: string): boolean;
17
- /** The connection's negotiated frame capacity in UTF-8 bytes. */
15
+ /**
16
+ * Sends one frame on the socket: JSON text, or a binary `stream-data` message; false when the
17
+ * socket is no longer open.
18
+ */
19
+ send(frame: string | Uint8Array): boolean;
20
+ /** The connection's negotiated frame capacity in bytes. */
18
21
  maxFrameBytes(): number;
22
+ /** Whether hello and ready agreed on binary `stream-data` ({@link encodeDialInStreamData}). */
23
+ binaryStreamData(): boolean;
19
24
  }
20
25
  /** The reason every stream of a connection ends with when its socket closes. */
21
26
  export declare const STREAM_OFFLINE_REASON = "device-offline";
@@ -26,7 +31,8 @@ export declare const STREAM_OPEN_TIMEOUT_MS = 15000;
26
31
  * spec §6.1): opened with `stream-open`, carried as `stream-data` frames straight over the socket
27
32
  * (never through Redis or PG), each side sending only while it holds credit
28
33
  * ({@link DIAL_IN_STREAM_INITIAL_CREDIT} at the open, one more per message the other side
29
- * consumed). A data frame carries one whole message in base64; a message that does not fit the
34
+ * consumed). A data frame carries one whole message, in base64 inside JSON or, when hello and
35
+ * ready agreed on it, as a binary message (raw bytes); a message that does not fit the
30
36
  * connection's frame capacity is refused, never split. The table is the connection's own state and
31
37
  * lives exactly as long as the socket: its close ends every stream with
32
38
  * {@link STREAM_OFFLINE_REASON}.
@@ -53,6 +59,8 @@ export declare class DialInStreams {
53
59
  openStream(body: unknown, signal: AbortSignal): Promise<DeviceStream>;
54
60
  /** A stream frame from the machine; a frame of a stream that is not open is dropped. */
55
61
  onFrame(frame: DialInMachineStreamFrame): void;
62
+ /** A binary `stream-data` message from the machine; one of a stream not open is dropped. */
63
+ onData(streamId: string, data: Uint8Array): void;
56
64
  /** The socket closed: every stream ends, every opening fails. */
57
65
  closeAll(): void;
58
66
  }