@capybara-hq/kernel 0.1.0-rc.139 → 0.1.0-rc.140

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.
@@ -209,7 +209,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
209
209
  /** The host versions (an entry's `minKernel` is judged against them). */
210
210
  export declare const HOST_VERSIONS: {
211
211
  readonly kernel: string;
212
- readonly sdk: "0.1.0-rc.100";
212
+ readonly sdk: "0.1.0-rc.101";
213
213
  };
214
214
  /** Whether this deployment satisfies the entry's `minKernel`. */
215
215
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -365,8 +365,9 @@ export declare class ConversationsController {
365
365
  /**
366
366
  * The person's answer to a local agent's request (`external_request`, local agents spec Part 2,
367
367
  * call 8): 202 `{ event }`, the `external_request_answered` written once (the first answer wins;
368
- * a second → 409 `conversation.request_answered`) and the target's `answer` owed. An unknown
369
- * request → 404 `conversation.request_not_found`; an option it does not offer → 400.
368
+ * a second → 409 `conversation.request_answered`; one the target closed → 409
369
+ * `conversation.request_closed`) and the target's `answer` owed. An unknown request → 404
370
+ * `conversation.request_not_found`; an option it does not offer → 400.
370
371
  */
371
372
  answerExternal(principal: Principal, org: OrgContext, params: z.infer<typeof ExternalRequestParams>, body: z.infer<typeof ExternalAnswerBody>): Promise<{
372
373
  event: ConversationEvent;
@@ -602,8 +602,9 @@ let ConversationsController = class ConversationsController {
602
602
  /**
603
603
  * The person's answer to a local agent's request (`external_request`, local agents spec Part 2,
604
604
  * call 8): 202 `{ event }`, the `external_request_answered` written once (the first answer wins;
605
- * a second → 409 `conversation.request_answered`) and the target's `answer` owed. An unknown
606
- * request → 404 `conversation.request_not_found`; an option it does not offer → 400.
605
+ * a second → 409 `conversation.request_answered`; one the target closed → 409
606
+ * `conversation.request_closed`) and the target's `answer` owed. An unknown request → 404
607
+ * `conversation.request_not_found`; an option it does not offer → 400.
607
608
  */
608
609
  async answerExternal(principal, org, params, body) {
609
610
  const p = requireUser(principal);
@@ -2224,6 +2224,16 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
2224
2224
  optionId: z.ZodString;
2225
2225
  byAccountId: z.ZodString;
2226
2226
  }, z.core.$strip>;
2227
+ }, z.core.$strip>, z.ZodObject<{
2228
+ type: z.ZodLiteral<"external_request_closed">;
2229
+ payload: z.ZodObject<{
2230
+ requestId: z.ZodString;
2231
+ reason: z.ZodEnum<{
2232
+ cancelled: "cancelled";
2233
+ expired: "expired";
2234
+ superseded: "superseded";
2235
+ }>;
2236
+ }, z.core.$strip>;
2227
2237
  }, z.core.$strip>, z.ZodObject<{
2228
2238
  type: z.ZodLiteral<"external_turn">;
2229
2239
  payload: z.ZodObject<{
@@ -2057,6 +2057,15 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
2057
2057
  optionId: z.string().regex(EXTERNAL_OPTION_ID_RE),
2058
2058
  byAccountId: z.string(),
2059
2059
  })),
2060
+ /**
2061
+ * The target closed an open `external_request` without an answer (its turn was stopped or
2062
+ * interrupted, its process restarted); later answers are refused. Not model-visible; external
2063
+ * conversations have no runs, no DriftReason.
2064
+ */
2065
+ ev("external_request_closed", z.object({
2066
+ requestId: externalId,
2067
+ reason: z.enum(["cancelled", "expired", "superseded"]),
2068
+ })),
2060
2069
  /**
2061
2070
  * The end of the target's turn: `ended`, or `failed` with the error shown to the person. Not
2062
2071
  * model-visible; external conversations have no runs, no DriftReason.
@@ -152,8 +152,9 @@ export declare class ExternalConversationsService {
152
152
  private sendIn;
153
153
  /**
154
154
  * The person's answer to a target's `external_request`: `external_request_answered` written once
155
- * (a second answer → 409 `conversation.request_answered`), `answer` owed. An unknown request →
156
- * 404 `conversation.request_not_found`; an option it does not offer → 400.
155
+ * (a second answer → 409 `conversation.request_answered`; a request the target closed → 409
156
+ * `conversation.request_closed`), `answer` owed. An unknown request → 404
157
+ * `conversation.request_not_found`; an option it does not offer → 400.
157
158
  */
158
159
  answer(orgId: string, conversationId: string, accountId: string, requestId: string, optionId: string): Promise<ConversationEvent>;
159
160
  private answerIn;
@@ -220,6 +221,11 @@ export declare class ExternalConversationsService {
220
221
  events: unknown;
221
222
  }): Promise<void>;
222
223
  private appendIn;
224
+ /**
225
+ * The request ids the batch's `external_request_closed` events may close: requests already in
226
+ * the log, or appended earlier in the same batch.
227
+ */
228
+ private knownRequests;
223
229
  /**
224
230
  * The owner's personal inbox item for a target's request (local agents spec call 8): a kernel
225
231
  * item of kind `external_request` (title = the request's title, body = its detail, each cut to
@@ -113,6 +113,8 @@ function externalIdemKey(e) {
113
113
  return `external-activity:${e.payload.activityId}:${e.payload.status}`;
114
114
  case "external_request":
115
115
  return `external-request:${e.payload.requestId}`;
116
+ case "external_request_closed":
117
+ return requestResolvedKey(e.payload.requestId);
116
118
  case "external_turn":
117
119
  return undefined;
118
120
  }
@@ -146,13 +148,22 @@ function projectExternal(e) {
146
148
  payload: { requestId, title, ...(detail !== undefined && { detail }), options },
147
149
  };
148
150
  }
151
+ case "external_request_closed": {
152
+ const { requestId, reason } = e.payload;
153
+ return { type: e.type, payload: { requestId, reason } };
154
+ }
149
155
  case "external_turn": {
150
156
  const { state, error } = e.payload;
151
157
  return { type: e.type, payload: { state, ...(error !== undefined && { error }) } };
152
158
  }
153
159
  }
154
160
  }
155
- const answerIdemKey = (requestId) => `external-answer:${requestId}`;
161
+ /**
162
+ * The idempotency key of a request's resolution: shared by `external_request_answered` and
163
+ * `external_request_closed`, so one of them is written per request and the first one stands (an
164
+ * answer after a close is refused, a close after an answer is a no-op).
165
+ */
166
+ const requestResolvedKey = (requestId) => `external-answer:${requestId}`;
156
167
  /** The lock the deliveries of one conversation's messages take turns on (no `:`). */
157
168
  const deliveryLockKey = (conversationId) => `external-calls-${conversationId}`;
158
169
  /** The lifetime of a delivery lock without renewal (renewed while held). */
@@ -539,8 +550,9 @@ let ExternalConversationsService = class ExternalConversationsService {
539
550
  }
540
551
  /**
541
552
  * The person's answer to a target's `external_request`: `external_request_answered` written once
542
- * (a second answer → 409 `conversation.request_answered`), `answer` owed. An unknown request →
543
- * 404 `conversation.request_not_found`; an option it does not offer → 400.
553
+ * (a second answer → 409 `conversation.request_answered`; a request the target closed → 409
554
+ * `conversation.request_closed`), `answer` owed. An unknown request → 404
555
+ * `conversation.request_not_found`; an option it does not offer → 400.
544
556
  */
545
557
  async answer(orgId, conversationId, accountId, requestId, optionId) {
546
558
  await this.writableExternal(orgId, conversationId, accountId);
@@ -569,12 +581,15 @@ let ExternalConversationsService = class ExternalConversationsService {
569
581
  const r = await this.eventLog.appendInReport(conversationId, [
570
582
  {
571
583
  type: "external_request_answered",
572
- idemKey: answerIdemKey(requestId),
584
+ idemKey: requestResolvedKey(requestId),
573
585
  payload: { requestId, optionId, byAccountId: accountId },
574
586
  },
575
587
  ]);
576
- if (r.fresh[0] !== true)
588
+ if (r.fresh[0] !== true) {
589
+ if (r.events[0]?.type === "external_request_closed")
590
+ throw new ApiError("conversation.request_closed", "The request was closed without an answer; it can no longer be answered");
577
591
  throw new ApiError("conversation.request_answered", "The request was already answered");
592
+ }
578
593
  await this.inbox.resolveKernelItem(orgId, accountId, requestItemKey(conversationId, requestId));
579
594
  await this.outbox.add(externalCallJob({ orgId, conversationId, call: "answer", requestId, optionId }));
580
595
  return r.events[0];
@@ -907,18 +922,61 @@ let ExternalConversationsService = class ExternalConversationsService {
907
922
  }
908
923
  async appendIn(extension, orgId, conversationId, events) {
909
924
  const { accountId } = await this.ownRow(extension, orgId, conversationId, true);
910
- const appends = events.map((e) => {
925
+ const known = await this.knownRequests(orgId, conversationId, events);
926
+ const appends = events
927
+ // closing a request the conversation never had is a no-op (one answered already shares the
928
+ // resolution key with its answer, so it is not written either)
929
+ .filter((e) => e.type !== "external_request_closed" || known.has(e.payload.requestId))
930
+ .map((e) => {
911
931
  const idemKey = externalIdemKey(e);
912
932
  return { ...projectExternal(e), ...(idemKey !== undefined && { idemKey }) };
913
933
  });
934
+ if (appends.length === 0)
935
+ return null;
914
936
  const r = await this.eventLog.appendInReport(conversationId, appends);
915
937
  const written = r.events.filter((_, i) => r.fresh[i] === true);
916
- // a new request also reaches the owner's inbox (spec call 8), in the same transaction
917
- for (const e of written)
938
+ // a new request also reaches the owner's inbox (spec call 8), and a closed one leaves it (as
939
+ // an answer does), in the same transaction
940
+ for (const e of written) {
918
941
  if (e.type === "external_request")
919
942
  await this.postRequestItem(orgId, accountId, conversationId, e.payload);
943
+ else if (e.type === "external_request_closed")
944
+ await this.inbox.resolveKernelItem(orgId, accountId, requestItemKey(conversationId, e.payload.requestId));
945
+ }
920
946
  return written.length === 0 ? null : Math.max(...written.map((e) => e.seq));
921
947
  }
948
+ /**
949
+ * The request ids the batch's `external_request_closed` events may close: requests already in
950
+ * the log, or appended earlier in the same batch.
951
+ */
952
+ async knownRequests(orgId, conversationId, events) {
953
+ const known = new Set();
954
+ const asked = new Set();
955
+ const lookup = new Set();
956
+ for (const e of events) {
957
+ if (e.type === "external_request")
958
+ asked.add(e.payload.requestId);
959
+ else if (e.type === "external_request_closed") {
960
+ if (asked.has(e.payload.requestId))
961
+ known.add(e.payload.requestId);
962
+ else
963
+ lookup.add(e.payload.requestId);
964
+ }
965
+ }
966
+ if (lookup.size === 0)
967
+ return known;
968
+ const rows = await this.db
969
+ .selectFrom("conversation_events")
970
+ .select(sql `payload->>'requestId'`.as("requestId"))
971
+ .where("conversation_id", "=", conversationId)
972
+ .where("org_id", "=", orgId)
973
+ .where("type", "=", "external_request")
974
+ .where(sql `payload->>'requestId'`, "in", [...lookup])
975
+ .execute();
976
+ for (const r of rows)
977
+ known.add(r.requestId);
978
+ return known;
979
+ }
922
980
  /**
923
981
  * The owner's personal inbox item for a target's request (local agents spec call 8): a kernel
924
982
  * item of kind `external_request` (title = the request's title, body = its detail, each cut to
@@ -208,4 +208,10 @@ export declare class HostServiceAccess {
208
208
  private assertEnabled;
209
209
  private isMember;
210
210
  }
211
+ /**
212
+ * A provider's `DeviceAccessError` with `code`, matched by name and code, never `instanceof`: a
213
+ * provider may carry its own SDK copy (`host_consent_missing`: the owner has not allowed the
214
+ * service; `capability_missing`: the provider cannot run device services).
215
+ */
216
+ export declare function isProviderRefusal(e: unknown, code: "host_consent_missing" | "capability_missing"): boolean;
211
217
  export {};
@@ -382,7 +382,7 @@ let HostServiceAccess = class HostServiceAccess {
382
382
  // a provider that cannot run device services never will: no retry, the stop stays owed.
383
383
  // Said once per mark: the sweep owes the delivery again every window while the machine
384
384
  // stays connected, and those deliveries log at debug only
385
- if (err instanceof DeviceAccessError && err.code === "capability_missing") {
385
+ if (isProviderRefusal(err, "capability_missing")) {
386
386
  const fields = {
387
387
  extension: r.extension,
388
388
  orgId: r.org_id,
@@ -630,10 +630,13 @@ let HostServiceAccess = class HostServiceAccess {
630
630
  : fn(h, p, sig), a.signal);
631
631
  }
632
632
  catch (e) {
633
- if (isConsentMissing(e))
633
+ if (isProviderRefusal(e, "host_consent_missing"))
634
634
  throw new DeviceAccessError("host_consent_missing", `Allow it on the machine: capybara-device services allow ${caller.extension}.${service}`, { cause: e });
635
635
  if (e instanceof DeviceAccessError)
636
636
  throw e;
637
+ // a provider that cannot run device services, refused with its own SDK copy's class
638
+ if (isProviderRefusal(e, "capability_missing"))
639
+ throw new DeviceAccessError("capability_missing", e.message, { cause: e });
637
640
  throw deviceRefusal(e, this.log);
638
641
  }
639
642
  }
@@ -771,14 +774,15 @@ function requireHostServices(p) {
771
774
  throw new DeviceAccessError("capability_missing", "This device's provider cannot run device services, so it cannot run host services.");
772
775
  }
773
776
  /**
774
- * A provider's refusal of a host start for want of the owner's consent: a `DeviceAccessError`
775
- * with `host_consent_missing`, by name and code (a provider may carry its own SDK copy).
777
+ * A provider's `DeviceAccessError` with `code`, matched by name and code, never `instanceof`: a
778
+ * provider may carry its own SDK copy (`host_consent_missing`: the owner has not allowed the
779
+ * service; `capability_missing`: the provider cannot run device services).
776
780
  */
777
- function isConsentMissing(e) {
781
+ export function isProviderRefusal(e, code) {
778
782
  return (typeof e === "object" &&
779
783
  e !== null &&
780
784
  e.name === "DeviceAccessError" &&
781
- e.code === "host_consent_missing");
785
+ e.code === code);
782
786
  }
783
787
  function notEnabled(extension) {
784
788
  return new DeviceAccessError("capability_missing", `The extension ${extension} is not enabled in the organization.`);
@@ -40,7 +40,11 @@ export declare const CLAIM_RETRY_MS = 250;
40
40
  /**
41
41
  * The most `event` frames a connection may have waiting for the provider (received, not yet
42
42
  * handled): a machine sending faster than its provider handles them is closed (4400) instead of
43
- * growing the gateway's memory.
43
+ * growing the gateway's memory. A host service event (`{ op: "service.event" }`) beyond it is
44
+ * dropped instead, the connection kept: capybara-device keeps every such event until the provider
45
+ * acknowledges it and sends it again, so a dropped one is only late. The device keeps its host
46
+ * service events in flight below the cap (`SERVICE_EVENT_WINDOW`,
47
+ * `packages/device/src/services/host-events.ts`); change both together.
44
48
  */
45
49
  export declare const MAX_EVENTS_IN_FLIGHT = 32;
46
50
  type State = "hello" | "claiming" | "holding" | "closed";
@@ -78,6 +82,8 @@ declare class DeviceConnection {
78
82
  private accepted;
79
83
  /** `event` frames received and not yet handled ({@link MAX_EVENTS_IN_FLIGHT}). */
80
84
  private eventsInFlight;
85
+ /** A host service event beyond the cap was dropped and logged (once per connection). */
86
+ private serviceEventDropWarned;
81
87
  /** Why the connection closed, for the provider's `onClose` (offline unless set). */
82
88
  private closeReason;
83
89
  constructor(gw: DialInGateway, socket: WebSocket, identity: MachineIdentity, credential: string,
@@ -62,7 +62,11 @@ const MAX_PUBLISH_FAILURES = 3;
62
62
  /**
63
63
  * The most `event` frames a connection may have waiting for the provider (received, not yet
64
64
  * handled): a machine sending faster than its provider handles them is closed (4400) instead of
65
- * growing the gateway's memory.
65
+ * growing the gateway's memory. A host service event (`{ op: "service.event" }`) beyond it is
66
+ * dropped instead, the connection kept: capybara-device keeps every such event until the provider
67
+ * acknowledges it and sends it again, so a dropped one is only late. The device keeps its host
68
+ * service events in flight below the cap (`SERVICE_EVENT_WINDOW`,
69
+ * `packages/device/src/services/host-events.ts`); change both together.
66
70
  */
67
71
  export const MAX_EVENTS_IN_FLIGHT = 32;
68
72
  /** How often a held connection re-checks its credential (membership, org, device). */
@@ -154,6 +158,8 @@ const closeReason = (text) => {
154
158
  out = out.slice(0, -1);
155
159
  return out;
156
160
  };
161
+ /** A host service event body (`{ op: "service.event", … }`), which the device sends again. */
162
+ const isServiceEvent = (body) => typeof body === "object" && body !== null && body.op === "service.event";
157
163
  /**
158
164
  * One machine connection on this replica. Its state (the socket, the lease handle, the requests
159
165
  * it forwarded) is the socket's own and lives exactly as long as the socket.
@@ -186,6 +192,8 @@ class DeviceConnection {
186
192
  accepted;
187
193
  /** `event` frames received and not yet handled ({@link MAX_EVENTS_IN_FLIGHT}). */
188
194
  eventsInFlight = 0;
195
+ /** A host service event beyond the cap was dropped and logged (once per connection). */
196
+ serviceEventDropWarned = false;
189
197
  /** Why the connection closed, for the provider's `onClose` (offline unless set). */
190
198
  closeReason = "offline";
191
199
  constructor(gw, socket, identity, credential,
@@ -385,6 +393,16 @@ class DeviceConnection {
385
393
  return;
386
394
  }
387
395
  if (this.eventsInFlight >= MAX_EVENTS_IN_FLIGHT) {
396
+ if (isServiceEvent(frame.body)) {
397
+ // the device keeps it until acknowledged and sends it again: dropping loses nothing
398
+ if (!this.serviceEventDropWarned) {
399
+ this.serviceEventDropWarned = true;
400
+ this.gw.log.warn("device sent more host service events than its provider handles", {
401
+ deviceId: this.deviceId,
402
+ });
403
+ }
404
+ return;
405
+ }
388
406
  this.gw.log.warn("device sent more events than its provider handles", {
389
407
  deviceId: this.deviceId,
390
408
  });
package/dist/errors.d.ts CHANGED
@@ -456,6 +456,8 @@ export declare const ERROR_CODES: {
456
456
  readonly "conversation.request_not_found": 404;
457
457
  /** The request was already answered; the first answer stands. */
458
458
  readonly "conversation.request_answered": 409;
459
+ /** The target closed the request without an answer (`external_request_closed`). */
460
+ readonly "conversation.request_closed": 409;
459
461
  readonly "run.not_active": 409;
460
462
  /** A run that is not one of the conversation's (the live draft route, spec 2026-11-07 §3.2). */
461
463
  readonly "run.not_found": 404;
package/dist/errors.js CHANGED
@@ -456,6 +456,8 @@ export const ERROR_CODES = {
456
456
  "conversation.request_not_found": 404,
457
457
  /** The request was already answered; the first answer stands. */
458
458
  "conversation.request_answered": 409,
459
+ /** The target closed the request without an answer (`external_request_closed`). */
460
+ "conversation.request_closed": 409,
459
461
  "run.not_active": 409,
460
462
  /** A run that is not one of the conversation's (the live draft route, spec 2026-11-07 §3.2). */
461
463
  "run.not_found": 404,
@@ -233,10 +233,16 @@ let OutboxDispatcher = class OutboxDispatcher {
233
233
  const deadline = now + OUTBOX_REDIS_TIMEOUT_MS;
234
234
  const delivered = [];
235
235
  const failed = [];
236
- // after the first failure the queues left are failed without a try: Redis is likely down
236
+ // after the first real Redis failure the queues left are failed without a try: Redis is
237
+ // likely down. A selective `OUTBOX_DISPATCH_FAILS` test seam only holds its matching queues
238
+ // so other queues in the same relay pass are not poisoned into backoff alongside them.
237
239
  let firstError;
238
240
  for (const [name, group] of byQueue) {
239
241
  const ids = group.map((r) => r.id);
242
+ if (this.dispatchFails(name)) {
243
+ failed.push({ ids, error: "outbox dispatch failure (test seam)" });
244
+ continue;
245
+ }
240
246
  if (firstError !== undefined) {
241
247
  failed.push({
242
248
  ids,
@@ -245,8 +251,6 @@ let OutboxDispatcher = class OutboxDispatcher {
245
251
  continue;
246
252
  }
247
253
  try {
248
- if (this.dispatchFails(name))
249
- throw new Error("outbox dispatch failure (test seam)");
250
254
  const queue = queues.get(name);
251
255
  if (!queue)
252
256
  throw new Error(`"${name}" is not a kernel queue`);
@@ -1095,6 +1095,7 @@ export function buildModelRequest(input) {
1095
1095
  case "external_activity":
1096
1096
  case "external_request":
1097
1097
  case "external_request_answered":
1098
+ case "external_request_closed":
1098
1099
  case "external_turn":
1099
1100
  break;
1100
1101
  default: {
@@ -533,6 +533,7 @@ function transcriptLine(e, notes) {
533
533
  case "external_activity":
534
534
  case "external_request":
535
535
  case "external_request_answered":
536
+ case "external_request_closed":
536
537
  case "external_turn":
537
538
  return null;
538
539
  default: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.139",
3
+ "version": "0.1.0-rc.140",
4
4
  "description": "Capybara kernel: config, database, plugin host and HTTP API of the Capybara agent platform",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -70,7 +70,7 @@
70
70
  "yaml": "^2.9.1",
71
71
  "yauzl": "3.4.0",
72
72
  "zod": "^4.6.7",
73
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.100"
73
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.101"
74
74
  },
75
75
  "devDependencies": {
76
76
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",
@@ -82,7 +82,7 @@
82
82
  "@types/yauzl": "3.4.0",
83
83
  "pg-cursor": "^2.22.1",
84
84
  "ws": "^8.22.0",
85
- "@capybara-hq/testing": "0.1.0-rc.58"
85
+ "@capybara-hq/testing": "0.1.0-rc.59"
86
86
  },
87
87
  "scripts": {
88
88
  "build": "tsc -b"