@capybara-hq/kernel 0.1.0-rc.134 → 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 (113) hide show
  1. package/bootstrap.json +1 -1
  2. package/dist/admin/admin.module.js +3 -0
  3. package/dist/admin/health.service.d.ts +2 -2
  4. package/dist/admin/health.service.js +6 -2
  5. package/dist/catalog/marketplaces.service.d.ts +1 -1
  6. package/dist/config/schema.d.ts +7 -0
  7. package/dist/config/schema.js +60 -2
  8. package/dist/conversations/access.d.ts +15 -7
  9. package/dist/conversations/access.js +59 -10
  10. package/dist/conversations/conversation-agent.d.ts +18 -0
  11. package/dist/conversations/conversation-agent.js +23 -0
  12. package/dist/conversations/conversation-ref.d.ts +3 -2
  13. package/dist/conversations/conversation-ref.js +6 -1
  14. package/dist/conversations/conversations.controller.d.ts +28 -5
  15. package/dist/conversations/conversations.controller.js +99 -10
  16. package/dist/conversations/conversations.module.js +10 -0
  17. package/dist/conversations/conversations.schemas.d.ts +6 -0
  18. package/dist/conversations/conversations.schemas.js +15 -0
  19. package/dist/conversations/conversations.service.d.ts +125 -21
  20. package/dist/conversations/conversations.service.js +260 -90
  21. package/dist/conversations/event-log.d.ts +9 -1
  22. package/dist/conversations/event-log.js +2 -0
  23. package/dist/conversations/events.d.ts +57 -0
  24. package/dist/conversations/events.js +73 -1
  25. package/dist/conversations/external/external-calls.d.ts +75 -0
  26. package/dist/conversations/external/external-calls.js +91 -0
  27. package/dist/conversations/external/external-calls.processor.d.ts +45 -0
  28. package/dist/conversations/external/external-calls.processor.js +144 -0
  29. package/dist/conversations/external/external-conversations.service.d.ts +266 -0
  30. package/dist/conversations/external/external-conversations.service.js +1138 -0
  31. package/dist/conversations/external/external.schemas.d.ts +63 -0
  32. package/dist/conversations/external/external.schemas.js +52 -0
  33. package/dist/conversations/external/token.d.ts +6 -0
  34. package/dist/conversations/external/token.js +6 -0
  35. package/dist/conversations/permission-profile-store.d.ts +4 -1
  36. package/dist/conversations/permission-profiles.controller.d.ts +33 -9
  37. package/dist/conversations/permission-profiles.controller.js +86 -6
  38. package/dist/conversations/prompt-suggestions.js +2 -1
  39. package/dist/conversations/queue.js +2 -1
  40. package/dist/conversations/titles.js +4 -3
  41. package/dist/ctx/create-ctx.d.ts +7 -0
  42. package/dist/ctx/create-ctx.js +45 -2
  43. package/dist/db/extension-db.d.ts +8 -3
  44. package/dist/db/extension-db.js +107 -7
  45. package/dist/db/extension-role-provision.d.ts +9 -0
  46. package/dist/db/extension-role-provision.js +89 -0
  47. package/dist/db/extension-schema-transfer.d.ts +2 -1
  48. package/dist/db/extension-schema-transfer.js +103 -19
  49. package/dist/db/kernel-schema.d.ts +31 -4
  50. package/dist/db/migrator.d.ts +2 -0
  51. package/dist/db/migrator.js +4 -3
  52. package/dist/device-access/host-services.js +3 -2
  53. package/dist/device-access/person-handles.d.ts +16 -7
  54. package/dist/device-access/person-handles.js +14 -9
  55. package/dist/devices/conversation-devices.d.ts +5 -0
  56. package/dist/devices/conversation-devices.js +16 -0
  57. package/dist/erasure/org-catalog.js +2 -2
  58. package/dist/errors.d.ts +34 -0
  59. package/dist/errors.js +34 -0
  60. package/dist/evals/snapshot.js +3 -1
  61. package/dist/evals/trajectory.service.d.ts +2 -2
  62. package/dist/evals/trajectory.service.js +11 -7
  63. package/dist/extensions/admin-ops.js +17 -1
  64. package/dist/extensions/extensions.module.js +3 -0
  65. package/dist/extensions/host.d.ts +9 -1
  66. package/dist/extensions/host.js +14 -2
  67. package/dist/extensions/migrate-lock.js +1 -0
  68. package/dist/extensions/permission-view.d.ts +3 -1
  69. package/dist/extensions/permission-view.js +4 -1
  70. package/dist/extensions/point-defaults.d.ts +13 -21
  71. package/dist/extensions/point-defaults.js +32 -72
  72. package/dist/extensions/point-serving.d.ts +56 -0
  73. package/dist/extensions/point-serving.js +120 -0
  74. package/dist/inbox/inbox-items.service.d.ts +11 -0
  75. package/dist/inbox/inbox-items.service.js +39 -0
  76. package/dist/index.d.ts +3 -1
  77. package/dist/index.js +3 -1
  78. package/dist/infra/database/rls-role.d.ts +4 -11
  79. package/dist/infra/database/rls-role.js +71 -27
  80. package/dist/infra/outbox/registry.d.ts +70 -0
  81. package/dist/infra/outbox/registry.js +44 -0
  82. package/dist/infra/queue/queue-names.d.ts +1 -1
  83. package/dist/infra/queue/queue-names.js +1 -0
  84. package/dist/kernel.d.ts +2 -0
  85. package/dist/kernel.js +12 -2
  86. package/dist/kernel.module.js +4 -0
  87. package/dist/lifecycle/kernel-lifecycle.js +2 -3
  88. package/dist/platform/exclusions.js +10 -0
  89. package/dist/platform/ops/conversations.ops.d.ts +8 -1
  90. package/dist/platform/ops/conversations.ops.js +52 -14
  91. package/dist/plugin-reads/plugin-reads.service.js +4 -1
  92. package/dist/push/recipients.js +5 -2
  93. package/dist/retention/worker.js +2 -1
  94. package/dist/roles/worker-role.d.ts +3 -1
  95. package/dist/roles/worker-role.js +8 -2
  96. package/dist/roles/worker.module.js +3 -0
  97. package/dist/runtime/context/build.js +8 -0
  98. package/dist/runtime/context/compaction.js +7 -0
  99. package/dist/runtime/idle-arm.js +3 -1
  100. package/dist/runtime/idle-compaction.js +2 -1
  101. package/dist/runtime/run-finish.js +2 -1
  102. package/dist/runtime/run-jobs.js +2 -1
  103. package/dist/runtime/run-queue.js +4 -2
  104. package/dist/runtime/run-worker.js +5 -2
  105. package/dist/runtime/stream.js +10 -0
  106. package/dist/runtime/usage-report.js +2 -1
  107. package/dist/runtime/waits.js +2 -1
  108. package/dist/tools/approvals.service.js +6 -2
  109. package/dist/tools/builtins/skill-load.js +3 -2
  110. package/dist/tools/tool-watch.service.js +3 -1
  111. package/package.json +3 -3
  112. package/src/migrations/0226_enable_kernel_rls.sql +30 -0
  113. 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
@@ -5,11 +5,15 @@ export type ExtensionDbConnection = {
5
5
  login: string;
6
6
  url: string;
7
7
  separate: boolean;
8
+ /** Only dedicated identities can be handed to an isolated extension. */
9
+ dedicated?: true;
8
10
  };
9
11
  /** Kernel-owned credentials, resolved from the canonical extension name. */
10
12
  export interface ExtensionDbIdentity {
11
13
  resolve(name: string): ExtensionDbConnection;
12
14
  readonly sharedLogin?: string | undefined;
15
+ /** Used only by the one-shot operator to provision staged extensions. */
16
+ provisionedNames?(): string[];
13
17
  }
14
18
  export declare class ConfiguredExtensionDbIdentity implements ExtensionDbIdentity {
15
19
  private readonly identity;
@@ -17,11 +21,12 @@ export declare class ConfiguredExtensionDbIdentity implements ExtensionDbIdentit
17
21
  get sharedLogin(): string | undefined;
18
22
  resolve(name: string): ExtensionDbConnection;
19
23
  }
20
- export declare function extensionDbIdentity(db: Pick<KernelConfig["db"], "url" | "extensionsUrl">): ExtensionDbIdentity;
24
+ export declare function validateExtensionCredentials(db: Pick<KernelConfig["db"], "extensionsUrl" | "extensionCredentialsDir">): void;
25
+ export declare function extensionDbIdentity(db: Pick<KernelConfig["db"], "url" | "extensionsUrl" | "extensionCredentialsDir">): ExtensionDbIdentity;
21
26
  export declare function pluginSchemaName(name: string): string;
22
- export declare function assertExtensionSession(client: pg.ClientBase, login: string): Promise<void>;
27
+ export declare function assertExtensionSession(client: pg.ClientBase, login: string, dedicatedSchema?: string): Promise<void>;
23
28
  /** A missing schema is normal before a plugin's first migration. */
24
- export declare function assertExtensionSchemaOwner(client: pg.ClientBase, schema: string, login: string): Promise<void>;
29
+ export declare function assertExtensionSchemaOwner(client: pg.ClientBase, schema: string, login: string, required?: boolean): Promise<void>;
25
30
  /** One small, scope-aware pool per active extension instance. The host owns its lifetime. */
26
31
  export declare function extensionDbPool(identity: ExtensionDbConnection, name: string, config: {
27
32
  connectTimeoutMs?: number | undefined;