@capybara-hq/kernel 0.1.0-rc.32 → 0.1.0-rc.34

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 (107) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/catalog/marketplaces.service.d.ts +1 -1
  3. package/dist/catalog/requests.service.d.ts +8 -6
  4. package/dist/catalog/requests.service.js +52 -29
  5. package/dist/channels/inbound.d.ts +0 -25
  6. package/dist/channels/inbound.js +26 -1
  7. package/dist/channels/phrases.d.ts +28 -0
  8. package/dist/channels/phrases.js +28 -0
  9. package/dist/config/schema.d.ts +4 -0
  10. package/dist/config/schema.js +7 -1
  11. package/dist/conversations/conversations.controller.d.ts +4 -1
  12. package/dist/conversations/conversations.controller.js +14 -2
  13. package/dist/conversations/conversations.service.d.ts +43 -3
  14. package/dist/conversations/conversations.service.js +93 -19
  15. package/dist/conversations/event-log.d.ts +3 -3
  16. package/dist/conversations/event-log.js +3 -3
  17. package/dist/conversations/events.d.ts +24 -0
  18. package/dist/conversations/events.js +69 -0
  19. package/dist/db/kernel-schema.d.ts +20 -0
  20. package/dist/devices/conversation-devices.d.ts +57 -3
  21. package/dist/devices/conversation-devices.js +63 -11
  22. package/dist/devices/device-projects.service.d.ts +162 -0
  23. package/dist/devices/device-projects.service.js +503 -0
  24. package/dist/devices/devices.controller.d.ts +15 -2
  25. package/dist/devices/devices.controller.js +60 -3
  26. package/dist/devices/devices.module.js +15 -2
  27. package/dist/devices/devices.schemas.js +9 -1
  28. package/dist/devices/devices.service.js +8 -4
  29. package/dist/devices/dto.d.ts +31 -0
  30. package/dist/devices/dto.js +38 -1
  31. package/dist/devices/working-root.d.ts +41 -0
  32. package/dist/devices/working-root.js +50 -0
  33. package/dist/errors.d.ts +39 -0
  34. package/dist/errors.js +39 -0
  35. package/dist/evals/run-replay.d.ts +9 -1
  36. package/dist/evals/run-replay.js +15 -1
  37. package/dist/local-devices/local-device-provider.d.ts +37 -1
  38. package/dist/local-devices/local-device-provider.js +33 -0
  39. package/dist/local-devices/machines.d.ts +2 -1
  40. package/dist/local-devices/machines.js +4 -1
  41. package/dist/local-devices/network-grants.d.ts +1 -1
  42. package/dist/local-devices/network-grants.js +2 -3
  43. package/dist/local-devices/policy-summary.js +1 -0
  44. package/dist/local-devices/relay.d.ts +2 -0
  45. package/dist/local-devices/relay.js +3 -1
  46. package/dist/local-devices/targets.d.ts +6 -1
  47. package/dist/local-devices/targets.js +14 -0
  48. package/dist/orgs/settings.controller.d.ts +3 -1
  49. package/dist/orgs/settings.controller.js +7 -3
  50. package/dist/orgs/settings.service.d.ts +78 -31
  51. package/dist/orgs/settings.service.js +109 -52
  52. package/dist/overrides.d.ts +4 -0
  53. package/dist/overrides.js +2 -0
  54. package/dist/platform/ops/agent-skills.ops.js +2 -1
  55. package/dist/platform/ops/devices.ops.d.ts +3 -1
  56. package/dist/platform/ops/devices.ops.js +136 -3
  57. package/dist/platform/ops/org-settings.ops.js +20 -10
  58. package/dist/runtime/context/build.d.ts +3 -0
  59. package/dist/runtime/context/build.js +14 -0
  60. package/dist/runtime/context/compaction.js +2 -0
  61. package/dist/runtime/context/project-root.d.ts +43 -0
  62. package/dist/runtime/context/project-root.js +85 -0
  63. package/dist/runtime/model-call.js +25 -1
  64. package/dist/runtime/project/knowledge.d.ts +129 -0
  65. package/dist/runtime/project/knowledge.js +248 -0
  66. package/dist/runtime/project/knowledge.service.d.ts +85 -0
  67. package/dist/runtime/project/knowledge.service.js +288 -0
  68. package/dist/runtime/run-worker.d.ts +5 -0
  69. package/dist/runtime/run-worker.js +27 -6
  70. package/dist/runtime/runtime.module.js +7 -0
  71. package/dist/sandbox/modes.d.ts +31 -19
  72. package/dist/sandbox/modes.js +43 -24
  73. package/dist/sandbox/review/review.service.d.ts +14 -2
  74. package/dist/sandbox/review/review.service.js +2 -0
  75. package/dist/sandbox/review/rules.d.ts +6 -4
  76. package/dist/sandbox/review/rules.js +185 -62
  77. package/dist/sandbox/review/types.d.ts +14 -0
  78. package/dist/sandbox/sandbox.service.d.ts +20 -2
  79. package/dist/sandbox/sandbox.service.js +86 -3
  80. package/dist/schedules/grant-rules.d.ts +2 -0
  81. package/dist/schedules/grant-rules.js +3 -1
  82. package/dist/schedules/schedule-math.js +21 -2
  83. package/dist/schedules/scheduled-tasks.service.js +3 -1
  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/network-asks.d.ts +7 -0
  101. package/dist/tools/network-asks.js +11 -1
  102. package/dist/tools/pipeline.d.ts +1 -1
  103. package/dist/tools/pipeline.js +60 -9
  104. package/dist/tools/registry.d.ts +6 -0
  105. package/package.json +2 -2
  106. package/src/migrations/0133_project_root.sql +30 -0
  107. package/src/migrations/0134_org_cloud_network_delta.sql +38 -0
@@ -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
@@ -707,6 +707,30 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
707
707
  }>>;
708
708
  local: z.ZodOptional<z.ZodBoolean>;
709
709
  }, z.core.$strip>;
710
+ }, z.core.$strip>, z.ZodObject<{
711
+ type: z.ZodLiteral<"project_root">;
712
+ payload: z.ZodObject<{
713
+ project: z.ZodString;
714
+ root: z.ZodString;
715
+ agentsMd: z.ZodOptional<z.ZodString>;
716
+ agentsMdTruncated: z.ZodOptional<z.ZodLiteral<true>>;
717
+ unavailable: z.ZodOptional<z.ZodObject<{
718
+ reason: z.ZodEnum<{
719
+ gone: "gone";
720
+ outside_mode: "outside_mode";
721
+ removed: "removed";
722
+ unreadable: "unreadable";
723
+ unsupported: "unsupported";
724
+ }>;
725
+ message: z.ZodString;
726
+ }, z.core.$strict>>;
727
+ skills: z.ZodDefault<z.ZodArray<z.ZodObject<{
728
+ name: z.ZodString & z.ZodType<string, string, z.core.$ZodTypeInternals<string, string>>;
729
+ description: z.ZodString;
730
+ digest: z.ZodString;
731
+ }, z.core.$strip>>>;
732
+ skillsTruncated: z.ZodOptional<z.ZodLiteral<true>>;
733
+ }, z.core.$strict>;
710
734
  }, z.core.$strip>, z.ZodObject<{
711
735
  type: z.ZodLiteral<"tool_call_started">;
712
736
  payload: z.ZodObject<{
@@ -642,6 +642,75 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
642
642
  allowedMode: z.enum(["auto", "sandbox"]).optional(),
643
643
  local: z.boolean().optional(),
644
644
  })),
645
+ /**
646
+ * The project a bound conversation's run read at its start (project root spec §4.4): the
647
+ * project's name and root, its `AGENTS.md` text, and per skill its name, description and digest;
648
+ * or, for a project the run cannot use, why (`unavailable`). The payload holds everything the
649
+ * event renders, so the request is reconstructable from the log. A run writes it before its first
650
+ * model call when it differs from the conversation's latest one; within a run the snapshot is
651
+ * fixed, so the request stays append-only. **Model-visible**: rendered at its position as a
652
+ * system message, after the agent's own instructions (`project root` spec §4.5); a summary
653
+ * covering it is followed by the latest one again. A new event type's new content needs no
654
+ * `DriftReason`.
655
+ */
656
+ ev("project_root", z
657
+ .object({
658
+ /** The project's name, as the conversation's binding resolved it. */
659
+ project: z.string().min(1).max(255),
660
+ /** Its root on the device, the run's working directory. */
661
+ root: z.string().min(1).max(4096),
662
+ /**
663
+ * The project's `AGENTS.md` as read at run start, cut at 64 KiB by the reader (the visible
664
+ * marker is part of that cap). Absent when the project has none (no reason, no notice:
665
+ * spec §4.7) or is unavailable.
666
+ */
667
+ agentsMd: z.string().optional(),
668
+ /** `agentsMd` ends at the reader's cap and carries the marker. Absent: not cut. */
669
+ agentsMdTruncated: z.literal(true).optional(),
670
+ /**
671
+ * The run cannot use the project: its root is `gone`, `outside_mode` (the device's current
672
+ * mode cannot read it), `unreadable`, the device offers no projects (`unsupported`), or the
673
+ * device no longer keeps the bound name and path (`removed`); `message` says so in English
674
+ * for the model. Set alone: no `agentsMd`, no skills.
675
+ */
676
+ unavailable: z
677
+ .object({
678
+ reason: z.enum(["gone", "outside_mode", "unreadable", "unsupported", "removed"]),
679
+ message: z.string().min(1).max(500),
680
+ })
681
+ .strict()
682
+ .optional(),
683
+ /**
684
+ * The project's `.agents/skills/*` SKILL.md files: name, description and a digest of the
685
+ * file. Bodies are never recorded (`Skill` reads one on demand, and its result is a
686
+ * `tool_result`). Empty for a project without skills; the reader keeps the first 100.
687
+ */
688
+ skills: z
689
+ .array(z.object({
690
+ name: z.string().refine(isSkillName, "invalid skill name"),
691
+ description: z.string().max(4096),
692
+ digest: z.string().min(1).max(128),
693
+ }))
694
+ .max(SKILLS_CATALOG_MAX)
695
+ .default([]),
696
+ /** The project has more skill directories than `skills` was read from. Absent: all read. */
697
+ skillsTruncated: z.literal(true).optional(),
698
+ })
699
+ .strict()
700
+ .superRefine((p, ctx) => {
701
+ if (p.unavailable === undefined)
702
+ return;
703
+ if (p.agentsMd !== undefined ||
704
+ p.agentsMdTruncated !== undefined ||
705
+ p.skillsTruncated !== undefined ||
706
+ p.skills.length > 0) {
707
+ ctx.addIssue({
708
+ code: "custom",
709
+ path: ["unavailable"],
710
+ message: "an unavailable project carries no AGENTS.md and no skills",
711
+ });
712
+ }
713
+ })),
645
714
  /** 工具调用开始执行之前写入(续跑时「有开始无结果」的调用记为结果未知,不再执行)。 */
646
715
  ev("tool_call_started", z.object({ step: count, callId: z.string(), toolKey: z.string(), specHash: z.string() })),
647
716
  /**
@@ -273,6 +273,13 @@ export interface ConversationsTable {
273
273
  * root next starts a run. While set the tree's wakes are held (agent map spec §6).
274
274
  */
275
275
  tree_stopped_at: ColumnType<Date | null, Date | string | null | undefined, Date | string | null>;
276
+ /**
277
+ * 0133: the project of its device it is bound to at creation (project root §4.3); null: free.
278
+ * Written only by the insert, never updated (`never`: the binding is immutable).
279
+ */
280
+ project_name: ColumnType<string | null, string | null | undefined, never>;
281
+ /** 0133: the absolute path the bound project resolved to at creation; null: free mode. */
282
+ project_path: ColumnType<string | null, string | null | undefined, never>;
276
283
  }
277
284
  /** 0060: an org's order of file-preview@1 previewers (UI refresh B Task 11). */
278
285
  export interface FilePreviewersTable {
@@ -976,6 +983,18 @@ export interface DeviceMachinesTable {
976
983
  local_policy: ColumnType<unknown | null, string | null | undefined, string | null>;
977
984
  /** 0118: the `policy` ops sent whose answer is not recorded yet (`PendingPolicyOp[]`). */
978
985
  pending_policy_ops: ColumnType<unknown, string | undefined, string>;
986
+ /** 0133: the owner's home directory the program reported in its hello; null when not reported. */
987
+ home: ColumnType<string | null, string | null | undefined, string | null>;
988
+ }
989
+ /** 0133: a device's projects (project root design §4.1), written only by the kernel. */
990
+ export interface DeviceProjectsTable {
991
+ device_id: string;
992
+ /** The project's identity on its device (`isDeviceProjectName`). */
993
+ name: string;
994
+ /** The project's absolute path on the device. */
995
+ path: string;
996
+ created_by: string;
997
+ created_at: Ts;
979
998
  }
980
999
  /** 0088_environments.sql, renamed in 0105: the device a member's new conversations use by default. */
981
1000
  export interface DeviceDefaultsTable {
@@ -1320,6 +1339,7 @@ export interface KernelDatabase {
1320
1339
  device_instances: DeviceInstancesTable;
1321
1340
  device_defaults: DeviceDefaultsTable;
1322
1341
  device_machines: DeviceMachinesTable;
1342
+ device_projects: DeviceProjectsTable;
1323
1343
  background_tasks: BackgroundTasksTable;
1324
1344
  scheduled_tasks: ScheduledTasksTable;
1325
1345
  scheduled_task_runs: ScheduledTaskRunsTable;
@@ -6,6 +6,7 @@ import type { SandboxMode } from "../sandbox/modes.js";
6
6
  import { SandboxProviders } from "../sandbox/providers.js";
7
7
  import { DeviceAccess } from "./access.js";
8
8
  import { DevicesService } from "./devices.service.js";
9
+ import { type WorkingProject } from "./working-root.js";
9
10
  /** `details[0].reason` of the error an anonymous IM conversation's sandbox call gets. */
10
11
  export declare const ANONYMOUS_NO_DEVICE = "anonymous";
11
12
  /** Anonymous IM senders have no device (spec §4.2 item 8): their sandbox tools are off. */
@@ -16,6 +17,12 @@ export interface NewConversationDevice {
16
17
  deviceId?: string;
17
18
  /** An IM thread: the person's IM default (`device_defaults`) when still usable. */
18
19
  im?: boolean;
20
+ /**
21
+ * The name of one of the chosen device's projects to bind the conversation to (project root
22
+ * design §4.3): resolved with `DeviceProjectsService.resolveForBinding` in the transaction that
23
+ * writes the conversation, its name and path stored and never changed. Absent: free mode.
24
+ */
25
+ project?: string;
19
26
  }
20
27
  /** What the command review needs to know about a call's device (auto mode spec §5.1, §5.4). */
21
28
  export interface CommandReviewFacts {
@@ -25,8 +32,39 @@ export interface CommandReviewFacts {
25
32
  ownerAccountId: string;
26
33
  mode: SandboxMode;
27
34
  allowedMode: SandboxMode;
28
- /** The workspace root commands start in; absent: no device bound (the review is skipped). */
35
+ /** The device's workspace root; absent: no device bound (the review is skipped). */
29
36
  workspace: string | undefined;
37
+ /**
38
+ * The owner's home ({@link WorkingFacts.home}): `~` and the home-level sensitive paths are
39
+ * judged against it, never against a project root. Null: unknown.
40
+ */
41
+ home: string | null;
42
+ /**
43
+ * The home prefix of the device's workspace (`homeOf`), judged by the review beside `home`: a
44
+ * project outside every home with an implausible reported home still protects the real one.
45
+ */
46
+ deviceHome: string | null;
47
+ /**
48
+ * The conversation's working root ({@link workingRootOf}): the project's root when the root
49
+ * conversation's latest `project_root` is usable, else `workspace`. The review's `workspace`
50
+ * fact: commands start here, and a write inside it needs no ask (project root spec §4.3).
51
+ */
52
+ workingRoot: string | undefined;
53
+ }
54
+ /**
55
+ * What decides the working root of a call (project root spec §4.3), read the same way for a
56
+ * sandbox tool and for the command review, so both decide the same root.
57
+ */
58
+ export interface WorkingFacts {
59
+ /**
60
+ * The device's workspace: the latest `device_paths` roots recorded in the calling conversation,
61
+ * else the root's, else the machine's reported roots, else the default.
62
+ */
63
+ workspace: string;
64
+ /** The owner's home: the machine's reported home, else the workspace's home prefix; null: unknown. */
65
+ home: string | null;
66
+ /** The root conversation's latest project snapshot; null: free, or none recorded yet. */
67
+ project: WorkingProject | null;
30
68
  }
31
69
  /**
32
70
  * Which device a conversation works in (spec 2026-11-07-environments-design §4.1 items 1, 3;
@@ -58,10 +96,26 @@ export declare class ConversationDevices {
58
96
  * and the tool call fails on its own.
59
97
  */
60
98
  reviewFacts(orgId: string, rootConversationId: string, conversationId?: string): Promise<CommandReviewFacts | null>;
99
+ /**
100
+ * The {@link WorkingFacts} of a call in `deviceId` by `conversationId` of the tree rooted at
101
+ * `rootConversationId`: the one source of the workspace, home and project snapshot that the
102
+ * sandbox tools and the command review decide the working root from.
103
+ */
104
+ workingFacts(orgId: string, rootConversationId: string, conversationId: string, deviceId: string): Promise<WorkingFacts>;
105
+ /**
106
+ * The project snapshot that decides the working root of the conversation tree rooted at
107
+ * `rootConversationId` (project root spec §4.3): its latest `project_root` event, read only when
108
+ * the conversation is bound to a project (a free conversation reads one row by its key). Null:
109
+ * free, or bound with no snapshot recorded yet.
110
+ */
111
+ workingProject(orgId: string, rootConversationId: string): Promise<WorkingProject | null>;
61
112
  /** The workspace root of a conversation's latest `device_paths` event, or null. */
62
113
  private recordedWorkspace;
63
- /** The workspace root the device's active machine last reported, or null (cloud: none). */
64
- private machineWorkspace;
114
+ /**
115
+ * The workspace root and the owner's home the device's active machine last reported, or null
116
+ * (cloud: no machine).
117
+ */
118
+ private machineRoots;
65
119
  /**
66
120
  * The device a new conversation of `accountId` is bound to: the chosen one when it is
67
121
  * usable by the person (else `device.not_found` / `device.unavailable`, and nothing