@capybara-hq/kernel 0.1.0-rc.135 → 0.1.0-rc.136

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 (92) hide show
  1. package/dist/admin/admin.module.js +3 -0
  2. package/dist/admin/health.service.d.ts +2 -2
  3. package/dist/admin/health.service.js +6 -2
  4. package/dist/catalog/marketplaces.service.d.ts +1 -1
  5. package/dist/conversations/access.d.ts +15 -7
  6. package/dist/conversations/access.js +59 -10
  7. package/dist/conversations/conversation-agent.d.ts +18 -0
  8. package/dist/conversations/conversation-agent.js +23 -0
  9. package/dist/conversations/conversation-ref.d.ts +3 -2
  10. package/dist/conversations/conversation-ref.js +6 -1
  11. package/dist/conversations/conversations.controller.d.ts +28 -5
  12. package/dist/conversations/conversations.controller.js +99 -10
  13. package/dist/conversations/conversations.module.js +10 -0
  14. package/dist/conversations/conversations.schemas.d.ts +6 -0
  15. package/dist/conversations/conversations.schemas.js +15 -0
  16. package/dist/conversations/conversations.service.d.ts +125 -21
  17. package/dist/conversations/conversations.service.js +260 -90
  18. package/dist/conversations/event-log.d.ts +9 -1
  19. package/dist/conversations/event-log.js +2 -0
  20. package/dist/conversations/events.d.ts +57 -0
  21. package/dist/conversations/events.js +73 -1
  22. package/dist/conversations/external/external-calls.d.ts +75 -0
  23. package/dist/conversations/external/external-calls.js +91 -0
  24. package/dist/conversations/external/external-calls.processor.d.ts +45 -0
  25. package/dist/conversations/external/external-calls.processor.js +144 -0
  26. package/dist/conversations/external/external-conversations.service.d.ts +266 -0
  27. package/dist/conversations/external/external-conversations.service.js +1138 -0
  28. package/dist/conversations/external/external.schemas.d.ts +63 -0
  29. package/dist/conversations/external/external.schemas.js +52 -0
  30. package/dist/conversations/external/token.d.ts +6 -0
  31. package/dist/conversations/external/token.js +6 -0
  32. package/dist/conversations/permission-profile-store.d.ts +4 -1
  33. package/dist/conversations/permission-profiles.controller.d.ts +33 -9
  34. package/dist/conversations/permission-profiles.controller.js +86 -6
  35. package/dist/conversations/prompt-suggestions.js +2 -1
  36. package/dist/conversations/queue.js +2 -1
  37. package/dist/conversations/titles.js +4 -3
  38. package/dist/ctx/create-ctx.d.ts +7 -0
  39. package/dist/ctx/create-ctx.js +45 -2
  40. package/dist/db/kernel-schema.d.ts +31 -4
  41. package/dist/device-access/host-services.js +3 -2
  42. package/dist/device-access/person-handles.d.ts +16 -7
  43. package/dist/device-access/person-handles.js +14 -9
  44. package/dist/devices/conversation-devices.d.ts +5 -0
  45. package/dist/devices/conversation-devices.js +16 -0
  46. package/dist/erasure/org-catalog.js +2 -2
  47. package/dist/errors.d.ts +34 -0
  48. package/dist/errors.js +34 -0
  49. package/dist/evals/snapshot.js +3 -1
  50. package/dist/evals/trajectory.service.d.ts +2 -2
  51. package/dist/evals/trajectory.service.js +11 -7
  52. package/dist/extensions/extensions.module.js +3 -0
  53. package/dist/extensions/host.d.ts +7 -0
  54. package/dist/extensions/host.js +11 -0
  55. package/dist/extensions/permission-view.d.ts +3 -1
  56. package/dist/extensions/permission-view.js +4 -1
  57. package/dist/extensions/point-defaults.d.ts +13 -21
  58. package/dist/extensions/point-defaults.js +32 -72
  59. package/dist/extensions/point-serving.d.ts +56 -0
  60. package/dist/extensions/point-serving.js +120 -0
  61. package/dist/inbox/inbox-items.service.d.ts +11 -0
  62. package/dist/inbox/inbox-items.service.js +39 -0
  63. package/dist/infra/outbox/registry.d.ts +70 -0
  64. package/dist/infra/outbox/registry.js +44 -0
  65. package/dist/infra/queue/queue-names.d.ts +1 -1
  66. package/dist/infra/queue/queue-names.js +1 -0
  67. package/dist/kernel.module.js +4 -0
  68. package/dist/platform/exclusions.js +10 -0
  69. package/dist/platform/ops/conversations.ops.d.ts +8 -1
  70. package/dist/platform/ops/conversations.ops.js +52 -14
  71. package/dist/plugin-reads/plugin-reads.service.js +4 -1
  72. package/dist/push/recipients.js +5 -2
  73. package/dist/retention/worker.js +2 -1
  74. package/dist/roles/worker-role.d.ts +3 -1
  75. package/dist/roles/worker-role.js +8 -2
  76. package/dist/roles/worker.module.js +3 -0
  77. package/dist/runtime/context/build.js +8 -0
  78. package/dist/runtime/context/compaction.js +7 -0
  79. package/dist/runtime/idle-arm.js +3 -1
  80. package/dist/runtime/idle-compaction.js +2 -1
  81. package/dist/runtime/run-finish.js +2 -1
  82. package/dist/runtime/run-jobs.js +2 -1
  83. package/dist/runtime/run-queue.js +4 -2
  84. package/dist/runtime/run-worker.js +5 -2
  85. package/dist/runtime/stream.js +10 -0
  86. package/dist/runtime/usage-report.js +2 -1
  87. package/dist/runtime/waits.js +2 -1
  88. package/dist/tools/approvals.service.js +6 -2
  89. package/dist/tools/builtins/skill-load.js +3 -2
  90. package/dist/tools/tool-watch.service.js +3 -1
  91. package/package.json +3 -3
  92. package/src/migrations/0227_external_conversations.sql +33 -0
@@ -0,0 +1,63 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * The schemas of external conversations (local agents spec Part 2): the routes' params and bodies,
4
+ * and what a `conversation-target@1` provider's `targets()` must return to be listed.
5
+ */
6
+ /** A target's key (`ConversationTargetInfo.key`). */
7
+ export declare const TARGET_KEY_RE: RegExp;
8
+ /** The target a first message starts an external conversation with. */
9
+ export declare const ExternalTargetRef: z.ZodObject<{
10
+ extension: z.ZodString;
11
+ targetKey: z.ZodString;
12
+ }, z.core.$strict>;
13
+ /** A target's option id (a model, effort or mode the target lists). */
14
+ export declare const TargetOptionId: z.ZodString;
15
+ /** `POST …/conversations/:id/external-requests/:requestId`: the route params. */
16
+ export declare const ExternalRequestParams: z.ZodObject<{
17
+ id: z.ZodString;
18
+ requestId: z.ZodString;
19
+ }, z.core.$strip>;
20
+ /** `POST …/conversations/:id/external-requests/:requestId`: the chosen option. */
21
+ export declare const ExternalAnswerBody: z.ZodObject<{
22
+ optionId: z.ZodString;
23
+ }, z.core.$strict>;
24
+ /**
25
+ * One target as a provider's `targets()` returns it (`ConversationTargetInfo`); a target that does
26
+ * not parse is left out of the list (logged).
27
+ */
28
+ export declare const ConversationTargetInfoSchema: z.ZodObject<{
29
+ key: z.ZodString;
30
+ label: z.ZodObject<{
31
+ zh: z.ZodString;
32
+ en: z.ZodString;
33
+ }, z.core.$strip>;
34
+ description: z.ZodOptional<z.ZodObject<{
35
+ zh: z.ZodString;
36
+ en: z.ZodString;
37
+ }, z.core.$strip>>;
38
+ icon: z.ZodOptional<z.ZodString>;
39
+ devices: z.ZodArray<z.ZodObject<{
40
+ deviceId: z.ZodString;
41
+ ready: z.ZodNullable<z.ZodBoolean>;
42
+ models: z.ZodArray<z.ZodObject<{
43
+ id: z.ZodString;
44
+ label: z.ZodObject<{
45
+ zh: z.ZodString;
46
+ en: z.ZodString;
47
+ }, z.core.$strip>;
48
+ }, z.core.$strip>>;
49
+ efforts: z.ZodArray<z.ZodString>;
50
+ modes: z.ZodArray<z.ZodObject<{
51
+ id: z.ZodString;
52
+ label: z.ZodObject<{
53
+ zh: z.ZodString;
54
+ en: z.ZodString;
55
+ }, z.core.$strip>;
56
+ }, z.core.$strip>>;
57
+ defaults: z.ZodObject<{
58
+ model: z.ZodOptional<z.ZodString>;
59
+ effort: z.ZodOptional<z.ZodString>;
60
+ mode: z.ZodOptional<z.ZodString>;
61
+ }, z.core.$strip>;
62
+ }, z.core.$strip>>;
63
+ }, z.core.$strip>;
@@ -0,0 +1,52 @@
1
+ import { EXTERNAL_EVENT_ID_RE, EXTERNAL_OPTION_ID_RE } from "@capybara-hq/plugin-sdk";
2
+ import { z } from "zod";
3
+ /**
4
+ * The schemas of external conversations (local agents spec Part 2): the routes' params and bodies,
5
+ * and what a `conversation-target@1` provider's `targets()` must return to be listed.
6
+ */
7
+ /** A target's key (`ConversationTargetInfo.key`). */
8
+ export const TARGET_KEY_RE = /^[a-z0-9][a-z0-9-]{0,62}$/;
9
+ /** The target a first message starts an external conversation with. */
10
+ export const ExternalTargetRef = z
11
+ .object({
12
+ extension: z.string().min(1).max(100),
13
+ targetKey: z.string().regex(TARGET_KEY_RE, "targetKey must be a target key"),
14
+ })
15
+ .strict();
16
+ /** A target's option id (a model, effort or mode the target lists). */
17
+ export const TargetOptionId = z.string().min(1).max(200);
18
+ /** `POST …/conversations/:id/external-requests/:requestId`: the route params. */
19
+ export const ExternalRequestParams = z.object({
20
+ id: z.string().min(1).max(100),
21
+ requestId: z.string().regex(EXTERNAL_EVENT_ID_RE, "requestId is not a request id"),
22
+ });
23
+ /** `POST …/conversations/:id/external-requests/:requestId`: the chosen option. */
24
+ export const ExternalAnswerBody = z
25
+ .object({ optionId: z.string().regex(EXTERNAL_OPTION_ID_RE, "optionId is not an option id") })
26
+ .strict();
27
+ const LocalizedNameSchema = z.object({ zh: z.string().max(200), en: z.string().max(200) });
28
+ const TargetOptionSchema = z.object({ id: TargetOptionId, label: LocalizedNameSchema });
29
+ /**
30
+ * One target as a provider's `targets()` returns it (`ConversationTargetInfo`); a target that does
31
+ * not parse is left out of the list (logged).
32
+ */
33
+ export const ConversationTargetInfoSchema = z.object({
34
+ key: z.string().regex(TARGET_KEY_RE),
35
+ label: LocalizedNameSchema,
36
+ description: LocalizedNameSchema.optional(),
37
+ icon: z.string().max(2000).optional(),
38
+ devices: z
39
+ .array(z.object({
40
+ deviceId: z.string().min(1).max(100),
41
+ ready: z.boolean().nullable(),
42
+ models: z.array(TargetOptionSchema).max(200),
43
+ efforts: z.array(z.string().max(200)).max(50),
44
+ modes: z.array(TargetOptionSchema).max(50),
45
+ defaults: z.object({
46
+ model: z.string().max(200).optional(),
47
+ effort: z.string().max(200).optional(),
48
+ mode: z.string().max(200).optional(),
49
+ }),
50
+ }))
51
+ .max(50),
52
+ });
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The token the extension host finds `ExternalConversationsService` by at the time of use
3
+ * (`ModuleRef`, `ctx.conversations`' external methods): a symbol in a file of its own, so the
4
+ * host never imports the service's module graph.
5
+ */
6
+ export declare const EXTERNAL_CONVERSATIONS_BACKEND: unique symbol;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The token the extension host finds `ExternalConversationsService` by at the time of use
3
+ * (`ModuleRef`, `ctx.conversations`' external methods): a symbol in a file of its own, so the
4
+ * host never imports the service's module graph.
5
+ */
6
+ export const EXTERNAL_CONVERSATIONS_BACKEND = Symbol("EXTERNAL_CONVERSATIONS_BACKEND");
@@ -10,7 +10,7 @@ export declare class PermissionProfileStore {
10
10
  constructor(db: KernelDb, access: ConversationAccess);
11
11
  own(orgId: string, id: string, accountId: string): Promise<{
12
12
  account_id: string;
13
- agent_id: string;
13
+ agent_id: string | null;
14
14
  archived_at: Date | null;
15
15
  automation_id: string | null;
16
16
  consumed_seq: string;
@@ -20,6 +20,9 @@ export declare class PermissionProfileStore {
20
20
  deleted_at: Date | null;
21
21
  device_id: string | null;
22
22
  eval_run_id: string | null;
23
+ external: import("../db/kernel-schema.js").ExternalRef | null;
24
+ external_delivered_seq: string;
25
+ external_state: import("@capybara-hq/plugin-sdk").ExternalConversationState;
23
26
  id: string;
24
27
  kind: import("../db/kernel-schema.js").ConversationKind;
25
28
  last_seq: string;
@@ -1,12 +1,19 @@
1
1
  import type { FastifyReply } from "fastify";
2
- import type { z } from "zod";
2
+ import { z } from "zod";
3
3
  import { type Principal } from "../identity/principal.js";
4
4
  import { type OrgContext } from "../orgs/org.guard.js";
5
- import { ConversationsService } from "./conversations.service.js";
5
+ import { ConversationsService, type ConversationView } from "./conversations.service.js";
6
+ import type { ConversationEvent } from "./events.js";
7
+ import { type ConversationTargetItem, ExternalConversationsService } from "./external/external-conversations.service.js";
6
8
  import { PermissionGetParams, PermissionPatchBody, PermissionPreviewQuery } from "./permission-profiles.schemas.js";
7
9
  import { PermissionProfilesService } from "./permission-profiles.service.js";
10
+ /**
11
+ * `POST …/conversations/first-message`: exactly one of `agentId` (with `permission`) or `target`
12
+ * (local agents spec Part 2: an external conversation, with the target's `model`, `effort` and
13
+ * `mode`; `deviceId` and `project` as for an agent). Mixing the two kinds' fields is
14
+ * `conversation.target_fields`.
15
+ */
8
16
  export declare const FirstMessageBody: z.ZodObject<{
9
- agentId: z.ZodString;
10
17
  deviceId: z.ZodOptional<z.ZodString>;
11
18
  project: z.ZodOptional<z.ZodString & z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>>;
12
19
  message: z.ZodNonOptional<z.ZodOptional<z.ZodObject<{
@@ -50,19 +57,36 @@ export declare const FirstMessageBody: z.ZodObject<{
50
57
  }>>;
51
58
  clientMessageId: z.ZodString;
52
59
  }, z.core.$strict>>>;
53
- permission: z.ZodObject<{
60
+ agentId: z.ZodOptional<z.ZodString>;
61
+ permission: z.ZodOptional<z.ZodObject<{
54
62
  profile: z.ZodEnum<{
55
63
  "approve-for-me": "approve-for-me";
56
64
  "full-access": "full-access";
57
65
  "request-approval": "request-approval";
58
66
  }>;
59
67
  consentScopeRevision: z.ZodOptional<z.ZodString>;
60
- }, z.core.$strict>;
68
+ }, z.core.$strict>>;
69
+ target: z.ZodOptional<z.ZodObject<{
70
+ extension: z.ZodString;
71
+ targetKey: z.ZodString;
72
+ }, z.core.$strict>>;
73
+ model: z.ZodOptional<z.ZodString>;
74
+ effort: z.ZodOptional<z.ZodString>;
75
+ mode: z.ZodOptional<z.ZodString>;
61
76
  }, z.core.$strict>;
62
77
  export declare class PermissionProfilesController {
63
78
  private readonly permissions;
64
79
  private readonly conversations;
65
- constructor(permissions: PermissionProfilesService, conversations: ConversationsService);
80
+ private readonly external;
81
+ constructor(permissions: PermissionProfilesService, conversations: ConversationsService, external: Pick<ExternalConversationsService, "targets" | "createWithMessage">);
82
+ /**
83
+ * The conversation targets (local agents) the caller can start a conversation with, from every
84
+ * `conversation-target@1` provider serving the org (local agents spec Part 2); a provider that
85
+ * fails or does not answer within `tools.timeoutMs` is left out.
86
+ */
87
+ targets(org: OrgContext, p: Principal): Promise<{
88
+ targets: ConversationTargetItem[];
89
+ }>;
66
90
  get(org: OrgContext, p: Principal, { id }: z.infer<typeof PermissionGetParams>): Promise<{
67
91
  availability: import("../sandbox/permission-availability.js").PermissionAvailability;
68
92
  profile: import("@capybara-hq/plugin-sdk").PermissionProfile;
@@ -107,8 +131,8 @@ export declare class PermissionProfilesController {
107
131
  availability: import("../sandbox/permission-availability.js").PermissionAvailability;
108
132
  }>;
109
133
  first(org: OrgContext, p: Principal, body: z.infer<typeof FirstMessageBody>, reply: FastifyReply): Promise<{
110
- conversation: import("./conversations.service.js").ConversationView;
111
- event: import("./events.js").ConversationEvent;
112
- events: import("./events.js").ConversationEvent[];
134
+ conversation: ConversationView;
135
+ event: ConversationEvent;
136
+ events: ConversationEvent[];
113
137
  }>;
114
138
  }
@@ -8,6 +8,8 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
10
  import { Controller, Get, Inject, Patch, Post, Res } from "@nestjs/common";
11
+ import { z } from "zod";
12
+ import { ApiError } from "../errors.js";
11
13
  import { requestSignal } from "../http/request-signal.js";
12
14
  import { CurrentPrincipal, requireUser, SessionOnly, } from "../identity/principal.js";
13
15
  import { createZodDto } from "../infra/validation/create-zod-dto.js";
@@ -15,11 +17,42 @@ import { ZBody, ZParam, ZQuery } from "../infra/validation/zod-params.js";
15
17
  import { CurrentOrg, OrgAction } from "../orgs/org.guard.js";
16
18
  import { CreateBody } from "./conversations.controller.js";
17
19
  import { ConversationsService } from "./conversations.service.js";
20
+ import { ExternalTargetRef, TargetOptionId } from "./external/external.schemas.js";
21
+ import { ExternalConversationsService, } from "./external/external-conversations.service.js";
18
22
  import { PermissionGetParams, PermissionPatchBody, PermissionPreviewQuery, PermissionSelectionSchema, } from "./permission-profiles.schemas.js";
19
23
  import { PermissionProfilesService } from "./permission-profiles.service.js";
24
+ /**
25
+ * `POST …/conversations/first-message`: exactly one of `agentId` (with `permission`) or `target`
26
+ * (local agents spec Part 2: an external conversation, with the target's `model`, `effort` and
27
+ * `mode`; `deviceId` and `project` as for an agent). Mixing the two kinds' fields is
28
+ * `conversation.target_fields`.
29
+ */
20
30
  export const FirstMessageBody = CreateBody.required({ message: true })
21
- .extend({ permission: PermissionSelectionSchema })
22
- .strict();
31
+ .extend({
32
+ agentId: z.string().min(1).max(100).optional(),
33
+ permission: PermissionSelectionSchema.optional(),
34
+ target: ExternalTargetRef.optional(),
35
+ model: TargetOptionId.optional(),
36
+ effort: TargetOptionId.optional(),
37
+ mode: TargetOptionId.optional(),
38
+ })
39
+ .strict()
40
+ .superRefine((b, ctx) => {
41
+ if ((b.agentId === undefined) === (b.target === undefined))
42
+ ctx.addIssue({
43
+ code: "custom",
44
+ message: "Give exactly one of agentId or target",
45
+ path: ["agentId"],
46
+ });
47
+ else if (b.agentId !== undefined && b.permission === undefined)
48
+ ctx.addIssue({
49
+ code: "custom",
50
+ message: "permission is required with agentId",
51
+ path: ["permission"],
52
+ });
53
+ });
54
+ /** The message fields a first message to a target does not take (it has its own options). */
55
+ const NOT_TARGET_MESSAGE_FIELDS = ["tokens", "files", "model", "effort", "skill"];
23
56
  class PermissionParamsDto extends createZodDto(PermissionGetParams, "PermissionParams") {
24
57
  }
25
58
  class PermissionPatchDto extends createZodDto(PermissionPatchBody, "PermissionPatch") {
@@ -31,9 +64,19 @@ class FirstMessageDto extends createZodDto(FirstMessageBody, "ConversationFirstM
31
64
  let PermissionProfilesController = class PermissionProfilesController {
32
65
  permissions;
33
66
  conversations;
34
- constructor(permissions, conversations) {
67
+ external;
68
+ constructor(permissions, conversations, external) {
35
69
  this.permissions = permissions;
36
70
  this.conversations = conversations;
71
+ this.external = external;
72
+ }
73
+ /**
74
+ * The conversation targets (local agents) the caller can start a conversation with, from every
75
+ * `conversation-target@1` provider serving the org (local agents spec Part 2); a provider that
76
+ * fails or does not answer within `tools.timeoutMs` is left out.
77
+ */
78
+ async targets(org, p) {
79
+ return { targets: await this.external.targets(org.orgId, requireUser(p).account.id) };
37
80
  }
38
81
  get(org, p, { id }) {
39
82
  return this.permissions.get(org.orgId, id, requireUser(p).account.id);
@@ -45,8 +88,37 @@ let PermissionProfilesController = class PermissionProfilesController {
45
88
  return this.permissions.preview(org.orgId, requireUser(p).account.id, q.deviceId, q.project);
46
89
  }
47
90
  async first(org, p, body, reply) {
48
- const { permission, agentId, message, deviceId, project } = body;
49
- const out = await this.conversations.createWithMessage(org.orgId, requireUser(p).account.id, agentId, {
91
+ const { permission, agentId, target, message, deviceId, project } = body;
92
+ const accountId = requireUser(p).account.id;
93
+ if (target !== undefined) {
94
+ const mixed = [
95
+ ...(permission !== undefined ? ["permission"] : []),
96
+ ...NOT_TARGET_MESSAGE_FIELDS.filter((k) => message[k] !== undefined).map((k) => `message.${k}`),
97
+ ];
98
+ if (mixed.length > 0)
99
+ throw new ApiError("conversation.target_fields", `A first message to a target takes no ${mixed.join(", ")}`);
100
+ const out = await this.external.createWithMessage(org.orgId, accountId, {
101
+ extension: target.extension,
102
+ targetKey: target.targetKey,
103
+ text: message.text,
104
+ clientMessageId: message.clientMessageId,
105
+ ...(deviceId !== undefined && { deviceId }),
106
+ ...(project !== undefined && { project }),
107
+ ...(body.model !== undefined && { model: body.model }),
108
+ ...(body.effort !== undefined && { effort: body.effort }),
109
+ ...(body.mode !== undefined && { mode: body.mode }),
110
+ ...(message.locale !== undefined && { locale: message.locale }),
111
+ });
112
+ reply.status(out.created ? 201 : 200);
113
+ return { conversation: out.conversation, event: out.event, events: out.events };
114
+ }
115
+ const mixed = ["model", "effort", "mode"].filter((k) => body[k] !== undefined);
116
+ if (mixed.length > 0)
117
+ throw new ApiError("conversation.target_fields", `A first message to an agent takes no ${mixed.join(", ")}`);
118
+ // the refinement made both present
119
+ if (agentId === undefined || permission === undefined)
120
+ throw new ApiError("validation_failed", "agentId and permission are required");
121
+ const out = await this.conversations.createWithMessage(org.orgId, accountId, agentId, {
50
122
  text: message.text,
51
123
  clientMessageId: message.clientMessageId,
52
124
  ...(message.tokens !== undefined ? { tokens: message.tokens } : {}),
@@ -64,6 +136,13 @@ let PermissionProfilesController = class PermissionProfilesController {
64
136
  return { conversation: out.conversation, event: out.event, events: out.events };
65
137
  }
66
138
  };
139
+ __decorate([
140
+ Get("conversation-targets"),
141
+ SessionOnly(),
142
+ OrgAction("agents.use"),
143
+ __param(0, CurrentOrg()),
144
+ __param(1, CurrentPrincipal())
145
+ ], PermissionProfilesController.prototype, "targets", null);
67
146
  __decorate([
68
147
  Get("conversations/:id/permissions"),
69
148
  SessionOnly(),
@@ -101,6 +180,7 @@ __decorate([
101
180
  PermissionProfilesController = __decorate([
102
181
  Controller("api/v1/orgs/:orgId"),
103
182
  __param(0, Inject(PermissionProfilesService)),
104
- __param(1, Inject(ConversationsService))
183
+ __param(1, Inject(ConversationsService)),
184
+ __param(2, Inject(ExternalConversationsService))
105
185
  ], PermissionProfilesController);
106
186
  export { PermissionProfilesController };
@@ -35,6 +35,7 @@ import { fireObserve, hookDeniedAudit, hookDeniedEvent, } from "../runtime/hook-
35
35
  import { consumeModelStream, deltaChars } from "../runtime/model-call.js";
36
36
  import { ModelRequestDenied, ProviderRegistry, ProvidersModule, prepareModelStream, } from "../runtime/providers.js";
37
37
  import { UsageReportJobs, UsageReportJobsModule } from "../runtime/usage-report-jobs.js";
38
+ import { agentIdOf } from "./conversation-agent.js";
38
39
  import { EventLog, EventLogModule } from "./event-log.js";
39
40
  import { resolveConversationOrg } from "./job-org.js";
40
41
  import { buildSuggestionRequest, cleanSuggestion, lastModelCallOf, PROMPT_SUGGESTION_TIMEOUT_MS, suggestionEligible, suggestionStale, } from "./prompt-suggestion-request.js";
@@ -326,7 +327,7 @@ let PromptSuggestionGenerator = class PromptSuggestionGenerator {
326
327
  return "not_eligible";
327
328
  return {
328
329
  orgId: conv.org_id,
329
- agentId: conv.agent_id,
330
+ agentId: agentIdOf(conv),
330
331
  accountId: s.triggerAccountId,
331
332
  agentVersion: s.agentVersion,
332
333
  afterSeq: Number(finished.seq),
@@ -2,6 +2,7 @@ import { sql } from "kysely";
2
2
  import { normalizeStoredDefinition } from "../agents/definition.js";
3
3
  import { ApiError } from "../errors.js";
4
4
  import { recordedSkillBlocked, } from "../skills/invoke.js";
5
+ import { agentIdOf } from "./conversation-agent.js";
5
6
  import { payloadJson } from "./event-log.js";
6
7
  import { userMessageIdemKey } from "./idem-keys.js";
7
8
  import { readMessageContext } from "./message-context.js";
@@ -194,7 +195,7 @@ async function currentAgent(t, conversationId) {
194
195
  .executeTakeFirstOrThrow();
195
196
  return {
196
197
  orgId: row.org_id,
197
- agentId: row.agent_id,
198
+ agentId: agentIdOf(row),
198
199
  definition: normalizeStoredDefinition(row.definition),
199
200
  };
200
201
  }
@@ -26,6 +26,7 @@ import { ModelPurposesService, PurposeAttemptError } from "../models/purposes.js
26
26
  import { fireObserve, hookDeniedAudit, hookDeniedEvent, } from "../runtime/hook-calls.js";
27
27
  import { UsageReportJobs, UsageReportJobsModule } from "../runtime/usage-report-jobs.js";
28
28
  import { HIDDEN_FORMAT_RE } from "../text.js";
29
+ import { agentIdOf } from "./conversation-agent.js";
29
30
  import { EventLog, EventLogModule } from "./event-log.js";
30
31
  import { typedInvocation } from "./events.js";
31
32
  import { resolveConversationOrg } from "./job-org.js";
@@ -198,6 +199,7 @@ export async function runTitleJob(d, conversationId, attempt) {
198
199
  .executeTakeFirst();
199
200
  if (!claimed)
200
201
  return;
202
+ const agentId = agentIdOf(claimed);
201
203
  const started = await d.eventLog.latestOfType(conversationId, "run_started");
202
204
  const fallback = started?.payload.model;
203
205
  const signal = AbortSignal.any([
@@ -207,9 +209,8 @@ export async function runTitleJob(d, conversationId, attempt) {
207
209
  const scope = {
208
210
  orgId: claimed.org_id,
209
211
  accountId: claimed.account_id,
210
- agentId: claimed.agent_id,
211
- agentVersion: started?.payload.agentVersion ??
212
- (await agentVersionOf(d.db, claimed.org_id, claimed.agent_id)),
212
+ agentId,
213
+ agentVersion: started?.payload.agentVersion ?? (await agentVersionOf(d.db, claimed.org_id, agentId)),
213
214
  conversationId,
214
215
  runId: "",
215
216
  };
@@ -2,6 +2,7 @@ import { type EmbedClaims, type ExtensionContext, type ExtensionManifest, type E
2
2
  import type { Redis } from "ioredis";
3
3
  import { Kysely } from "kysely";
4
4
  import type { TriggerEventsService } from "../automations/events/trigger-events.service.js";
5
+ import type { ExternalConversationsBackend } from "../conversations/external/external-conversations.service.js";
5
6
  import { pluginSchemaName } from "../db/extension-db.js";
6
7
  import type { DeviceAccessService } from "../device-access/device-access.service.js";
7
8
  import type { ServiceEventHandler, ServiceEventsBackend } from "../device-access/service-events.js";
@@ -107,6 +108,12 @@ export interface KernelDeps {
107
108
  * found at the time of use like `inbox`. Absent, or resolving to undefined: those calls reject.
108
109
  */
109
110
  pluginReads?: () => PluginReadsBackend | undefined;
111
+ /**
112
+ * What `ctx.conversations`' external methods call through (`ExternalConversationsService`),
113
+ * found at the time of use like `inbox`. Absent, or resolving to undefined: those calls reject
114
+ * (`streamExternalText` drops its hint).
115
+ */
116
+ externalConversations?: () => ExternalConversationsBackend | undefined;
110
117
  runWorkers: boolean;
111
118
  /** 内核 logger(`debug` 可选:插件 Logger 没有它,测试可不给)。 */
112
119
  log: Logger & {
@@ -1,6 +1,7 @@
1
- import { CtxReadError, DEVICE_PROVIDER_EXTENSION_POINT, DeviceAccessError, EXTENSION_POINTS, ExtensionPermissionError, ExtensionPointUnavailableError, FILE_PREVIEW_EXTENSION_POINT, InboxError, OBJECT_STORE_EXTENSION_POINT, parseExtensionPoint, resolveUiSlots, SETUP_CHECK_ID_RE, SETUP_GUIDE_PLACES, TriggerError, validateFilePreviewProvider, validateToolSpec, } from "@capybara-hq/plugin-sdk";
1
+ import { CONVERSATION_TARGET_EXTENSION_POINT, CtxReadError, DEVICE_PROVIDER_EXTENSION_POINT, DeviceAccessError, EXTENSION_POINTS, ExtensionPermissionError, ExtensionPointUnavailableError, FILE_PREVIEW_EXTENSION_POINT, InboxError, OBJECT_STORE_EXTENSION_POINT, parseExtensionPoint, resolveUiSlots, SETUP_CHECK_ID_RE, SETUP_GUIDE_PLACES, TriggerError, validateFilePreviewProvider, validateToolSpec, } from "@capybara-hq/plugin-sdk";
2
2
  import { Command, ConnectionBuilder, ControlledTransactionBuilder, Kysely, TransactionBuilder, } from "kysely";
3
3
  import { conversationTopic } from "../conversations/event-log.js";
4
+ import { checkExternalText } from "../conversations/external/external-calls.js";
4
5
  import { pluginSchemaName } from "../db/extension-db.js";
5
6
  import { kernelDb } from "../db/kernel-schema.js";
6
7
  import { ApiError } from "../errors.js";
@@ -644,9 +645,23 @@ identity = { sha256: null }) {
644
645
  },
645
646
  }
646
647
  : undefined;
647
- const conversationsApi = perms.conversations
648
+ // bySubject needs `permissions.conversations`; the external-conversation methods belong to a
649
+ // `conversation-target@1` provider, on its own conversations only (the backend checks that and
650
+ // that it serves the org); every call runs in the named org's scope
651
+ const providesTarget = manifest.provides.includes(CONVERSATION_TARGET_EXTENSION_POINT);
652
+ const externalBackend = () => {
653
+ if (!providesTarget)
654
+ deny(`provides ${CONVERSATION_TARGET_EXTENSION_POINT}`);
655
+ const b = deps.externalConversations?.();
656
+ if (!b)
657
+ throw new Error("External conversations are not available in this process.");
658
+ return b;
659
+ };
660
+ const conversationsApi = perms.conversations || providesTarget
648
661
  ? {
649
662
  bySubject: async (args) => {
663
+ if (!perms.conversations)
664
+ deny("permissions.conversations");
650
665
  const a = readArgs(args);
651
666
  const s = a.subject;
652
667
  if (typeof s !== "object" ||
@@ -659,6 +674,34 @@ identity = { sha256: null }) {
659
674
  const subject = { kind: s.kind, id: s.id };
660
675
  return withOrgScope(a.orgId, () => readsBackend().bySubject(name, a.orgId, subject));
661
676
  },
677
+ appendExternal: async (args) => {
678
+ const b = externalBackend();
679
+ const a = readArgs(args);
680
+ return withOrgScope(a.orgId, () => b.appendExternal(name, {
681
+ orgId: a.orgId,
682
+ conversationId: a.conversationId,
683
+ events: a.events,
684
+ }));
685
+ },
686
+ setExternalState: async (args) => {
687
+ const b = externalBackend();
688
+ const a = readArgs(args);
689
+ return withOrgScope(a.orgId, () => b.setExternalState(name, {
690
+ orgId: a.orgId,
691
+ conversationId: a.conversationId,
692
+ state: a.state,
693
+ }));
694
+ },
695
+ streamExternalText: (args) => {
696
+ const b = externalBackend();
697
+ // checked now (a wrong call throws); the publish is a hint, its failure only logged
698
+ const a = checkExternalText(args);
699
+ void withOrgScope(a.orgId, () => b.streamExternalText(name, a)).catch((err) => deps.log.warn("external partial text failed", {
700
+ plugin: name,
701
+ conversationId: a.conversationId,
702
+ err,
703
+ }));
704
+ },
662
705
  }
663
706
  : undefined;
664
707
  const peopleApi = perms.people
@@ -1,4 +1,4 @@
1
- import type { CacheWriteByTtl, ConversationSource, FileSystemHandle, GitHostEntry, ParsedTheme, PermissionProfile, SandboxBrowseScope, SandboxExecutionRef, SandboxOperationScope, SandboxPermissionSupport, SandboxRoots, SiteAccessAction, SkillInvocation, TriggerFactValue, TriggerSubject } from "@capybara-hq/plugin-sdk";
1
+ import type { CacheWriteByTtl, ConversationSource, ExternalConversationState, FileSystemHandle, GitHostEntry, ParsedTheme, PermissionProfile, SandboxBrowseScope, SandboxExecutionRef, SandboxOperationScope, SandboxPermissionSupport, SandboxRoots, SiteAccessAction, SkillInvocation, TriggerFactValue, TriggerSubject } from "@capybara-hq/plugin-sdk";
2
2
  import type { ColumnType, Generated, Kysely } from "kysely";
3
3
  import type { ModelRef } from "../agents/definition.js";
4
4
  import type { AutomationChat, AutomationEventMarker, AutomationMode, AutomationOrigin, AutomationPauseReason, AutomationPrincipal, AutomationStatus, AutomationTrigger, AutomationUnattendedAsk, ScheduleMarker, TaskRunSkipReason, TaskRunStatus } from "../automations/types.js";
@@ -399,7 +399,8 @@ export interface ConversationsTable {
399
399
  create_request_hash: ColumnType<string | null, string | null | undefined, string | null>;
400
400
  id: string;
401
401
  org_id: string;
402
- agent_id: string;
402
+ /** 0227: null exactly when `kind` is 'external' (`conversations_external_shape`). */
403
+ agent_id: string | null;
403
404
  account_id: string;
404
405
  title: string | null;
405
406
  last_seq: Int8;
@@ -455,6 +456,29 @@ export interface ConversationsTable {
455
456
  project_name: ColumnType<string | null, string | null | undefined, never>;
456
457
  /** 0133: the absolute path the bound project resolved to at creation; null: free mode. */
457
458
  project_path: ColumnType<string | null, string | null | undefined, never>;
459
+ /** 0227: the target an external conversation is held with (set once); null for other kinds. */
460
+ external: ColumnType<ExternalRef | null, string | null | undefined, never>;
461
+ /** 0227: what the target last reported (external conversations; 'idle' for the others). */
462
+ external_state: ColumnType<ExternalConversationState, ExternalConversationState | undefined, ExternalConversationState>;
463
+ /**
464
+ * 0227: the highest `external_user_message.deliverySeq` handed to the target; -1 (written only
465
+ * by the kernel) once the conversation's `start` was dropped after its retries.
466
+ */
467
+ external_delivered_seq: Int8;
468
+ }
469
+ /** `conversations.external` (0227): the `conversation-target@1` target of an external conversation. */
470
+ export interface ExternalRef {
471
+ /** The extension that provides the target. */
472
+ extension: string;
473
+ targetKey: string;
474
+ /** The target's label as written at creation. */
475
+ label: string;
476
+ /** The options chosen for the start on the new conversation page (absent: none recorded). */
477
+ options?: {
478
+ model?: string;
479
+ effort?: string;
480
+ mode?: string;
481
+ };
458
482
  }
459
483
  /** 0060: an org's order of file-preview@1 previewers (UI refresh B Task 11). */
460
484
  export interface FilePreviewersTable {
@@ -514,8 +538,11 @@ export interface ConversationSubject {
514
538
  id: string;
515
539
  title: string;
516
540
  }
517
- /** chat; eval (a hidden full-run replay conversation); subagent (0053: a sub-agent's conversation). */
518
- export type ConversationKind = "chat" | "eval" | "subagent";
541
+ /**
542
+ * chat; eval (a hidden full-run replay conversation); subagent (0053: a sub-agent's conversation);
543
+ * external (0227: mirrored from a `conversation-target@1` target; no agent, never a run).
544
+ */
545
+ export type ConversationKind = "chat" | "eval" | "subagent" | "external";
519
546
  /** 0006_conversations.sql: append-only conversation event log. */
520
547
  export interface ConversationEventsTable {
521
548
  conversation_id: string;
@@ -74,9 +74,10 @@ function resolveAt(at) {
74
74
  return { orgId: call.orgId, accountId: call.accountId, deviceId, call };
75
75
  }
76
76
  const person = personOf(at.person);
77
- if (person === null)
77
+ // a handle bound to one device (a conversation target's call) reaches that device only
78
+ if (person === null || (person.deviceId !== undefined && person.deviceId !== deviceId))
78
79
  throw new DeviceAccessError("invalid_request", HOST_SCOPE_TEXT);
79
- return { ...person, deviceId, call: null };
80
+ return { orgId: person.orgId, accountId: person.accountId, deviceId, call: null };
80
81
  }
81
82
  /**
82
83
  * Host device services (local agents spec, Part 1): a service of a platform-trusted extension that
@@ -1,10 +1,19 @@
1
1
  import type { DevicePersonHandle } from "@capybara-hq/plugin-sdk";
2
- /** A new handle for `accountId` in `orgId`, live until {@link revokePersonHandle}. */
3
- export declare function issuePersonHandle(orgId: string, accountId: string): DevicePersonHandle;
4
- /** Ends the handle: later host service calls with it are refused. */
5
- export declare function revokePersonHandle(handle: DevicePersonHandle): void;
6
- /** The org and account of a live handle the kernel issued; null for anything else. */
7
- export declare function personOf(handle: unknown): {
2
+ /**
3
+ * What a live handle stands for; `deviceId` only for a handle bound to one device (null: bound to
4
+ * none, so no device is reached with it).
5
+ */
6
+ export interface PersonHandleScope {
8
7
  orgId: string;
9
8
  accountId: string;
10
- } | null;
9
+ deviceId?: string | null;
10
+ }
11
+ /**
12
+ * A new handle for `accountId` in `orgId`, live until {@link revokePersonHandle}; with `deviceId`,
13
+ * valid for that device only (null: for no device).
14
+ */
15
+ export declare function issuePersonHandle(orgId: string, accountId: string, deviceId?: string | null): DevicePersonHandle;
16
+ /** Ends the handle: later host service calls with it are refused. */
17
+ export declare function revokePersonHandle(handle: DevicePersonHandle): void;
18
+ /** The org, account (and bound device) of a live handle the kernel issued; null for anything else. */
19
+ export declare function personOf(handle: unknown): PersonHandleScope | null;