@capybara-hq/kernel 0.1.0-rc.31 → 0.1.0-rc.33

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 (104) hide show
  1. package/dist/catalog/marketplaces.service.d.ts +1 -1
  2. package/dist/channels/inbound.d.ts +0 -25
  3. package/dist/channels/inbound.js +26 -1
  4. package/dist/channels/phrases.d.ts +28 -0
  5. package/dist/channels/phrases.js +28 -0
  6. package/dist/conversations/conversations.controller.d.ts +4 -1
  7. package/dist/conversations/conversations.controller.js +14 -2
  8. package/dist/conversations/conversations.service.d.ts +43 -3
  9. package/dist/conversations/conversations.service.js +93 -19
  10. package/dist/conversations/event-log.d.ts +3 -3
  11. package/dist/conversations/event-log.js +3 -3
  12. package/dist/conversations/events.d.ts +24 -0
  13. package/dist/conversations/events.js +69 -0
  14. package/dist/ctx/create-ctx.d.ts +26 -4
  15. package/dist/ctx/create-ctx.js +54 -34
  16. package/dist/db/kernel-schema.d.ts +20 -0
  17. package/dist/devices/conversation-devices.d.ts +57 -3
  18. package/dist/devices/conversation-devices.js +63 -11
  19. package/dist/devices/device-projects.service.d.ts +162 -0
  20. package/dist/devices/device-projects.service.js +503 -0
  21. package/dist/devices/devices.controller.d.ts +15 -2
  22. package/dist/devices/devices.controller.js +60 -3
  23. package/dist/devices/devices.module.js +15 -2
  24. package/dist/devices/devices.schemas.js +9 -1
  25. package/dist/devices/dto.d.ts +31 -0
  26. package/dist/devices/dto.js +38 -1
  27. package/dist/devices/working-root.d.ts +41 -0
  28. package/dist/devices/working-root.js +50 -0
  29. package/dist/errors.d.ts +39 -0
  30. package/dist/errors.js +39 -0
  31. package/dist/evals/run-replay.d.ts +9 -1
  32. package/dist/evals/run-replay.js +15 -1
  33. package/dist/extensions/permission-set.d.ts +7 -6
  34. package/dist/extensions/permission-set.js +9 -6
  35. package/dist/extensions/permission-view.d.ts +4 -4
  36. package/dist/extensions/permission-view.js +10 -5
  37. package/dist/http/app.d.ts +8 -2
  38. package/dist/http/app.js +12 -2
  39. package/dist/http/plugin-dispatch.d.ts +55 -18
  40. package/dist/http/plugin-dispatch.js +124 -29
  41. package/dist/http/plugin-route-access.d.ts +56 -0
  42. package/dist/http/plugin-route-access.js +192 -0
  43. package/dist/identity/auth.guard.d.ts +26 -12
  44. package/dist/identity/auth.guard.js +62 -33
  45. package/dist/infra/throttler/named-throttlers.d.ts +3 -0
  46. package/dist/infra/throttler/named-throttlers.js +16 -0
  47. package/dist/infra/throttler/throttler.guard.d.ts +2 -1
  48. package/dist/infra/throttler/throttler.guard.js +2 -1
  49. package/dist/kernel.module.js +3 -0
  50. package/dist/local-devices/local-device-provider.d.ts +37 -1
  51. package/dist/local-devices/local-device-provider.js +33 -0
  52. package/dist/local-devices/machines.d.ts +2 -1
  53. package/dist/local-devices/machines.js +4 -1
  54. package/dist/local-devices/policy-summary.js +1 -0
  55. package/dist/local-devices/relay.d.ts +2 -0
  56. package/dist/local-devices/relay.js +3 -1
  57. package/dist/local-devices/targets.d.ts +6 -1
  58. package/dist/local-devices/targets.js +14 -0
  59. package/dist/overrides.d.ts +7 -0
  60. package/dist/overrides.js +4 -0
  61. package/dist/platform/ops/agent-skills.ops.js +2 -1
  62. package/dist/platform/ops/devices.ops.d.ts +3 -1
  63. package/dist/platform/ops/devices.ops.js +136 -3
  64. package/dist/runtime/context/build.d.ts +3 -0
  65. package/dist/runtime/context/build.js +14 -0
  66. package/dist/runtime/context/compaction.js +2 -0
  67. package/dist/runtime/context/project-root.d.ts +43 -0
  68. package/dist/runtime/context/project-root.js +85 -0
  69. package/dist/runtime/model-call.js +25 -1
  70. package/dist/runtime/project/knowledge.d.ts +129 -0
  71. package/dist/runtime/project/knowledge.js +248 -0
  72. package/dist/runtime/project/knowledge.service.d.ts +85 -0
  73. package/dist/runtime/project/knowledge.service.js +288 -0
  74. package/dist/runtime/run-worker.d.ts +5 -0
  75. package/dist/runtime/run-worker.js +27 -6
  76. package/dist/runtime/runtime.module.js +7 -0
  77. package/dist/sandbox/review/review.service.d.ts +14 -2
  78. package/dist/sandbox/review/review.service.js +2 -0
  79. package/dist/sandbox/review/rules.d.ts +6 -4
  80. package/dist/sandbox/review/rules.js +185 -62
  81. package/dist/sandbox/review/types.d.ts +14 -0
  82. package/dist/sandbox/sandbox.service.d.ts +16 -1
  83. package/dist/sandbox/sandbox.service.js +75 -3
  84. package/dist/skills/catalog.d.ts +6 -1
  85. package/dist/skills/catalog.js +18 -4
  86. package/dist/skills/invoke.d.ts +64 -2
  87. package/dist/skills/invoke.js +214 -6
  88. package/dist/skills/skills.module.js +5 -0
  89. package/dist/tools/approvals.service.d.ts +6 -0
  90. package/dist/tools/builtins/sandbox/bash.js +19 -4
  91. package/dist/tools/builtins/sandbox/common.d.ts +36 -6
  92. package/dist/tools/builtins/sandbox/common.js +69 -8
  93. package/dist/tools/builtins/sandbox/edit.js +2 -2
  94. package/dist/tools/builtins/sandbox/glob.js +3 -2
  95. package/dist/tools/builtins/sandbox/grep.js +2 -1
  96. package/dist/tools/builtins/sandbox/read.js +3 -3
  97. package/dist/tools/builtins/sandbox/write.js +2 -2
  98. package/dist/tools/builtins/skill-load.d.ts +47 -2
  99. package/dist/tools/builtins/skill-load.js +160 -2
  100. package/dist/tools/pipeline.d.ts +1 -1
  101. package/dist/tools/pipeline.js +53 -8
  102. package/dist/tools/registry.d.ts +6 -0
  103. package/package.json +3 -3
  104. package/src/migrations/0133_project_root.sql +30 -0
@@ -188,7 +188,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
188
188
  /** The host versions (an entry's `minKernel` is judged against them). */
189
189
  export declare const HOST_VERSIONS: {
190
190
  readonly kernel: string;
191
- readonly sdk: "0.1.0-rc.22";
191
+ readonly sdk: "0.1.0-rc.24";
192
192
  };
193
193
  /** Whether this deployment satisfies the entry's `minKernel`. */
194
194
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -24,31 +24,6 @@ export declare const DEDUPE_PENDING_TTL_SECONDS = 60;
24
24
  export declare const messageDedupeKey: (connectionId: string, messageId: string) => string;
25
25
  /** 带平台事件 id 的卡片点击的去重键(Ruling A26,Redis 键,可以含 `:`)。 */
26
26
  export declare const actionDedupeKey: (connectionId: string, eventId: string) => string;
27
- /**
28
- * 渠道入站(Ruling A21:持久化处理)。
29
- * - `onEvent`(插件 `connect` 的回调,必须快):消息按 `capk:channel-msg:<连接>:<消息>` `SET NX` 24 小时去重,
30
- * 再排一个入站任务(`inbound-<连接>-<消息 id 哈希>`)后返回;入队失败删掉去重键并抛错(插件不确认,平台重投)。
31
- * 带 `eventId` 的卡片操作同样按 `capk:channel-act:<连接>:<eventId>` 去重(任务 id 由 eventId 哈希,Ruling A26),
32
- * 不带的直接入队(任务 id 随机);`directory_changed` 只是投递一个通讯录同步任务,就地完成。
33
- * 返回即「内核已持久接收」:插件此后才向平台确认。
34
- * - `handle`(worker 上执行入站任务):失败抛错由 BullMQ 指数退避重试(共 5 次;插件在本副本未加载时推迟、
35
- * 回复报 auth / target_gone 时不重试);写用户消息带 `clientMessageId = "<连接>:<消息>"`,回复带由
36
- * `<连接>-<消息 id>-reply` 哈希的幂等键,重试不会重复写 / 重复回复。步骤:
37
- * 1. 连接停用、所属组织已删除或插件在该组织停用 → 什么都不做;群聊未 @ 机器人 → 忽略;
38
- * 2. 发言人按 `<插件>:<租户>` + externalId 纯查找账号(不建账号、不合并),且须是连接所属组织的活跃成员;
39
- * 否则按连接的未绑定策略:`bind` → 私聊回绑定卡片(群里只提示去私聊,绑定链接不能发在群里)、
40
- * 已绑定但非成员回提示;`anonymous` → 仅当绑定的 agent 全组织可见、且发言人与连接同一租户时用该组织的
41
- * 匿名访客(外部租户的人只能绑定),否则回提示。识别不出发言人时绝不借用连接创建者或任何人的身份;
42
- * 3. 私聊 `/new` → 归档当前对话行并回「已开始新对话」;
43
- * 4. 按话题找或建会话,写用户消息,记下投递目标并投递出站任务(Task 11)。A message whose text
44
- * (bot mention stripped) is `/name args` is posted as a skill invocation (phase D spec §9): the
45
- * same kernel path as the web, so the skill is resolved among the connection's agent's skills
46
- * for the bound person; a refusal (`skill.not_invocable`: unknown, not user-invocable, gone
47
- * since; `validation_failed`: over the limits) posts the text as typed, so nothing is lost.
48
- * `directory_changed` → 投递通讯录同步(Task 12);`card_action` 见 actions.ts。
49
- * 边界(已接受):同一 chat 的连续消息由不同任务并发处理,极少数情况下写入顺序可能与平台顺序不同;
50
- * 处理在写入用户消息之后失败而重试时,固定话术 / 卡片回复可能再发一次。
51
- */
52
27
  export declare class ChannelInbound {
53
28
  private readonly kdb;
54
29
  private readonly redis;
@@ -60,11 +60,31 @@ export const actionDedupeKey = (connectionId, eventId) => `capk:channel-act:${co
60
60
  * (bot mention stripped) is `/name args` is posted as a skill invocation (phase D spec §9): the
61
61
  * same kernel path as the web, so the skill is resolved among the connection's agent's skills
62
62
  * for the bound person; a refusal (`skill.not_invocable`: unknown, not user-invocable, gone
63
- * since; `validation_failed`: over the limits) posts the text as typed, so nothing is lost.
63
+ * since; `validation_failed`: over the limits) posts the text as typed, so nothing is lost; a
64
+ * project skill the project cannot serve (`skill.project_unavailable`) is refused with its
65
+ * reason and nothing is posted.
64
66
  * `directory_changed` → 投递通讯录同步(Task 12);`card_action` 见 actions.ts。
65
67
  * 边界(已接受):同一 chat 的连续消息由不同任务并发处理,极少数情况下写入顺序可能与平台顺序不同;
66
68
  * 处理在写入用户消息之后失败而重试时,固定话术 / 卡片回复可能再发一次。
67
69
  */
70
+ /** The note for a `skill.project_unavailable` refusal, by its reason. */
71
+ function projectSkillPhrase(err) {
72
+ const reason = err.details?.[0]?.reason;
73
+ switch (reason) {
74
+ case "gone":
75
+ return "projectSkillGone";
76
+ case "outside_mode":
77
+ return "projectSkillOutsideMode";
78
+ case "unparsable":
79
+ return "projectSkillUnparsable";
80
+ case "unsupported":
81
+ return "projectSkillUnsupported";
82
+ case "removed":
83
+ return "projectSkillRemoved";
84
+ default:
85
+ return "projectSkillUnreadable";
86
+ }
87
+ }
68
88
  let ChannelInbound = class ChannelInbound {
69
89
  kdb;
70
90
  redis;
@@ -270,6 +290,11 @@ let ChannelInbound = class ChannelInbound {
270
290
  }
271
291
  }
272
292
  catch (err) {
293
+ // a project skill the project cannot serve now: say why, post nothing (project root §4.6)
294
+ if (err instanceof ApiError && err.code === "skill.project_unavailable") {
295
+ await reply(projectSkillPhrase(err));
296
+ return;
297
+ }
273
298
  // agent 已对此人不可用(改了可见范围 / 已删除):会话按不存在处理
274
299
  if (err instanceof ApiError && err.code === "conversation.not_found") {
275
300
  await reply("agentUnavailable");
@@ -175,6 +175,34 @@ export declare const CHANNEL_PHRASES: {
175
175
  readonly zh: "技能没有运行:参数或技能内容过长。你的消息已按普通文本发送。";
176
176
  readonly en: "The skill was not run: its arguments or instructions are too long. Your message was sent as plain text.";
177
177
  };
178
+ /**
179
+ * Project root spec §4.6: `/project:<name>` named a skill of the conversation's project, but the
180
+ * kernel refused it (`skill.project_unavailable`, one phrase per reason); nothing was posted.
181
+ */
182
+ readonly projectSkillGone: {
183
+ readonly zh: "项目技能没有运行:项目或它的 SKILL.md 已不在设备上。你的消息没有发送。";
184
+ readonly en: "The project skill was not run: the project is no longer on the device. Your message was not sent.";
185
+ };
186
+ readonly projectSkillOutsideMode: {
187
+ readonly zh: "项目技能没有运行:设备当前的运行模式读不到它。你的消息没有发送。";
188
+ readonly en: "The project skill was not run: the device's current mode cannot read it. Your message was not sent.";
189
+ };
190
+ readonly projectSkillUnreadable: {
191
+ readonly zh: "项目技能没有运行:读取设备上的 SKILL.md 失败,请稍后重试。你的消息没有发送。";
192
+ readonly en: "The project skill was not run: reading its SKILL.md on the device failed; try again later. Your message was not sent.";
193
+ };
194
+ readonly projectSkillUnparsable: {
195
+ readonly zh: "项目技能没有运行:它的 SKILL.md 格式不正确,请在项目里修正。你的消息没有发送。";
196
+ readonly en: "The project skill was not run: its SKILL.md is not valid; fix it in the project. Your message was not sent.";
197
+ };
198
+ readonly projectSkillUnsupported: {
199
+ readonly zh: "项目技能没有运行:这台设备不支持项目。你的消息没有发送。";
200
+ readonly en: "The project skill was not run: this device does not support projects. Your message was not sent.";
201
+ };
202
+ readonly projectSkillRemoved: {
203
+ readonly zh: "项目技能没有运行:这个项目已从设备的项目中移除。你的消息没有发送。";
204
+ readonly en: "The project skill was not run: the project was removed from the device's projects. Your message was not sent.";
205
+ };
178
206
  /** 运行被中止(收尾挂着的草稿时附在已有文本之后)。 */
179
207
  readonly runStopped: {
180
208
  readonly zh: "已停止。";
@@ -137,6 +137,34 @@ export const CHANNEL_PHRASES = {
137
137
  zh: "技能没有运行:参数或技能内容过长。你的消息已按普通文本发送。",
138
138
  en: "The skill was not run: its arguments or instructions are too long. Your message was sent as plain text.",
139
139
  },
140
+ /**
141
+ * Project root spec §4.6: `/project:<name>` named a skill of the conversation's project, but the
142
+ * kernel refused it (`skill.project_unavailable`, one phrase per reason); nothing was posted.
143
+ */
144
+ projectSkillGone: {
145
+ zh: "项目技能没有运行:项目或它的 SKILL.md 已不在设备上。你的消息没有发送。",
146
+ en: "The project skill was not run: the project is no longer on the device. Your message was not sent.",
147
+ },
148
+ projectSkillOutsideMode: {
149
+ zh: "项目技能没有运行:设备当前的运行模式读不到它。你的消息没有发送。",
150
+ en: "The project skill was not run: the device's current mode cannot read it. Your message was not sent.",
151
+ },
152
+ projectSkillUnreadable: {
153
+ zh: "项目技能没有运行:读取设备上的 SKILL.md 失败,请稍后重试。你的消息没有发送。",
154
+ en: "The project skill was not run: reading its SKILL.md on the device failed; try again later. Your message was not sent.",
155
+ },
156
+ projectSkillUnparsable: {
157
+ zh: "项目技能没有运行:它的 SKILL.md 格式不正确,请在项目里修正。你的消息没有发送。",
158
+ en: "The project skill was not run: its SKILL.md is not valid; fix it in the project. Your message was not sent.",
159
+ },
160
+ projectSkillUnsupported: {
161
+ zh: "项目技能没有运行:这台设备不支持项目。你的消息没有发送。",
162
+ en: "The project skill was not run: this device does not support projects. Your message was not sent.",
163
+ },
164
+ projectSkillRemoved: {
165
+ zh: "项目技能没有运行:这个项目已从设备的项目中移除。你的消息没有发送。",
166
+ en: "The project skill was not run: the project was removed from the device's projects. Your message was not sent.",
167
+ },
140
168
  /** 运行被中止(收尾挂着的草稿时附在已有文本之后)。 */
141
169
  runStopped: { zh: "已停止。", en: "Stopped." },
142
170
  /** 运行失败。 */
@@ -79,11 +79,14 @@ declare const MessageBody: z.ZodObject<{
79
79
  * first send; `clientMessageId` is required and makes a retry return the same conversation).
80
80
  * Without it the conversation is created empty (API clients; the web never does).
81
81
  * `deviceId` binds it to one of the caller's devices; without it the caller's default
82
- * device (environments spec §4.1 item 1).
82
+ * device (environments spec §4.1 item 1). `project` binds it to one of that device's projects
83
+ * (project root design §4.3; the device's owner only, refused when the device's current mode
84
+ * cannot read it); without it the conversation runs in free mode.
83
85
  */
84
86
  declare const CreateBody: z.ZodObject<{
85
87
  agentId: z.ZodString;
86
88
  deviceId: z.ZodOptional<z.ZodString>;
89
+ project: z.ZodOptional<z.ZodString & z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>>;
87
90
  message: z.ZodOptional<z.ZodObject<{
88
91
  text: z.ZodString;
89
92
  attachments: z.ZodOptional<z.ZodArray<z.ZodObject<{
@@ -7,6 +7,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  var __param = (this && this.__param) || function (paramIndex, decorator) {
8
8
  return function (target, key) { decorator(target, key, paramIndex); }
9
9
  };
10
+ import { isDeviceProjectName } from "@capybara-hq/plugin-sdk";
10
11
  import { Controller, Delete, Get, Header, HttpCode, Inject, Param, Patch, Post, Res, } from "@nestjs/common";
11
12
  import { z } from "zod";
12
13
  import { ModelRef } from "../agents/definition.js";
@@ -107,12 +108,20 @@ const MessageBody = MessageFields.strict().refine(...textRule);
107
108
  * first send; `clientMessageId` is required and makes a retry return the same conversation).
108
109
  * Without it the conversation is created empty (API clients; the web never does).
109
110
  * `deviceId` binds it to one of the caller's devices; without it the caller's default
110
- * device (environments spec §4.1 item 1).
111
+ * device (environments spec §4.1 item 1). `project` binds it to one of that device's projects
112
+ * (project root design §4.3; the device's owner only, refused when the device's current mode
113
+ * cannot read it); without it the conversation runs in free mode.
111
114
  */
112
115
  const CreateBody = z
113
116
  .object({
114
117
  agentId: z.string().min(1).max(100),
115
118
  deviceId: z.string().min(1).max(100).optional(),
119
+ project: z
120
+ .string()
121
+ .refine(isDeviceProjectName, {
122
+ message: "A project name is 1-64 characters, not . or .., without / or control characters, and without leading or trailing spaces",
123
+ })
124
+ .optional(),
116
125
  message: MessageFields.omit({ retryOf: true })
117
126
  .extend({ clientMessageId: z.string().min(1).max(200) })
118
127
  .strict()
@@ -189,7 +198,10 @@ let ConversationsController = class ConversationsController {
189
198
  */
190
199
  async create(principal, org, body, reply) {
191
200
  const p = requireUser(principal);
192
- const pick = body.deviceId === undefined ? {} : { deviceId: body.deviceId };
201
+ const pick = {
202
+ ...(body.deviceId !== undefined && { deviceId: body.deviceId }),
203
+ ...(body.project !== undefined && { project: body.project }),
204
+ };
193
205
  if (body.message === undefined) {
194
206
  return {
195
207
  conversation: await this.conversations.create(org.orgId, p.account.id, body.agentId, pick, {
@@ -5,6 +5,7 @@ import type { AgentAvatar } from "../agents/profile.js";
5
5
  import { BackgroundTaskStopper } from "../background/stop.js";
6
6
  import type { TitleSource } from "../db/kernel-schema.js";
7
7
  import { ConversationDevices, type NewConversationDevice } from "../devices/conversation-devices.js";
8
+ import { DeviceProjectsService } from "../devices/device-projects.service.js";
8
9
  import { KernelDb } from "../infra/database/kernel-db.js";
9
10
  import { TransactionHost } from "../infra/database/transaction-host.js";
10
11
  import { KernelEvents } from "../infra/events/kernel-events.js";
@@ -50,12 +51,35 @@ export interface ConversationView {
50
51
  deviceId: string | null;
51
52
  /** The scheduled task that created it (a `new`-mode task's run); null otherwise (spec §4). */
52
53
  scheduledTaskId: string | null;
54
+ /**
55
+ * The device project it is bound to (project root spec §4.3: chosen at creation, never
56
+ * changed), as resolved then: its name and absolute path on the device; null in free mode (a
57
+ * sub-agent's is null too: it works in its root conversation's).
58
+ */
59
+ project: {
60
+ name: string;
61
+ path: string;
62
+ } | null;
63
+ /**
64
+ * The latest `project_root` snapshot of its log (project root spec §4.7), however far back:
65
+ * `loaded` with whether the project's `AGENTS.md` was found, or the reason the project is
66
+ * `unavailable`; null when no run start has recorded one (a free conversation, a bound one before
67
+ * its first run). Single-conversation responses compute it; the list queries carry null.
68
+ */
69
+ projectState: ProjectState | null;
53
70
  /**
54
71
  * What the latest run is doing: `running` (queued or running), `waiting` (an approval or a
55
72
  * question), else null. Only the list queries compute it; other responses carry null.
56
73
  */
57
74
  activity: "running" | "waiting" | null;
58
75
  }
76
+ /** The state a conversation's latest `project_root` event records ({@link ConversationView}). */
77
+ export type ProjectState = {
78
+ loaded: true;
79
+ agentsMd: boolean;
80
+ } | {
81
+ unavailable: "gone" | "outside_mode" | "unreadable" | "unsupported" | "removed";
82
+ };
59
83
  /** Escapes `\`, `%` and `_` so user text is matched literally by `LIKE … ESCAPE '\'`. */
60
84
  export declare function escapeLike(s: string): string;
61
85
  /** One agent's group in the sidebar list: the caller's newest conversations with that agent. */
@@ -267,6 +291,8 @@ export declare class ConversationsService {
267
291
  private readonly background;
268
292
  /** The device a new conversation is bound to (environments spec §4.1 item 1). */
269
293
  private readonly devices;
294
+ /** The project of that device a new conversation is bound to (project root design §4.3). */
295
+ private readonly projects;
270
296
  /** A starter's message skips the run's pending questions (reply-while-question spec §8.1). */
271
297
  private readonly questions;
272
298
  /** ... and its pending network asks (network ask-to-allow spec §6.7). */
@@ -288,6 +314,8 @@ export declare class ConversationsService {
288
314
  background: Pick<BackgroundTaskStopper, "stopForDeletedConversation">,
289
315
  /** The device a new conversation is bound to (environments spec §4.1 item 1). */
290
316
  devices: Pick<ConversationDevices, "forNew">,
317
+ /** The project of that device a new conversation is bound to (project root design §4.3). */
318
+ projects: Pick<DeviceProjectsService, "resolveForBinding">,
291
319
  /** A starter's message skips the run's pending questions (reply-while-question spec §8.1). */
292
320
  questions: Pick<QuestionsService, "skipPendingIn">,
293
321
  /** ... and its pending network asks (network ask-to-allow spec §6.7). */
@@ -296,8 +324,9 @@ export declare class ConversationsService {
296
324
  * Creates an empty conversation bound to its device (`pick`, see
297
325
  * {@link ConversationDevices.forNew}); an agent the account cannot use →
298
326
  * `agent.not_found`, a device it may not use → `device.not_found` /
299
- * `device.unavailable`, and nothing is created. `opts.source` records where the conversation
300
- * comes from.
327
+ * `device.unavailable`, and nothing is created. `pick.project` binds it to one of that device's
328
+ * projects ({@link bindingFor}), refused as that says. `opts.source` records where the
329
+ * conversation comes from.
301
330
  */
302
331
  create(orgId: string, accountId: string, agentId: string, pick: NewConversationDevice | undefined, opts: NewConversationOptions): Promise<ConversationView>;
303
332
  /**
@@ -309,7 +338,9 @@ export declare class ConversationsService {
309
338
  * `events` are every event the create wrote, in seq order from seq 1 (a `model_switched` before
310
339
  * the message when the send switched), so a client can seed the new conversation's log whole.
311
340
  * `internal`: the conversation's source and, for kernel callers only, a scheduled task's marker,
312
- * which also sets `conversations.scheduled_task_id`, and its zone override.
341
+ * which also sets `conversations.scheduled_task_id`, and its zone override. `pick.project` binds
342
+ * the conversation to one of its device's projects inside the write ({@link bindingFor}); a
343
+ * retry answers with the conversation the first send created, its binding unchanged.
313
344
  */
314
345
  createWithMessage(orgId: string, accountId: string, agentId: string, input: UserMessageInput & {
315
346
  clientMessageId: string;
@@ -321,6 +352,15 @@ export declare class ConversationsService {
321
352
  }>;
322
353
  /** The conversation row and its first message (undefined: a concurrent retry committed first). */
323
354
  private createIn;
355
+ /**
356
+ * The project a new conversation binds to (project root design §4.3): `name` resolved against
357
+ * the chosen device's projects by `DeviceProjectsService.resolveForBinding`, which reads only and
358
+ * checks the owner and the device's current mode (refused with `device.not_found`,
359
+ * `device.projects_unsupported`, `device.project_not_found` or `device.project_outside_mode`).
360
+ * Called inside the transaction that writes the conversation. A conversation without a device
361
+ * (no cloud provider, an anonymous IM sender) cannot have one. Undefined name: free mode.
362
+ */
363
+ private bindingFor;
324
364
  /**
325
365
  * The conversation (and its first event) an earlier first send with this id created. The id used
326
366
  * for another agent's conversation → `conflict` (the caller only checked access to `agentId`, so
@@ -14,6 +14,7 @@ import { AgentLookup, visibleTo } from "../agents/agent-lookup.js";
14
14
  import { BackgroundTaskStopper } from "../background/stop.js";
15
15
  import { unbindConversation } from "../channels/threads.js";
16
16
  import { ConversationDevices, } from "../devices/conversation-devices.js";
17
+ import { DeviceProjectsService } from "../devices/device-projects.service.js";
17
18
  import { ApiError } from "../errors.js";
18
19
  import { KernelDb } from "../infra/database/kernel-db.js";
19
20
  import { TransactionHost } from "../infra/database/transaction-host.js";
@@ -34,6 +35,24 @@ import { userMessageIdemKey } from "./idem-keys.js";
34
35
  import { readMessageContext, } from "./message-context.js";
35
36
  import { NO_SELECTION, planSelection, readSelection } from "./selection.js";
36
37
  import { conversationTree } from "./tree.js";
38
+ /**
39
+ * SQL for the {@link ProjectState} of the conversation row aliased/named `ref` (a correlated
40
+ * subquery on the latest `project_root` event, served by `conversation_events_project_root_idx`).
41
+ */
42
+ function projectStateSql(ref) {
43
+ const id = sql.ref(`${ref}.id`);
44
+ return sql `(
45
+ SELECT CASE
46
+ WHEN pe.payload ? 'unavailable'
47
+ THEN jsonb_build_object('unavailable', pe.payload->'unavailable'->>'reason')
48
+ ELSE jsonb_build_object('loaded', true, 'agentsMd', pe.payload ? 'agentsMd') END
49
+ FROM capybara.conversation_events pe
50
+ WHERE pe.conversation_id = ${id} AND pe.type = 'project_root'
51
+ ORDER BY pe.seq DESC LIMIT 1
52
+ )`;
53
+ }
54
+ /** The columns of a single-conversation response: {@link COLUMNS} and its project state. */
55
+ const viewColumns = () => [...COLUMNS, projectStateSql("conversations").as("project_state")];
37
56
  /** Escapes `\`, `%` and `_` so user text is matched literally by `LIKE … ESCAPE '\'`. */
38
57
  export function escapeLike(s) {
39
58
  return s.replace(/[\\%_]/g, (ch) => `\\${ch}`);
@@ -74,6 +93,8 @@ const COLUMNS = [
74
93
  "archived_at",
75
94
  "device_id",
76
95
  "scheduled_task_id",
96
+ "project_name",
97
+ "project_path",
77
98
  ];
78
99
  function toView(r) {
79
100
  return {
@@ -92,6 +113,10 @@ function toView(r) {
92
113
  archivedAt: r.archived_at,
93
114
  deviceId: r.device_id,
94
115
  scheduledTaskId: r.scheduled_task_id,
116
+ project: r.project_name !== null && r.project_path !== null
117
+ ? { name: r.project_name, path: r.project_path }
118
+ : null,
119
+ projectState: r.project_state ?? null,
95
120
  activity: r.activity ?? null,
96
121
  };
97
122
  }
@@ -134,6 +159,7 @@ let ConversationsService = class ConversationsService {
134
159
  invoker;
135
160
  background;
136
161
  devices;
162
+ projects;
137
163
  questions;
138
164
  approvals;
139
165
  events;
@@ -153,6 +179,8 @@ let ConversationsService = class ConversationsService {
153
179
  background,
154
180
  /** The device a new conversation is bound to (environments spec §4.1 item 1). */
155
181
  devices,
182
+ /** The project of that device a new conversation is bound to (project root design §4.3). */
183
+ projects,
156
184
  /** A starter's message skips the run's pending questions (reply-while-question spec §8.1). */
157
185
  questions,
158
186
  /** ... and its pending network asks (network ask-to-allow spec §6.7). */
@@ -168,6 +196,7 @@ let ConversationsService = class ConversationsService {
168
196
  this.invoker = invoker;
169
197
  this.background = background;
170
198
  this.devices = devices;
199
+ this.projects = projects;
171
200
  this.questions = questions;
172
201
  this.approvals = approvals;
173
202
  this.events = events;
@@ -177,12 +206,14 @@ let ConversationsService = class ConversationsService {
177
206
  * Creates an empty conversation bound to its device (`pick`, see
178
207
  * {@link ConversationDevices.forNew}); an agent the account cannot use →
179
208
  * `agent.not_found`, a device it may not use → `device.not_found` /
180
- * `device.unavailable`, and nothing is created. `opts.source` records where the conversation
181
- * comes from.
209
+ * `device.unavailable`, and nothing is created. `pick.project` binds it to one of that device's
210
+ * projects ({@link bindingFor}), refused as that says. `opts.source` records where the
211
+ * conversation comes from.
182
212
  */
183
213
  async create(orgId, accountId, agentId, pick = {}, opts) {
184
214
  await this.agents.get(orgId, agentId, accountId);
185
215
  const deviceId = await this.devices.forNew(orgId, accountId, pick);
216
+ const project = await this.bindingFor(orgId, accountId, deviceId, pick.project);
186
217
  const row = await this.db
187
218
  .insertInto("conversations")
188
219
  .values({
@@ -191,6 +222,8 @@ let ConversationsService = class ConversationsService {
191
222
  agent_id: agentId,
192
223
  account_id: accountId,
193
224
  device_id: deviceId,
225
+ project_name: project?.name ?? null,
226
+ project_path: project?.path ?? null,
194
227
  source: opts.source,
195
228
  })
196
229
  .returning(COLUMNS)
@@ -206,7 +239,9 @@ let ConversationsService = class ConversationsService {
206
239
  * `events` are every event the create wrote, in seq order from seq 1 (a `model_switched` before
207
240
  * the message when the send switched), so a client can seed the new conversation's log whole.
208
241
  * `internal`: the conversation's source and, for kernel callers only, a scheduled task's marker,
209
- * which also sets `conversations.scheduled_task_id`, and its zone override.
242
+ * which also sets `conversations.scheduled_task_id`, and its zone override. `pick.project` binds
243
+ * the conversation to one of its device's projects inside the write ({@link bindingFor}); a
244
+ * retry answers with the conversation the first send created, its binding unchanged.
210
245
  */
211
246
  async createWithMessage(orgId, accountId, agentId, input, pick = {}, internal) {
212
247
  const agent = await this.agents.get(orgId, agentId, accountId);
@@ -216,9 +251,22 @@ let ConversationsService = class ConversationsService {
216
251
  const deviceId = await this.devices.forNew(orgId, accountId, pick);
217
252
  const next = await this.planSwitch(orgId, agent.definition, NO_SELECTION, input);
218
253
  const extra = await this.resolveExtra(orgId, accountId, input);
219
- const invoked = await this.prepareSkill(orgId, agentId, undefined, agent.definition, input);
254
+ const invoked = await this.prepareSkill(orgId, accountId, agentId, undefined, agent.definition, input);
220
255
  const id = randomUUID();
221
- const all = await this.createIn({ id, orgId, accountId, agentId, deviceId }, input, next, extra, invoked, internal);
256
+ let all;
257
+ try {
258
+ all = await this.createIn({ id, orgId, accountId, agentId, deviceId, project: pick.project }, input, next, extra, invoked, internal);
259
+ }
260
+ catch (e) {
261
+ // a concurrent first send with this id created the conversation while this one resolved its
262
+ // binding: a refusal here (the project just went away) answers with what the first created
263
+ if (!(e instanceof ApiError))
264
+ throw e;
265
+ const raced = await this.findCreated(orgId, accountId, agentId, input.clientMessageId);
266
+ if (!raced)
267
+ throw e;
268
+ return raced;
269
+ }
222
270
  const written = all?.at(-1);
223
271
  if (!all || !written) {
224
272
  const raced = await this.findCreated(orgId, accountId, agentId, input.clientMessageId);
@@ -234,6 +282,7 @@ let ConversationsService = class ConversationsService {
234
282
  // its own transaction: the caller notifies and publishes after the commit
235
283
  async createIn(conv, input, next, extra, invoked, internal) {
236
284
  const { id, orgId, accountId } = conv;
285
+ const project = await this.bindingFor(orgId, accountId, conv.deviceId, conv.project);
237
286
  const row = await this.db
238
287
  .insertInto("conversations")
239
288
  .values({
@@ -242,6 +291,8 @@ let ConversationsService = class ConversationsService {
242
291
  agent_id: conv.agentId,
243
292
  account_id: accountId,
244
293
  device_id: conv.deviceId,
294
+ project_name: project?.name ?? null,
295
+ project_path: project?.path ?? null,
245
296
  create_request_id: input.clientMessageId,
246
297
  scheduled_task_id: internal.schedule?.taskId ?? null,
247
298
  source: internal.source,
@@ -259,6 +310,22 @@ let ConversationsService = class ConversationsService {
259
310
  // a new conversation has no run yet, so nothing to skip
260
311
  return (await this.writeMessage(orgId, id, accountId, input, next, extra, blocks, invoked, internal)).events;
261
312
  }
313
+ /**
314
+ * The project a new conversation binds to (project root design §4.3): `name` resolved against
315
+ * the chosen device's projects by `DeviceProjectsService.resolveForBinding`, which reads only and
316
+ * checks the owner and the device's current mode (refused with `device.not_found`,
317
+ * `device.projects_unsupported`, `device.project_not_found` or `device.project_outside_mode`).
318
+ * Called inside the transaction that writes the conversation. A conversation without a device
319
+ * (no cloud provider, an anonymous IM sender) cannot have one. Undefined name: free mode.
320
+ */
321
+ async bindingFor(orgId, accountId, deviceId, name) {
322
+ if (name === undefined)
323
+ return undefined;
324
+ if (deviceId === null) {
325
+ throw new ApiError("device.projects_unsupported", "This conversation has no device, so it cannot be bound to a project; choose one of your devices, or start it without a project");
326
+ }
327
+ return this.projects.resolveForBinding(orgId, deviceId, accountId, name);
328
+ }
262
329
  /**
263
330
  * The conversation (and its first event) an earlier first send with this id created. The id used
264
331
  * for another agent's conversation → `conflict` (the caller only checked access to `agentId`, so
@@ -267,7 +334,7 @@ let ConversationsService = class ConversationsService {
267
334
  async findCreated(orgId, accountId, agentId, clientMessageId) {
268
335
  const row = await this.db
269
336
  .selectFrom("conversations")
270
- .select(COLUMNS)
337
+ .select(viewColumns())
271
338
  .where("org_id", "=", orgId)
272
339
  .where("account_id", "=", accountId)
273
340
  .where("create_request_id", "=", clientMessageId)
@@ -296,7 +363,7 @@ let ConversationsService = class ConversationsService {
296
363
  async rowView(id) {
297
364
  return toView(await this.db
298
365
  .selectFrom("conversations")
299
- .select(COLUMNS)
366
+ .select(viewColumns())
300
367
  .where("id", "=", id)
301
368
  .executeTakeFirstOrThrow());
302
369
  }
@@ -310,7 +377,7 @@ let ConversationsService = class ConversationsService {
310
377
  .updateTable("conversations")
311
378
  .set({ title, title_source: "manual" })
312
379
  .where("id", "=", conversationId)
313
- .returning(COLUMNS)
380
+ .returning(viewColumns())
314
381
  .executeTakeFirstOrThrow();
315
382
  await this.eventLog.publishChanged(conversationId, "title");
316
383
  return toView(row);
@@ -325,7 +392,7 @@ let ConversationsService = class ConversationsService {
325
392
  .updateTable("conversations")
326
393
  .set({ archived_at: archived ? sql `now()` : null })
327
394
  .where("id", "=", conversationId)
328
- .returning(COLUMNS)
395
+ .returning(viewColumns())
329
396
  .executeTakeFirstOrThrow();
330
397
  await this.eventLog.publishChanged(conversationId, "archived");
331
398
  return toView(row);
@@ -394,7 +461,7 @@ let ConversationsService = class ConversationsService {
394
461
  async readable(orgId, conversationId, viewerAccountId) {
395
462
  const row = await this.db
396
463
  .selectFrom("conversations")
397
- .select([...COLUMNS, "kind"])
464
+ .select([...viewColumns(), "kind"])
398
465
  .where("id", "=", conversationId)
399
466
  .where("org_id", "=", orgId)
400
467
  .where("account_id", "=", viewerAccountId)
@@ -502,14 +569,16 @@ let ConversationsService = class ConversationsService {
502
569
  SELECT page.agent_id, page.latest_at, v.definition ->> 'name' AS agent_name,
503
570
  a.profile_avatar, a.profile_updated_at, cs.id, cs.org_id, cs.account_id, cs.title, cs.title_source, cs.selection, cs.last_seq,
504
571
  cs.created_at, cs.updated_at, cs.parent_conversation_id, cs.subagent_type,
505
- cs.archived_at, cs.device_id, cs.scheduled_task_id, cs.activity
572
+ cs.archived_at, cs.device_id, cs.scheduled_task_id, cs.project_name, cs.project_path,
573
+ cs.activity
506
574
  FROM page
507
575
  JOIN capybara.agents a ON a.id = page.agent_id
508
576
  JOIN capybara.agent_versions v ON v.agent_id = a.id AND v.version = a.current_version
509
577
  CROSS JOIN LATERAL (
510
578
  SELECT c.id, c.org_id, c.account_id, c.title, c.title_source, c.selection, c.last_seq,
511
579
  c.created_at, c.updated_at, c.parent_conversation_id, c.subagent_type,
512
- c.archived_at, c.device_id, c.scheduled_task_id, ${activitySql("c")} AS activity
580
+ c.archived_at, c.device_id, c.scheduled_task_id, c.project_name, c.project_path,
581
+ ${activitySql("c")} AS activity
513
582
  FROM capybara.conversations c
514
583
  WHERE c.org_id = ${orgId} AND c.account_id = ${accountId} AND c.kind = 'chat'
515
584
  AND c.deleted_at IS NULL AND ${archivedFilter} ${searchFilter} ${stateFilter}
@@ -733,7 +802,7 @@ let ConversationsService = class ConversationsService {
733
802
  const extra = await this.resolveExtra(orgId, accountId, input);
734
803
  const invoked = agent === undefined
735
804
  ? undefined
736
- : await this.prepareSkill(orgId, conv.agentId, conversationId, agent, input);
805
+ : await this.prepareSkill(orgId, accountId, conv.agentId, conversationId, agent, input);
737
806
  // one transaction: the sender, time zone and language are read with the message's write
738
807
  // (run context spec §3.2)
739
808
  const { event, skipped, toSeq } = await this.postIn(orgId, conversationId, accountId, input, next, extra, invoked);
@@ -910,12 +979,13 @@ let ConversationsService = class ConversationsService {
910
979
  * Renders the message's skill invocation (phase D), or undefined when it has none. Resolved
911
980
  * against the agent's current version and, for an existing conversation, its trial drafts.
912
981
  */
913
- async prepareSkill(orgId, agentId, conversationId, agent, input) {
982
+ async prepareSkill(orgId, accountId, agentId, conversationId, agent, input) {
914
983
  if (input.skill === undefined)
915
984
  return undefined;
916
985
  return this.invoker.prepare({
917
986
  orgId,
918
987
  agentId,
988
+ accountId,
919
989
  ...(conversationId !== undefined && { conversationId }),
920
990
  agent,
921
991
  name: input.skill.name,
@@ -931,7 +1001,7 @@ let ConversationsService = class ConversationsService {
931
1001
  if (input.skill === undefined)
932
1002
  return undefined;
933
1003
  const agent = await this.agents.get(orgId, conv.agentId, accountId);
934
- return this.prepareSkill(orgId, conv.agentId, conv.id, agent.definition, input);
1004
+ return this.prepareSkill(orgId, accountId, conv.agentId, conv.id, agent.definition, input);
935
1005
  }
936
1006
  /**
937
1007
  * Reads the `@` resources with the sender's credentials (nothing when there are none). Shared
@@ -1099,6 +1169,9 @@ let ConversationsService = class ConversationsService {
1099
1169
  return run.id;
1100
1170
  }
1101
1171
  };
1172
+ __decorate([
1173
+ Transactional()
1174
+ ], ConversationsService.prototype, "create", null);
1102
1175
  __decorate([
1103
1176
  Transactional({ propagation: "requires_new" })
1104
1177
  ], ConversationsService.prototype, "createIn", null);
@@ -1133,9 +1206,10 @@ ConversationsService = __decorate([
1133
1206
  __param(8, Inject(SkillInvoker)),
1134
1207
  __param(9, Inject(BackgroundTaskStopper)),
1135
1208
  __param(10, Inject(ConversationDevices)),
1136
- __param(11, Inject(QuestionsService)),
1137
- __param(12, Inject(ApprovalsService)),
1138
- __param(13, Inject(KernelEvents)),
1139
- __param(14, Inject(TransactionHost))
1209
+ __param(11, Inject(DeviceProjectsService)),
1210
+ __param(12, Inject(QuestionsService)),
1211
+ __param(13, Inject(ApprovalsService)),
1212
+ __param(14, Inject(KernelEvents)),
1213
+ __param(15, Inject(TransactionHost))
1140
1214
  ], ConversationsService);
1141
1215
  export { ConversationsService };
@@ -152,9 +152,9 @@ export declare class EventLog {
152
152
  findByIdem(conversationId: string, idemKey: string): Promise<ConversationEvent | undefined>;
153
153
  /**
154
154
  * The conversation's latest event of `type` (by seq); undefined without one. `skills_catalog`
155
- * (0025) and `device_paths` (0094) have partial indexes that answer it directly; other
156
- * types scan the conversation's events backwards on the (conversation_id, seq) key, the whole
157
- * conversation when it has none.
155
+ * (0025), `device_paths` (0094) and `project_root` (0133) have partial indexes that answer it
156
+ * directly; other types scan the conversation's events backwards on the (conversation_id, seq)
157
+ * key, the whole conversation when it has none.
158
158
  */
159
159
  latestOfType<T extends ConversationEventType>(conversationId: string, type: T): Promise<Extract<ConversationEvent, {
160
160
  type: T;
@@ -253,9 +253,9 @@ let EventLog = class EventLog {
253
253
  }
254
254
  /**
255
255
  * The conversation's latest event of `type` (by seq); undefined without one. `skills_catalog`
256
- * (0025) and `device_paths` (0094) have partial indexes that answer it directly; other
257
- * types scan the conversation's events backwards on the (conversation_id, seq) key, the whole
258
- * conversation when it has none.
256
+ * (0025), `device_paths` (0094) and `project_root` (0133) have partial indexes that answer it
257
+ * directly; other types scan the conversation's events backwards on the (conversation_id, seq)
258
+ * key, the whole conversation when it has none.
259
259
  */
260
260
  async latestOfType(conversationId, type) {
261
261
  const r = await this.db