@capybara-hq/kernel 0.1.0-rc.91 → 0.1.0-rc.93

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/bootstrap.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "schemaVersion": 1,
4
4
  "marketplace": {
5
5
  "url": "https://github.com/capybara-hq/plugins.git",
6
- "commit": "44fa9a1384c92d8016c54dae17d36fb9d464c9e5"
6
+ "commit": "a48ecd8f674cbe24c7094ab8390d7d9ef56b7d80"
7
7
  },
8
8
  "plugins": [
9
9
  {
@@ -98,8 +98,8 @@
98
98
  "name": "device-local",
99
99
  "source": "npm",
100
100
  "npm": "@capybara-hq/plugin-device-local",
101
- "version": "0.1.0-rc.11",
102
- "integrity": "sha512-ZxWxrGjPjNpJtwH/2oK58itxfPFRi5CQQFbMe8VPyfYaEdfyPT8ZlOjgocdz/F8hR9jeu+E2VPgOmh7uMeBo/w==",
101
+ "version": "0.1.0-rc.12",
102
+ "integrity": "sha512-ncQmaRGa48fNjFD5rHQL94yEzBKv0pTS+4vy1uoK9SMWqSJw4/NUfVHs18Li0N2X92yRUystyuGHuJ0/oD4HPA==",
103
103
  "required": false,
104
104
  "scope": "all"
105
105
  },
@@ -208,7 +208,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
208
208
  /** The host versions (an entry's `minKernel` is judged against them). */
209
209
  export declare const HOST_VERSIONS: {
210
210
  readonly kernel: string;
211
- readonly sdk: "0.1.0-rc.73";
211
+ readonly sdk: "0.1.0-rc.76";
212
212
  };
213
213
  /** Whether this deployment satisfies the entry's `minKernel`. */
214
214
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -1617,6 +1617,10 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1617
1617
  en: z.ZodString;
1618
1618
  }, z.core.$strip>]>;
1619
1619
  url: z.ZodOptional<z.ZodString>;
1620
+ body: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
1621
+ zh: z.ZodString;
1622
+ en: z.ZodString;
1623
+ }, z.core.$strip>]>>;
1620
1624
  fields: z.ZodArray<z.ZodObject<{
1621
1625
  key: z.ZodString;
1622
1626
  label: z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
@@ -1631,6 +1635,13 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
1631
1635
  multiSelect: z.ZodOptional<z.ZodBoolean>;
1632
1636
  allowOther: z.ZodOptional<z.ZodBoolean>;
1633
1637
  required: z.ZodOptional<z.ZodBoolean>;
1638
+ choices: z.ZodOptional<z.ZodArray<z.ZodObject<{
1639
+ value: z.ZodUnion<readonly [z.ZodString, z.ZodBoolean]>;
1640
+ label: z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
1641
+ zh: z.ZodString;
1642
+ en: z.ZodString;
1643
+ }, z.core.$strip>]>;
1644
+ }, z.core.$strip>>>;
1634
1645
  }, z.core.$strip>>;
1635
1646
  }, z.core.$strip>;
1636
1647
  expiresAt: z.ZodString;
@@ -671,6 +671,8 @@ const InputFormSchema = z.object({
671
671
  title: FormTextSchema,
672
672
  /** 需要用户在浏览器里打开的外部页面(MCP URL 模式的 elicitation)。较早的事件没有。 */
673
673
  url: z.string().optional(),
674
+ /** Longer text under the title (`InputForm.body`). Older events have none. */
675
+ body: FormTextSchema.optional(),
674
676
  fields: z.array(z.object({
675
677
  key: z.string(),
676
678
  label: FormTextSchema,
@@ -679,6 +681,10 @@ const InputFormSchema = z.object({
679
681
  multiSelect: z.boolean().optional(),
680
682
  allowOther: z.boolean().optional(),
681
683
  required: z.boolean().optional(),
684
+ /** The field's buttons (`InputForm` `choices`). Older events have none. */
685
+ choices: z
686
+ .array(z.object({ value: z.union([z.string(), z.boolean()]), label: FormTextSchema }))
687
+ .optional(),
682
688
  })),
683
689
  });
684
690
  /** 表单答案(plugin-sdk 的 `FormAnswer`)。 */
@@ -21,6 +21,11 @@ export interface DeviceStreamTicket {
21
21
  orgId: string;
22
22
  accountId: string;
23
23
  conversationId: string;
24
+ /**
25
+ * The root of `conversationId`'s tree at mint (itself outside sub-agents): the viewer context
26
+ * the kernel writes first on the service stream names it.
27
+ */
28
+ rootConversationId: string;
24
29
  deviceId: string;
25
30
  providerName: string;
26
31
  service: string;
@@ -103,7 +108,7 @@ export declare class DeviceAccessService {
103
108
  /**
104
109
  * Whether a taken viewer ticket's record still stands when its viewer opens (the checks of
105
110
  * {@link mintTicket} again, binding nothing): the conversation live and owned by the record's
106
- * account, its device still the record's device on the record's provider and the account's
111
+ * account, its current tree root the record's root, its device still the record's device on the record's provider and the account's
107
112
  * own, the record's extension still enabled in the org and its approved manifest as loaded now
108
113
  * (not the record's copy) still declaring the service in `permissions.deviceAccess.services`.
109
114
  * False when any of that no longer holds; other failures (the database) are thrown.
@@ -125,14 +130,24 @@ export declare class DeviceAccessService {
125
130
  hosts: string[];
126
131
  }): Promise<void>;
127
132
  /**
128
- * Answers the pending question of tool call `callId` in the conversation with `{ done }`, under
129
- * the questions' own rules (only the run's starter answers, the form validates the answer); only
130
- * a question one of this extension's tools raised.
133
+ * Answers the pending question of tool call `callId` in conversation `handoffConversationId`
134
+ * with `{ done }`, under the questions' own rules (only the run's starter answers, the form
135
+ * validates the answer); only a question one of this extension's tools raised, and only in the
136
+ * scope conversation or one of its sub-agent descendants (the root's panel answers a
137
+ * sub-agent's handoff; a call id is unique only within a run). Anything else is
138
+ * `question.not_found`, without telling whether such a question exists elsewhere.
131
139
  */
132
140
  answerHandoff(caller: DeviceAccessCaller, scope: DeviceAccessScope & {
133
141
  callId: string;
142
+ handoffConversationId: string;
134
143
  done: boolean;
135
144
  }): Promise<void>;
145
+ /**
146
+ * Whether `id` is `ancestorId` itself or a live conversation below it: walks `id`'s parent links
147
+ * up, every row in org `orgId` and not deleted, at most 16 levels (far above
148
+ * `subagents.maxDepth`'s bound of 5, so a corrupt parent chain cannot loop forever).
149
+ */
150
+ private isSelfOrDescendant;
136
151
  /** The use of the call's device (bound now when the conversation has none yet, as tools do). */
137
152
  private callUse;
138
153
  /**
@@ -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, deviceServiceId, parseToolKey, ToolError, } from "@capybara-hq/plugin-sdk";
11
+ import { DeviceAccessError, deviceServiceFilesDigest, 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";
@@ -141,8 +141,12 @@ let DeviceAccessService = class DeviceAccessService {
141
141
  }
142
142
  };
143
143
  // race-free: the provider keeps a running service and never starts a stopped one here
144
+ // a service running other files (the extension was upgraded since it started) gets a start
145
+ // like a stopped one, reviewed below; the provider then restarts it on the spec's files
146
+ const digest = deviceServiceFilesDigest(providerSpec.files);
147
+ const current = (st) => st.state === "running" && (st.filesDigest === undefined || st.filesDigest === digest);
144
148
  const found = await ensure(true);
145
- if (found.state === "running")
149
+ if (current(found))
146
150
  return found;
147
151
  const reviewFacts = await this.devices.reviewFacts(call.orgId, facts.rootConversationId, call.conversationId);
148
152
  if (reviewFacts === null || reviewFacts.deviceId !== use.deviceId)
@@ -193,11 +197,11 @@ let DeviceAccessService = class DeviceAccessService {
193
197
  // another call may have started it since the first look (that call audits its own start):
194
198
  // found running now, this call started nothing and audits nothing
195
199
  const raced = await ensure(true);
196
- if (raced.state === "running")
200
+ if (current(raced))
197
201
  return raced;
198
202
  const started = await ensure(false);
199
- // audited only when this ensure started it: the service was stopped (no startedAt) just
200
- // before, and runs with a startedAt now
203
+ // audited only when this ensure started it: the service was stopped (no startedAt) or ran
204
+ // other files just before, and runs with a new startedAt now
201
205
  if (started.state !== "running" || started.startedAt === raced.startedAt)
202
206
  return started;
203
207
  await audit(this.db, {
@@ -274,6 +278,7 @@ let DeviceAccessService = class DeviceAccessService {
274
278
  orgId: d.orgId,
275
279
  accountId: scope.accountId,
276
280
  conversationId: d.conversationId,
281
+ rootConversationId: d.rootConversationId,
277
282
  deviceId: d.deviceId,
278
283
  providerName: d.provider,
279
284
  service,
@@ -295,7 +300,7 @@ let DeviceAccessService = class DeviceAccessService {
295
300
  /**
296
301
  * Whether a taken viewer ticket's record still stands when its viewer opens (the checks of
297
302
  * {@link mintTicket} again, binding nothing): the conversation live and owned by the record's
298
- * account, its device still the record's device on the record's provider and the account's
303
+ * account, its current tree root the record's root, its device still the record's device on the record's provider and the account's
299
304
  * own, the record's extension still enabled in the org and its approved manifest as loaded now
300
305
  * (not the record's copy) still declaring the service in `permissions.deviceAccess.services`.
301
306
  * False when any of that no longer holds; other failures (the database) are thrown.
@@ -315,7 +320,10 @@ let DeviceAccessService = class DeviceAccessService {
315
320
  return "revoked";
316
321
  try {
317
322
  const d = await this.scopedDevice({ extension: t.extension, services: [t.service] }, { orgId: t.orgId, accountId: t.accountId, conversationId: t.conversationId });
318
- return d.orgId === t.orgId && d.deviceId === t.deviceId && d.provider === t.providerName
323
+ return d.orgId === t.orgId &&
324
+ d.rootConversationId === t.rootConversationId &&
325
+ d.deviceId === t.deviceId &&
326
+ d.provider === t.providerName
319
327
  ? "stands"
320
328
  : "revoked";
321
329
  }
@@ -358,29 +366,58 @@ let DeviceAccessService = class DeviceAccessService {
358
366
  }
359
367
  }
360
368
  /**
361
- * Answers the pending question of tool call `callId` in the conversation with `{ done }`, under
362
- * the questions' own rules (only the run's starter answers, the form validates the answer); only
363
- * a question one of this extension's tools raised.
369
+ * Answers the pending question of tool call `callId` in conversation `handoffConversationId`
370
+ * with `{ done }`, under the questions' own rules (only the run's starter answers, the form
371
+ * validates the answer); only a question one of this extension's tools raised, and only in the
372
+ * scope conversation or one of its sub-agent descendants (the root's panel answers a
373
+ * sub-agent's handoff; a call id is unique only within a run). Anything else is
374
+ * `question.not_found`, without telling whether such a question exists elsewhere.
364
375
  */
365
376
  async answerHandoff(caller, scope) {
366
377
  const d = await this.scopedDevice(caller, scope);
378
+ const notFound = () => new ApiError("question.not_found", `No pending question of tool call ${scope.callId} in this conversation`);
379
+ if (!(await this.isSelfOrDescendant(d.orgId, d.conversationId, scope.handoffConversationId)))
380
+ throw notFound();
367
381
  const q = await this.db
368
382
  .selectFrom("questions")
369
383
  .select(["id", "spec"])
370
384
  .where("org_id", "=", d.orgId)
371
- .where("conversation_id", "=", d.conversationId)
385
+ .where("conversation_id", "=", scope.handoffConversationId)
372
386
  .where("call_id", "=", scope.callId)
373
387
  .where("status", "=", "pending")
374
388
  .orderBy("created_at", "desc")
375
389
  .executeTakeFirst();
376
390
  if (q === undefined)
377
- throw new ApiError("question.not_found", `No pending question of tool call ${scope.callId} in this conversation`);
391
+ throw notFound();
378
392
  const key = q.spec?.toolKey;
379
393
  const parsed = typeof key === "string" ? parseToolKey(key) : null;
380
394
  if (parsed?.kind !== "extension" || parsed.plugin !== caller.extension)
381
395
  throw new ApiError("question.not_found", `No pending question of tool call ${scope.callId} of ${caller.extension} in this conversation`);
382
396
  await this.questions.answer(q.id, scope.accountId, { done: scope.done }, d.orgId);
383
397
  }
398
+ /**
399
+ * Whether `id` is `ancestorId` itself or a live conversation below it: walks `id`'s parent links
400
+ * up, every row in org `orgId` and not deleted, at most 16 levels (far above
401
+ * `subagents.maxDepth`'s bound of 5, so a corrupt parent chain cannot loop forever).
402
+ */
403
+ async isSelfOrDescendant(orgId, ancestorId, id) {
404
+ let current = id;
405
+ for (let i = 0; i <= 16; i++) {
406
+ if (current === ancestorId)
407
+ return true;
408
+ const row = await this.db
409
+ .selectFrom("conversations")
410
+ .select("parent_conversation_id")
411
+ .where("id", "=", current)
412
+ .where("org_id", "=", orgId)
413
+ .where("deleted_at", "is", null)
414
+ .executeTakeFirst();
415
+ if (!row?.parent_conversation_id)
416
+ return false;
417
+ current = row.parent_conversation_id;
418
+ }
419
+ return false;
420
+ }
384
421
  /** The use of the call's device (bound now when the conversation has none yet, as tools do). */
385
422
  async callUse(call, rootConversationId, scope) {
386
423
  const conv = await this.db
@@ -151,7 +151,10 @@ export declare function parseTicketRecord(raw: unknown): DeviceStreamTicket | nu
151
151
  * The viewer endpoint (browser use spec §6.2, served on the gateway role by `viewer-routes.ts`):
152
152
  * `GET /device/stream?ticket=` takes the single-use viewer ticket
153
153
  * (`DeviceAccessService.takeTicket`) and pipes the device service's stream to the browser, bytes
154
- * unchanged both ways. Where the stream opens:
154
+ * unchanged both ways, after one message of its own: the first stream message the service gets is
155
+ * the viewer context (`encodeViewerContext`: the record's conversation and its root, from the
156
+ * ticket record only), written where the stream opens and before any of the browser's messages
157
+ * (queued by its {@link WsEnd} meanwhile). Where the stream opens:
155
158
  *
156
159
  * - A device whose provider declares `permissions.dialIn` (a local device) streams only from the
157
160
  * gateway replica holding its machine's socket. Any other replica hops once: a `ws` connection
@@ -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, deviceServiceId, isDeviceOfflineError, } from "@capybara-hq/plugin-sdk";
11
+ import { DeviceAccessError, deviceServiceId, encodeViewerContext, 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";
@@ -354,6 +354,7 @@ export function parseTicketRecord(raw) {
354
354
  "orgId",
355
355
  "accountId",
356
356
  "conversationId",
357
+ "rootConversationId",
357
358
  "deviceId",
358
359
  "providerName",
359
360
  "service",
@@ -366,6 +367,7 @@ export function parseTicketRecord(raw) {
366
367
  orgId: r.orgId,
367
368
  accountId: r.accountId,
368
369
  conversationId: r.conversationId,
370
+ rootConversationId: r.rootConversationId,
369
371
  deviceId: r.deviceId,
370
372
  providerName: r.providerName,
371
373
  service: r.service,
@@ -376,7 +378,10 @@ export function parseTicketRecord(raw) {
376
378
  * The viewer endpoint (browser use spec §6.2, served on the gateway role by `viewer-routes.ts`):
377
379
  * `GET /device/stream?ticket=` takes the single-use viewer ticket
378
380
  * (`DeviceAccessService.takeTicket`) and pipes the device service's stream to the browser, bytes
379
- * unchanged both ways. Where the stream opens:
381
+ * unchanged both ways, after one message of its own: the first stream message the service gets is
382
+ * the viewer context (`encodeViewerContext`: the record's conversation and its root, from the
383
+ * ticket record only), written where the stream opens and before any of the browser's messages
384
+ * (queued by its {@link WsEnd} meanwhile). Where the stream opens:
380
385
  *
381
386
  * - A device whose provider declares `permissions.dialIn` (a local device) streams only from the
382
387
  * gateway replica holding its machine's socket. Any other replica hops once: a `ws` connection
@@ -746,7 +751,15 @@ let DeviceStreamViewers = class DeviceStreamViewers {
746
751
  });
747
752
  viewed = true;
748
753
  void pump(stream.messages, end);
749
- const inbound = pump(end.messages, stream);
754
+ // the first stream message is the kernel's viewer context, from the ticket record only; the
755
+ // panel's messages (queued by `end` meanwhile) follow it
756
+ const inbound = stream
757
+ .send(encodeViewerContext({
758
+ kind: "viewer",
759
+ conversationId: record.conversationId,
760
+ rootConversationId: record.rootConversationId,
761
+ }))
762
+ .then(() => pump(end.messages, stream), (failed) => ({ failed: failed ?? new Error("send failed") }));
750
763
  const settled = await Promise.race([
751
764
  end.closed.then(() => ({ side: "viewer" })),
752
765
  stream.closed.then((c) => ({ side: "stream", reason: c.reason })),
@@ -2559,11 +2559,14 @@ let ToolPipeline = class ToolPipeline {
2559
2559
  if (!handler)
2560
2560
  return { kind: "error", message: `Tool ${tool.key} is no longer available.` };
2561
2561
  // 插件处理函数只拿到 SDK 的 ToolCallContext;内置工具另外拿到本步解析出的工具(ToolSearch 用)
2562
+ // the tree root the person looks at; every sub-agent run carries it from its start
2563
+ const rootConversationId = ctx.parent?.rootConversationId ?? ctx.conversationId;
2562
2564
  const base = {
2563
2565
  orgId: ctx.orgId,
2564
2566
  accountId: ctx.accountId,
2565
2567
  agentId: ctx.agentId,
2566
2568
  conversationId: ctx.conversationId,
2569
+ rootConversationId,
2567
2570
  callId,
2568
2571
  idempotencyKey: toolIdempotencyKey(ctx.conversationId, ctx.runId, callId),
2569
2572
  ...(resume !== undefined && { resume }),
@@ -2650,7 +2653,7 @@ let ToolPipeline = class ToolPipeline {
2650
2653
  scope = attachCallScope(call, {
2651
2654
  runId: ctx.runId,
2652
2655
  step: ctx.step,
2653
- rootConversationId: ctx.parent?.rootConversationId ?? ctx.conversationId,
2656
+ rootConversationId,
2654
2657
  unattended: ctx.unattended != null,
2655
2658
  agentVersion: ctx.agentVersion,
2656
2659
  ...(ctx.conversationKind !== undefined && { conversationKind: ctx.conversationKind }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/kernel",
3
- "version": "0.1.0-rc.91",
3
+ "version": "0.1.0-rc.93",
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": {
@@ -66,7 +66,7 @@
66
66
  "yaml": "^2.9.1",
67
67
  "yauzl": "3.4.0",
68
68
  "zod": "^4.6.7",
69
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.73"
69
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.76"
70
70
  },
71
71
  "devDependencies": {
72
72
  "@langchain/langgraph-checkpoint-validation": "^1.2.0",
@@ -75,7 +75,7 @@
75
75
  "@types/ws": "^8.18.2",
76
76
  "@types/yauzl": "3.4.0",
77
77
  "ws": "^8.22.0",
78
- "@capybara-hq/testing": "0.1.0-rc.41"
78
+ "@capybara-hq/testing": "0.1.0-rc.42"
79
79
  },
80
80
  "scripts": {
81
81
  "build": "tsc -b"