@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
@@ -8,6 +8,7 @@ import { Module } from "@nestjs/common";
8
8
  import { CatalogModule } from "../catalog/catalog.module.js";
9
9
  import { TemplateConnectorsQueueModule } from "../catalog/template-connector-jobs.js";
10
10
  import { ChannelsModule } from "../channels/channels.module.js";
11
+ import { ExternalConversationsModule } from "../conversations/external/external-conversations.service.js";
11
12
  import { PromptSuggestionsModule } from "../conversations/prompt-suggestions.js";
12
13
  import { TitlesModule } from "../conversations/titles.js";
13
14
  import { DeviceServiceEventsModule } from "../device-access/service-events.js";
@@ -75,6 +76,8 @@ AdminModule = __decorate([
75
76
  TemplateConnectorsQueueModule,
76
77
  // the device service events queue the overview counts
77
78
  DeviceServiceEventsModule,
79
+ // the external conversation calls queue the overview counts
80
+ ExternalConversationsModule,
78
81
  // the price table of the usage aggregate
79
82
  ModelsModule,
80
83
  ],
@@ -5,7 +5,7 @@ import { type LiveReplica, ReplicaPresence } from "../infra/presence/replica-pre
5
5
  import type { KernelLogger } from "../log.js";
6
6
  import { DeviceProviders } from "../sandbox/providers.js";
7
7
  /** The kernel's own queues, in the order the overview lists them (extension queues are not read). */
8
- export declare const KERNEL_QUEUE_NAMES: readonly ["cap-kernel-runs", "cap-kernel-subagent-runs", "cap-kernel-channels", "cap-kernel-maintenance", "cap-kernel-tool-watch", "cap-kernel-plugin-scope", "cap-kernel-titles", "cap-kernel-suggestions", "cap-kernel-usage-report", "cap-kernel-evals", "cap-kernel-lifecycle", "cap-push-deliver", "cap-connector-tools", "cap-template-connectors", "cap-device-service-events"];
8
+ export declare const KERNEL_QUEUE_NAMES: readonly ["cap-kernel-runs", "cap-kernel-subagent-runs", "cap-kernel-channels", "cap-kernel-maintenance", "cap-kernel-tool-watch", "cap-kernel-plugin-scope", "cap-kernel-titles", "cap-kernel-suggestions", "cap-kernel-usage-report", "cap-kernel-evals", "cap-kernel-lifecycle", "cap-push-deliver", "cap-connector-tools", "cap-template-connectors", "cap-device-service-events", "cap-external-calls"];
9
9
  /** How long each source's reads may take before the answer marks it unavailable. */
10
10
  export declare const HEALTH_READ_TIMEOUT_MS = 3000;
11
11
  /** A live replica as the overview shows it. */
@@ -110,7 +110,7 @@ export declare class AdminHealthService {
110
110
  private readonly log;
111
111
  private readonly providers;
112
112
  private readonly queues;
113
- constructor(presence: Pick<ReplicaPresence, "live">, db: KernelDb, redis: Pick<Redis, "zcount" | "status">, log: Pick<KernelLogger, "warn">, providers: Pick<DeviceProviders, "forDevice">, runs: Queue, subagentRuns: Queue, channels: Queue, maintenance: Queue, toolWatch: Queue, pluginScope: Queue, titles: Queue, suggestions: Queue, usageReport: Queue, evals: Queue, lifecycle: Queue, push: Queue, connectorTools: Queue, templateConnectors: Queue, serviceEvents: Queue);
113
+ constructor(presence: Pick<ReplicaPresence, "live">, db: KernelDb, redis: Pick<Redis, "zcount" | "status">, log: Pick<KernelLogger, "warn">, providers: Pick<DeviceProviders, "forDevice">, runs: Queue, subagentRuns: Queue, channels: Queue, maintenance: Queue, toolWatch: Queue, pluginScope: Queue, titles: Queue, suggestions: Queue, usageReport: Queue, evals: Queue, lifecycle: Queue, push: Queue, connectorTools: Queue, templateConnectors: Queue, serviceEvents: Queue, externalCalls: Queue);
114
114
  read(): Promise<AdminHealth>;
115
115
  private readRedis;
116
116
  private readDb;
@@ -13,6 +13,7 @@ import { sql } from "kysely";
13
13
  import { PLUGIN_SCOPE_QUEUE } from "../catalog/scope-sync.js";
14
14
  import { TEMPLATE_CONNECTORS_QUEUE } from "../catalog/template-connector-jobs.js";
15
15
  import { CHANNEL_QUEUE_NAME } from "../channels/jobs.js";
16
+ import { EXTERNAL_CALLS_QUEUE } from "../conversations/external/external-calls.js";
16
17
  import { PROMPT_SUGGESTION_QUEUE } from "../conversations/prompt-suggestions.js";
17
18
  import { TITLE_QUEUE } from "../conversations/titles.js";
18
19
  import { SERVICE_EVENTS_QUEUE } from "../device-access/service-events.js";
@@ -47,6 +48,7 @@ export const KERNEL_QUEUE_NAMES = [
47
48
  CONNECTOR_TOOLS_QUEUE,
48
49
  TEMPLATE_CONNECTORS_QUEUE,
49
50
  SERVICE_EVENTS_QUEUE,
51
+ EXTERNAL_CALLS_QUEUE,
50
52
  ];
51
53
  /** How long each source's reads may take before the answer marks it unavailable. */
52
54
  export const HEALTH_READ_TIMEOUT_MS = 3_000;
@@ -75,7 +77,7 @@ let AdminHealthService = class AdminHealthService {
75
77
  log;
76
78
  providers;
77
79
  queues;
78
- constructor(presence, db, redis, log, providers, runs, subagentRuns, channels, maintenance, toolWatch, pluginScope, titles, suggestions, usageReport, evals, lifecycle, push, connectorTools, templateConnectors, serviceEvents) {
80
+ constructor(presence, db, redis, log, providers, runs, subagentRuns, channels, maintenance, toolWatch, pluginScope, titles, suggestions, usageReport, evals, lifecycle, push, connectorTools, templateConnectors, serviceEvents, externalCalls) {
79
81
  this.presence = presence;
80
82
  this.db = db;
81
83
  this.redis = redis;
@@ -98,6 +100,7 @@ let AdminHealthService = class AdminHealthService {
98
100
  connectorTools,
99
101
  templateConnectors,
100
102
  serviceEvents,
103
+ externalCalls,
101
104
  ];
102
105
  }
103
106
  async read() {
@@ -311,6 +314,7 @@ AdminHealthService = __decorate([
311
314
  __param(16, Inject(getQueueToken(PUSH_QUEUE))),
312
315
  __param(17, Inject(getQueueToken(CONNECTOR_TOOLS_QUEUE))),
313
316
  __param(18, Inject(getQueueToken(TEMPLATE_CONNECTORS_QUEUE))),
314
- __param(19, Inject(getQueueToken(SERVICE_EVENTS_QUEUE)))
317
+ __param(19, Inject(getQueueToken(SERVICE_EVENTS_QUEUE))),
318
+ __param(20, Inject(getQueueToken(EXTERNAL_CALLS_QUEUE)))
315
319
  ], AdminHealthService);
316
320
  export { AdminHealthService };
@@ -209,7 +209,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
209
209
  /** The host versions (an entry's `minKernel` is judged against them). */
210
210
  export declare const HOST_VERSIONS: {
211
211
  readonly kernel: string;
212
- readonly sdk: "0.1.0-rc.99";
212
+ readonly sdk: "0.1.0-rc.100";
213
213
  };
214
214
  /** Whether this deployment satisfies the entry's `minKernel`. */
215
215
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -1,5 +1,6 @@
1
1
  import { type Expression, type ExpressionBuilder, type SqlBool } from "kysely";
2
2
  import type { KernelDatabase } from "../db/kernel-schema.js";
3
+ import { ExtensionPointServing } from "../extensions/point-serving.js";
3
4
  import { KernelDb } from "../infra/database/kernel-db.js";
4
5
  /**
5
6
  * A sub-agent's conversation is reached through the root of its tree (sub-agents spec §6.1,
@@ -11,27 +12,34 @@ import { KernelDb } from "../infra/database/kernel-db.js";
11
12
  */
12
13
  export declare const parentReachable: (viewerAccountId: string | Expression<string>) => (eb: ExpressionBuilder<KernelDatabase, "conversations">) => import("kysely").ExpressionWrapper<KernelDatabase, "conversations", SqlBool>;
13
14
  /**
14
- * The predicate of {@link ConversationAccess.isAccessible} over the `conversations` table (the
15
+ * The chat predicate of {@link ConversationAccess.isAccessible} over the `conversations` table (the
15
16
  * org is the caller's condition): the conversation belongs to the viewer and is not deleted, it is
16
17
  * a chat or sub-agent conversation whose tree root is reachable ({@link parentReachable}), the
17
18
  * viewer's account is active, and its agent is not deleted and still visible to the viewer
18
- * (`visibleTo` includes "the org is not deleted, the viewer is still a member"). The viewer may be
19
- * a column of the outer query: the share liveness check (`shares/liveness.ts`) asks it of each
19
+ * (`visibleTo` includes "the org is not deleted, the viewer is still a member"). An external
20
+ * conversation is not admitted here (it needs its target's serving check). The viewer may be a
21
+ * column of the outer query: the share liveness check (`shares/liveness.ts`) asks it of each
20
22
  * share's creator (`sql.ref("file_shares.created_by")`) in the same query.
21
23
  */
22
24
  export declare const accessibleTo: (viewer: string | Expression<string>) => (eb: ExpressionBuilder<KernelDatabase, "conversations">) => Expression<SqlBool>;
23
25
  /**
24
26
  * Whether a person may still see a conversation (one query, no agent view): what the event stream,
25
27
  * attachment downloads, file and output reads and the extension UI check. `ConversationsService`
26
- * delegates to it; it depends on the database only, so the attachments (which the skills and tools
27
- * use) can check access without the conversations module.
28
+ * delegates to it; it depends on the database and, for an external conversation, on whether its
29
+ * extension serves the org ({@link ExtensionPointServing}, below the extensions module), so the attachments (which the skills and tools use) can check
30
+ * access without the conversations module.
28
31
  */
29
32
  export declare class ConversationAccess {
30
33
  private readonly db;
31
- constructor(db: KernelDb);
34
+ /** Whether an external conversation's extension serves the org. */
35
+ private readonly serving;
36
+ constructor(db: KernelDb,
37
+ /** Whether an external conversation's extension serves the org. */
38
+ serving: Pick<ExtensionPointServing, "serves">);
32
39
  /**
33
40
  * The light visibility check (one query, no agent view) used when a long connection (SSE) opens
34
- * and on its periodic re-check: {@link accessibleTo} for a conversation of this org.
41
+ * and on its periodic re-check: {@link accessibleTo} for a conversation of this org, an external
42
+ * conversation's extension checked for serving `conversation-target@1` in the org.
35
43
  */
36
44
  isAccessible(orgId: string, conversationId: string, viewerAccountId: string): Promise<boolean>;
37
45
  }
@@ -10,7 +10,9 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { Inject, Injectable, Module } from "@nestjs/common";
11
11
  import { sql } from "kysely";
12
12
  import { visibleTo } from "../agents/agent-lookup.js";
13
+ import { ExtensionPointServing, ExtensionPointServingModule } from "../extensions/point-serving.js";
13
14
  import { KernelDb } from "../infra/database/kernel-db.js";
15
+ import { TARGET_POINT } from "./external/external-calls.js";
14
16
  /**
15
17
  * The root of a sub-agent conversation's tree, as a correlated scalar subquery: walks
16
18
  * `parent_conversation_id` up from the conversation's parent through sub-agent conversations of
@@ -54,12 +56,13 @@ export const parentReachable = (viewerAccountId) => (eb) => eb.or([
54
56
  .where(visibleTo(viewerAccountId))),
55
57
  ]);
56
58
  /**
57
- * The predicate of {@link ConversationAccess.isAccessible} over the `conversations` table (the
59
+ * The chat predicate of {@link ConversationAccess.isAccessible} over the `conversations` table (the
58
60
  * org is the caller's condition): the conversation belongs to the viewer and is not deleted, it is
59
61
  * a chat or sub-agent conversation whose tree root is reachable ({@link parentReachable}), the
60
62
  * viewer's account is active, and its agent is not deleted and still visible to the viewer
61
- * (`visibleTo` includes "the org is not deleted, the viewer is still a member"). The viewer may be
62
- * a column of the outer query: the share liveness check (`shares/liveness.ts`) asks it of each
63
+ * (`visibleTo` includes "the org is not deleted, the viewer is still a member"). An external
64
+ * conversation is not admitted here (it needs its target's serving check). The viewer may be a
65
+ * column of the outer query: the share liveness check (`shares/liveness.ts`) asks it of each
63
66
  * share's creator (`sql.ref("file_shares.created_by")`) in the same query.
64
67
  */
65
68
  export const accessibleTo = (viewer) => (eb) => eb.and([
@@ -80,20 +83,51 @@ export const accessibleTo = (viewer) => (eb) => eb.and([
80
83
  .where("agents.deleted_at", "is", null)
81
84
  .where(visibleTo(viewer))),
82
85
  ]);
86
+ /**
87
+ * An external conversation (local agents spec Part 2) of the viewer that is not deleted, the
88
+ * viewer's account active and still a member of the conversation's live org (it has no agent to
89
+ * check that through), of any extension: the caller checks that it serves the org.
90
+ */
91
+ const externalConversationOf = (viewer) => (eb) => eb.and([
92
+ eb("conversations.account_id", "=", viewer),
93
+ eb("conversations.deleted_at", "is", null),
94
+ eb("conversations.kind", "=", "external"),
95
+ eb.exists(eb
96
+ .selectFrom("accounts")
97
+ .select(sql `1`.as("one"))
98
+ .where("accounts.id", "=", viewer)
99
+ .where("accounts.status", "=", "active")),
100
+ eb.exists(eb
101
+ .selectFrom("orgs")
102
+ .select(sql `1`.as("one"))
103
+ .whereRef("orgs.id", "=", "conversations.org_id")
104
+ .where("orgs.deleted_at", "is", null)),
105
+ eb.exists(eb
106
+ .selectFrom("memberships")
107
+ .select(sql `1`.as("one"))
108
+ .whereRef("memberships.org_id", "=", "conversations.org_id")
109
+ .where("memberships.account_id", "=", viewer)),
110
+ ]);
83
111
  /**
84
112
  * Whether a person may still see a conversation (one query, no agent view): what the event stream,
85
113
  * attachment downloads, file and output reads and the extension UI check. `ConversationsService`
86
- * delegates to it; it depends on the database only, so the attachments (which the skills and tools
87
- * use) can check access without the conversations module.
114
+ * delegates to it; it depends on the database and, for an external conversation, on whether its
115
+ * extension serves the org ({@link ExtensionPointServing}, below the extensions module), so the attachments (which the skills and tools use) can check
116
+ * access without the conversations module.
88
117
  */
89
118
  let ConversationAccess = class ConversationAccess {
90
119
  db;
91
- constructor(db) {
120
+ serving;
121
+ constructor(db,
122
+ /** Whether an external conversation's extension serves the org. */
123
+ serving) {
92
124
  this.db = db;
125
+ this.serving = serving;
93
126
  }
94
127
  /**
95
128
  * The light visibility check (one query, no agent view) used when a long connection (SSE) opens
96
- * and on its periodic re-check: {@link accessibleTo} for a conversation of this org.
129
+ * and on its periodic re-check: {@link accessibleTo} for a conversation of this org, an external
130
+ * conversation's extension checked for serving `conversation-target@1` in the org.
97
131
  */
98
132
  async isAccessible(orgId, conversationId, viewerAccountId) {
99
133
  const row = await this.db
@@ -103,18 +137,33 @@ let ConversationAccess = class ConversationAccess {
103
137
  .where("conversations.org_id", "=", orgId)
104
138
  .where(accessibleTo(viewerAccountId))
105
139
  .executeTakeFirst();
106
- return row !== undefined;
140
+ if (row !== undefined)
141
+ return true;
142
+ // not a chat or sub-agent conversation the viewer may see: perhaps their external one
143
+ const ext = await this.db
144
+ .selectFrom("conversations")
145
+ .select(sql `conversations.external->>'extension'`.as("extension"))
146
+ .where("conversations.id", "=", conversationId)
147
+ .where("conversations.org_id", "=", orgId)
148
+ .where(externalConversationOf(viewerAccountId))
149
+ .executeTakeFirst();
150
+ return ext !== undefined && (await this.serving.serves(orgId, TARGET_POINT, ext.extension));
107
151
  }
108
152
  };
109
153
  ConversationAccess = __decorate([
110
154
  Injectable(),
111
- __param(0, Inject(KernelDb))
155
+ __param(0, Inject(KernelDb)),
156
+ __param(1, Inject(ExtensionPointServing))
112
157
  ], ConversationAccess);
113
158
  export { ConversationAccess };
114
159
  /** The one {@link ConversationAccess} (database only). */
115
160
  let ConversationAccessModule = class ConversationAccessModule {
116
161
  };
117
162
  ConversationAccessModule = __decorate([
118
- Module({ providers: [ConversationAccess], exports: [ConversationAccess] })
163
+ Module({
164
+ imports: [ExtensionPointServingModule],
165
+ providers: [ConversationAccess],
166
+ exports: [ConversationAccess],
167
+ })
119
168
  ], ConversationAccessModule);
120
169
  export { ConversationAccessModule };
@@ -0,0 +1,18 @@
1
+ import type { ConversationKind } from "../db/kernel-schema.js";
2
+ /** The kinds that run an agent: every kind but 'external' (0227). */
3
+ export type AgentConversationKind = Exclude<ConversationKind, "external">;
4
+ /**
5
+ * The agent of a conversation row read by code that reaches only agent conversations: it filters
6
+ * by kind, or it starts from a run, a queue or an approval (an external conversation has none).
7
+ * `conversations_external_shape` makes `agent_id` non-null for every kind but 'external', so a null
8
+ * here is a kernel bug and throws.
9
+ */
10
+ export declare function agentIdOf(row: {
11
+ agent_id: string | null;
12
+ }): string;
13
+ /** `kind` as an agent conversation's kind; throws for 'external', like {@link agentIdOf}. */
14
+ export declare function agentKindOf(kind: ConversationKind): AgentConversationKind;
15
+ /** {@link agentIdOf} for a conversation view (`ConversationView.agentId`). */
16
+ export declare function agentIdOfView(view: {
17
+ agentId: string | null;
18
+ }): string;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The agent of a conversation row read by code that reaches only agent conversations: it filters
3
+ * by kind, or it starts from a run, a queue or an approval (an external conversation has none).
4
+ * `conversations_external_shape` makes `agent_id` non-null for every kind but 'external', so a null
5
+ * here is a kernel bug and throws.
6
+ */
7
+ export function agentIdOf(row) {
8
+ if (row.agent_id === null) {
9
+ throw new Error("an external conversation reached code that needs a conversation's agent");
10
+ }
11
+ return row.agent_id;
12
+ }
13
+ /** `kind` as an agent conversation's kind; throws for 'external', like {@link agentIdOf}. */
14
+ export function agentKindOf(kind) {
15
+ if (kind === "external") {
16
+ throw new Error("an external conversation reached code that needs a conversation's agent");
17
+ }
18
+ return kind;
19
+ }
20
+ /** {@link agentIdOf} for a conversation view (`ConversationView.agentId`). */
21
+ export function agentIdOfView(view) {
22
+ return agentIdOf({ agent_id: view.agentId });
23
+ }
@@ -19,7 +19,7 @@ export interface ConversationRefSource {
19
19
  id: string;
20
20
  /** The title at send time; null: untitled. */
21
21
  title: string | null;
22
- /** The name of the conversation's agent. */
22
+ /** The name of the conversation's agent; an external conversation's target label. */
23
23
  agentName: string;
24
24
  /** When the conversation was last active (its `updated_at`). */
25
25
  lastActiveAt: Date;
@@ -53,6 +53,7 @@ export declare function conversationRefText(src: ConversationRefSource): string;
53
53
  * no nested blocks), an `assistant_message`'s text blocks (no thinking, tool calls or results).
54
54
  * A skill invocation contributes what the person typed (`/name args`), never the rendered skill
55
55
  * in `content[0]`; a template sub-agent's skill (or its notice) contributes nothing, like
56
- * `caseTitle` (evals/sets.service.ts).
56
+ * `caseTitle` (evals/sets.service.ts). An external conversation's `external_user_message` and
57
+ * `external_message` contribute their text (local agents spec Part 2).
57
58
  */
58
59
  export declare function refMessageText(type: string, payload: unknown): string;
@@ -72,9 +72,14 @@ export function conversationRefText(src) {
72
72
  * no nested blocks), an `assistant_message`'s text blocks (no thinking, tool calls or results).
73
73
  * A skill invocation contributes what the person typed (`/name args`), never the rendered skill
74
74
  * in `content[0]`; a template sub-agent's skill (or its notice) contributes nothing, like
75
- * `caseTitle` (evals/sets.service.ts).
75
+ * `caseTitle` (evals/sets.service.ts). An external conversation's `external_user_message` and
76
+ * `external_message` contribute their text (local agents spec Part 2).
76
77
  */
77
78
  export function refMessageText(type, payload) {
79
+ if (type === "external_user_message" || type === "external_message") {
80
+ const text = payload?.text;
81
+ return typeof text === "string" ? text.trim() : "";
82
+ }
78
83
  const content = payload?.content;
79
84
  if (!Array.isArray(content))
80
85
  return "";
@@ -11,6 +11,8 @@ import { CompactBody, EventsQuery, FilesQuery, IdParams, ListQuery, PatchBody, S
11
11
  import { type ConversationGroup, type ConversationListRow, ConversationsService, type ConversationView, type SubagentView, type UsageTotals } from "./conversations.service.js";
12
12
  import { ConversationDeviceStatus } from "./device-status.js";
13
13
  import type { ConversationEvent } from "./events.js";
14
+ import { ExternalAnswerBody, ExternalRequestParams } from "./external/external.schemas.js";
15
+ import { ExternalConversationsService } from "./external/external-conversations.service.js";
14
16
  import { ConversationFiles, type FileOutput } from "./files.js";
15
17
  import { ConversationOutputs, type OutputPage } from "./outputs-read.js";
16
18
  import type { QueueItem, QueuePauseReason } from "./queue.js";
@@ -71,6 +73,11 @@ export declare const MessageTokenSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
71
73
  type: z.ZodLiteral<"conversation">;
72
74
  id: z.ZodString;
73
75
  }, z.core.$strict>], "type">;
76
+ /**
77
+ * `POST …/messages`. On an external conversation only `text` (with `clientMessageId` and the
78
+ * browser context) and `interrupt` (stop the target's current turn first) are taken; the other
79
+ * fields are `conversation.external_fields`, and so is `interrupt` on any other conversation.
80
+ */
74
81
  declare const MessageBody: z.ZodObject<{
75
82
  text: z.ZodString;
76
83
  clientMessageId: z.ZodOptional<z.ZodString>;
@@ -112,6 +119,7 @@ declare const MessageBody: z.ZodObject<{
112
119
  en: "en";
113
120
  zh: "zh";
114
121
  }>>;
122
+ interrupt: z.ZodOptional<z.ZodBoolean>;
115
123
  }, z.core.$strict>;
116
124
  /**
117
125
  * `POST /conversations`: `message` creates the conversation with its first message (create on
@@ -184,7 +192,8 @@ export declare class ConversationsController {
184
192
  private readonly toolInfo;
185
193
  private readonly queue;
186
194
  private readonly files;
187
- constructor(conversations: ConversationsService, outputs: ConversationOutputs, artifacts: ConversationArtifacts, deviceStatus: ConversationDeviceStatus, toolInfo: ConversationToolInfo, queue: ConversationQueue, files: ConversationFiles);
195
+ private readonly external;
196
+ constructor(conversations: ConversationsService, outputs: ConversationOutputs, artifacts: ConversationArtifacts, deviceStatus: ConversationDeviceStatus, toolInfo: ConversationToolInfo, queue: ConversationQueue, files: ConversationFiles, external: Pick<ExternalConversationsService, "find" | "send" | "stop" | "answer">);
188
197
  /**
189
198
  * 201 when created; 200 when `message.clientMessageId` repeats an earlier first send. With a
190
199
  * message the answer has `event` (the `user_message`) and `events`: every event the first send
@@ -205,7 +214,8 @@ export declare class ConversationsController {
205
214
  /** Soft delete (owner only): stops an active run and hides the conversation everywhere. */
206
215
  remove(principal: Principal, org: OrgContext, { id }: z.infer<typeof IdParams>): Promise<void>;
207
216
  /**
208
- * My conversations, most recently updated first, each with its agent: `next` is the next page's
217
+ * My conversations, most recently updated first, each with its agent (null for an external
218
+ * conversation; `target` keeps one target's, local agents spec Part 2): `next` is the next page's
209
219
  * cursor (passed back as `after`), null when there are no more; `total` counts every match of
210
220
  * the filters and comes only when asked (`withTotal=true`) on the first page (no `after`).
211
221
  */
@@ -215,8 +225,9 @@ export declare class ConversationsController {
215
225
  total?: number;
216
226
  }>;
217
227
  /**
218
- * My conversations grouped by agent, for the sidebar: groups by latest activity, `perGroup`
219
- * newest conversations each with `more`; `next` is the last group's agent id (passed back as
228
+ * My conversations grouped by agent, and my external ones by target, for the sidebar: groups by
229
+ * latest activity, `perGroup` newest conversations each with `more`; `next` is the last group's
230
+ * key (passed back as
220
231
  * `after`), null when there are no more groups. Declared before `:id` so it is not captured.
221
232
  */
222
233
  groups(principal: Principal, org: OrgContext, q: z.infer<typeof GroupsQuery>): Promise<{
@@ -317,6 +328,8 @@ export declare class ConversationsController {
317
328
  postMessage(principal: Principal, org: OrgContext, id: string, body: z.infer<typeof MessageBody>, reply: FastifyReply): Promise<{
318
329
  event: ConversationEvent;
319
330
  }>;
331
+ /** {@link postMessage} on a conversation Capybara runs. */
332
+ private postChatMessage;
320
333
  /**
321
334
  * Queued messages (owner only): `paused` after a run failed or was stopped with items queued, or
322
335
  * the head item could not be sent; `pauseReason` says which (absent when not recorded).
@@ -344,9 +357,19 @@ export declare class ConversationsController {
344
357
  * ran). On a sub-agent's conversation (the root's owner, at any depth) the
345
358
  * sub-agent stops with every sub-agent below it, and `runId` is the sub-agent's latest run,
346
359
  * which may already be finished when only its descendants were working (agent map spec §6).
360
+ * On an external conversation the target's `stop` is owed and `runId` is null.
347
361
  */
348
362
  abort(principal: Principal, org: OrgContext, id: string): Promise<{
349
- runId: string;
363
+ runId: string | null;
364
+ }>;
365
+ /**
366
+ * The person's answer to a local agent's request (`external_request`, local agents spec Part 2,
367
+ * call 8): 202 `{ event }`, the `external_request_answered` written once (the first answer wins;
368
+ * a second → 409 `conversation.request_answered`) and the target's `answer` owed. An unknown
369
+ * request → 404 `conversation.request_not_found`; an option it does not offer → 400.
370
+ */
371
+ answerExternal(principal: Principal, org: OrgContext, params: z.infer<typeof ExternalRequestParams>, body: z.infer<typeof ExternalAnswerBody>): Promise<{
372
+ event: ConversationEvent;
350
373
  }>;
351
374
  /**
352
375
  * Manual compaction (context compaction spec §4.7): starts a compact run that summarizes the
@@ -11,6 +11,7 @@ import { isDeviceProjectName } from "@capybara-hq/plugin-sdk";
11
11
  import { Controller, Delete, Get, Header, HttpCode, Inject, Param, Patch, Post, Res, } from "@nestjs/common";
12
12
  import { z } from "zod";
13
13
  import { ModelRef } from "../agents/definition.js";
14
+ import { ApiError } from "../errors.js";
14
15
  import { requestSignal } from "../http/request-signal.js";
15
16
  import { CurrentPrincipal, requireUser } from "../identity/principal.js";
16
17
  import { createZodDto } from "../infra/validation/create-zod-dto.js";
@@ -20,9 +21,11 @@ import { MAX_ATTACHMENTS } from "../tools/connector-content.js";
20
21
  import { ConversationToolInfo, TOOL_INFO_KEY_MAX, TOOL_INFO_MAX_KEYS, } from "../tools/info.js";
21
22
  import { ARTIFACT_DOWNLOAD_CACHE_SECONDS, ConversationArtifacts, } from "./artifacts.js";
22
23
  import { MAX_CONVERSATION_REFS } from "./conversation-ref.js";
23
- import { CompactBody, DOWNLOAD_AS, EventsQuery, FilesQuery, IdParams, ListQuery, PatchBody, SubagentsQuery, searchFields, } from "./conversations.schemas.js";
24
+ import { CompactBody, DOWNLOAD_AS, EventsQuery, FilesQuery, IdParams, ListQuery, PatchBody, SubagentsQuery, searchFields, targetRefOf, } from "./conversations.schemas.js";
24
25
  import { ConversationsService, MAX_PROJECT_FILES, } from "./conversations.service.js";
25
26
  import { ConversationDeviceStatus } from "./device-status.js";
27
+ import { ExternalAnswerBody, ExternalRequestParams } from "./external/external.schemas.js";
28
+ import { ExternalConversationsService } from "./external/external-conversations.service.js";
26
29
  import { ConversationFiles, FILE_CONTENT_MAX_BYTES } from "./files.js";
27
30
  import { countMarkers, MAX_CONNECTOR_MENTIONS, MAX_TOKENS, tokenEntityKey, } from "./inline-tokens.js";
28
31
  import { ConversationOutputs, OUTPUT_PAGE_MAX_CHARS } from "./outputs-read.js";
@@ -30,8 +33,11 @@ import { ConversationQueue } from "./queue.service.js";
30
33
  const GroupsQuery = z.object({
31
34
  perGroup: z.coerce.number().int().min(1).max(20).default(5),
32
35
  limit: z.coerce.number().int().min(1).max(50).default(20),
33
- /** The last group's agent id from the previous page (`next`). */
34
- after: z.string().min(1).max(100).optional(),
36
+ /**
37
+ * The last group's key from the previous page (`next`): an agent id, or
38
+ * `target/<extension>/<targetKey>`.
39
+ */
40
+ after: z.string().min(1).max(200).optional(),
35
41
  ...searchFields,
36
42
  });
37
43
  /** `?keys=a,b`: 1–100 comma-separated tool keys of 1–200 characters each. */
@@ -173,9 +179,17 @@ function tokenRules(b, ctx) {
173
179
  }
174
180
  }
175
181
  }
176
- const MessageBody = MessageFields.strict()
182
+ /**
183
+ * `POST …/messages`. On an external conversation only `text` (with `clientMessageId` and the
184
+ * browser context) and `interrupt` (stop the target's current turn first) are taken; the other
185
+ * fields are `conversation.external_fields`, and so is `interrupt` on any other conversation.
186
+ */
187
+ const MessageBody = MessageFields.extend({ interrupt: z.boolean().optional() })
188
+ .strict()
177
189
  .refine(...textRule)
178
190
  .superRefine(tokenRules);
191
+ /** The message fields an external conversation does not take. */
192
+ const NOT_EXTERNAL_FIELDS = ["tokens", "files", "model", "effort", "retryOf", "skill"];
179
193
  /**
180
194
  * `POST /conversations`: `message` creates the conversation with its first message (create on
181
195
  * first send; `clientMessageId` is required and makes a retry return the same conversation).
@@ -235,6 +249,10 @@ class ConversationQueueEditBodyDto extends createZodDto(QueueEditBody, "Conversa
235
249
  }
236
250
  class ConversationCompactBodyDto extends createZodDto(CompactBody, "ConversationCompactBody") {
237
251
  }
252
+ class ExternalRequestParamsDto extends createZodDto(ExternalRequestParams, "ConversationExternalRequestParams") {
253
+ }
254
+ class ExternalAnswerBodyDto extends createZodDto(ExternalAnswerBody, "ConversationExternalAnswer") {
255
+ }
238
256
  /**
239
257
  * 会话(`/api/v1/orgs/:orgId/conversations`):`agents.use`(访客以上),只接受人类用户;
240
258
  * 服务令牌 → 403 `forbidden`。只有会话所有者可见,其他人一律 `conversation.not_found`。
@@ -247,7 +265,8 @@ let ConversationsController = class ConversationsController {
247
265
  toolInfo;
248
266
  queue;
249
267
  files;
250
- constructor(conversations, outputs, artifacts, deviceStatus, toolInfo, queue, files) {
268
+ external;
269
+ constructor(conversations, outputs, artifacts, deviceStatus, toolInfo, queue, files, external) {
251
270
  this.conversations = conversations;
252
271
  this.outputs = outputs;
253
272
  this.artifacts = artifacts;
@@ -255,6 +274,7 @@ let ConversationsController = class ConversationsController {
255
274
  this.toolInfo = toolInfo;
256
275
  this.queue = queue;
257
276
  this.files = files;
277
+ this.external = external;
258
278
  }
259
279
  /**
260
280
  * 201 when created; 200 when `message.clientMessageId` repeats an earlier first send. With a
@@ -314,7 +334,8 @@ let ConversationsController = class ConversationsController {
314
334
  await this.conversations.remove(org.orgId, id, p.account.id);
315
335
  }
316
336
  /**
317
- * My conversations, most recently updated first, each with its agent: `next` is the next page's
337
+ * My conversations, most recently updated first, each with its agent (null for an external
338
+ * conversation; `target` keeps one target's, local agents spec Part 2): `next` is the next page's
318
339
  * cursor (passed back as `after`), null when there are no more; `total` counts every match of
319
340
  * the filters and comes only when asked (`withTotal=true`) on the first page (no `after`).
320
341
  */
@@ -325,6 +346,7 @@ let ConversationsController = class ConversationsController {
325
346
  total: q.withTotal === "true" && q.after === undefined,
326
347
  ...(q.after !== undefined && { after: q.after }),
327
348
  ...(q.agentId !== undefined && { agentId: q.agentId }),
349
+ ...(q.target !== undefined && { target: targetRefOf(q.target) }),
328
350
  ...(q.q !== undefined && { q: q.q }),
329
351
  ...(q.state !== undefined && { state: q.state }),
330
352
  ...(q.archived !== undefined && { archived: true }),
@@ -334,8 +356,9 @@ let ConversationsController = class ConversationsController {
334
356
  return { conversations, next, ...(total !== undefined && { total }) };
335
357
  }
336
358
  /**
337
- * My conversations grouped by agent, for the sidebar: groups by latest activity, `perGroup`
338
- * newest conversations each with `more`; `next` is the last group's agent id (passed back as
359
+ * My conversations grouped by agent, and my external ones by target, for the sidebar: groups by
360
+ * latest activity, `perGroup` newest conversations each with `more`; `next` is the last group's
361
+ * key (passed back as
339
362
  * `after`), null when there are no more groups. Declared before `:id` so it is not captured.
340
363
  */
341
364
  async groups(principal, org, q) {
@@ -477,8 +500,46 @@ let ConversationsController = class ConversationsController {
477
500
  }
478
501
  async postMessage(principal, org, id, body, reply) {
479
502
  const p = requireUser(principal);
503
+ const toExternal = async () => {
504
+ if (!(await this.external.find(org.orgId, id, p.account.id)))
505
+ return null;
506
+ const extra = NOT_EXTERNAL_FIELDS.filter((k) => body[k] !== undefined);
507
+ if (extra.length > 0)
508
+ throw new ApiError("conversation.external_fields", `A local agent's conversation takes text only, not ${extra.join(", ")}`);
509
+ return {
510
+ event: await this.external.send(org.orgId, id, p.account.id, {
511
+ text: body.text,
512
+ interrupt: body.interrupt ?? false,
513
+ ...(body.clientMessageId !== undefined && { clientMessageId: body.clientMessageId }),
514
+ }),
515
+ };
516
+ };
517
+ if (body.interrupt !== undefined) {
518
+ const sent = await toExternal();
519
+ if (sent)
520
+ return sent;
521
+ throw new ApiError("conversation.external_fields", "interrupt is only for a local agent's conversation");
522
+ }
523
+ // A chat message pays no external lookup: the chat path's own row read refuses an external
524
+ // conversation (`external_read_only`, or not found while its target does not serve the org),
525
+ // and only then is it looked up as one.
526
+ try {
527
+ return await this.postChatMessage(org.orgId, id, p.account.id, body, reply);
528
+ }
529
+ catch (err) {
530
+ if (err instanceof ApiError &&
531
+ (err.code === "conversation.external_read_only" || err.code === "conversation.not_found")) {
532
+ const sent = await toExternal();
533
+ if (sent)
534
+ return sent;
535
+ }
536
+ throw err;
537
+ }
538
+ }
539
+ /** {@link postMessage} on a conversation Capybara runs. */
540
+ async postChatMessage(orgId, id, accountId, body, reply) {
480
541
  return {
481
- event: await this.conversations.postUserMessage(org.orgId, id, p.account.id, {
542
+ event: await this.conversations.postUserMessage(orgId, id, accountId, {
482
543
  text: body.text,
483
544
  ...(body.clientMessageId !== undefined && { clientMessageId: body.clientMessageId }),
484
545
  ...(body.tokens !== undefined && { tokens: body.tokens }),
@@ -527,11 +588,29 @@ let ConversationsController = class ConversationsController {
527
588
  * ran). On a sub-agent's conversation (the root's owner, at any depth) the
528
589
  * sub-agent stops with every sub-agent below it, and `runId` is the sub-agent's latest run,
529
590
  * which may already be finished when only its descendants were working (agent map spec §6).
591
+ * On an external conversation the target's `stop` is owed and `runId` is null.
530
592
  */
531
593
  async abort(principal, org, id) {
532
594
  const p = requireUser(principal);
595
+ // an external conversation has no runs: its target is asked to stop (owed, `runId` null)
596
+ if (await this.external.find(org.orgId, id, p.account.id)) {
597
+ await this.external.stop(org.orgId, id, p.account.id);
598
+ return { runId: null };
599
+ }
533
600
  return { runId: await this.conversations.abort(org.orgId, id, p.account.id) };
534
601
  }
602
+ /**
603
+ * The person's answer to a local agent's request (`external_request`, local agents spec Part 2,
604
+ * call 8): 202 `{ event }`, the `external_request_answered` written once (the first answer wins;
605
+ * a second → 409 `conversation.request_answered`) and the target's `answer` owed. An unknown
606
+ * request → 404 `conversation.request_not_found`; an option it does not offer → 400.
607
+ */
608
+ async answerExternal(principal, org, params, body) {
609
+ const p = requireUser(principal);
610
+ return {
611
+ event: await this.external.answer(org.orgId, params.id, p.account.id, params.requestId, body.optionId),
612
+ };
613
+ }
535
614
  /**
536
615
  * Manual compaction (context compaction spec §4.7): starts a compact run that summarizes the
537
616
  * conversation's earlier history and returns its id (`202 { runId }`); while one is queued or
@@ -749,6 +828,15 @@ __decorate([
749
828
  __param(1, CurrentOrg()),
750
829
  __param(2, Param("id"))
751
830
  ], ConversationsController.prototype, "abort", null);
831
+ __decorate([
832
+ Post(":id/external-requests/:requestId"),
833
+ HttpCode(202),
834
+ OrgAction("agents.use"),
835
+ __param(0, CurrentPrincipal()),
836
+ __param(1, CurrentOrg()),
837
+ __param(2, ZParam(ExternalRequestParamsDto)),
838
+ __param(3, ZBody(ExternalAnswerBodyDto))
839
+ ], ConversationsController.prototype, "answerExternal", null);
752
840
  __decorate([
753
841
  Post(":id/compact"),
754
842
  HttpCode(202),
@@ -766,6 +854,7 @@ ConversationsController = __decorate([
766
854
  __param(3, Inject(ConversationDeviceStatus)),
767
855
  __param(4, Inject(ConversationToolInfo)),
768
856
  __param(5, Inject(ConversationQueue)),
769
- __param(6, Inject(ConversationFiles))
857
+ __param(6, Inject(ConversationFiles)),
858
+ __param(7, Inject(ExternalConversationsService))
770
859
  ], ConversationsController);
771
860
  export { ConversationsController };