@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
@@ -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
  /**
@@ -1,10 +1,11 @@
1
- import { type ExtensionContext, type ExtensionManifest, type ExtensionPointRef, type Logger, resolveUiSlots, type SetupCheckArgs, type SetupGuidePlace, type ToolHandler, type ToolSpec } from "@capybara-hq/plugin-sdk";
1
+ import { type EmbedClaims, type ExtensionContext, type ExtensionManifest, type ExtensionPointRef, type HttpAccess, type Logger, type RouteCaller, resolveUiSlots, type SetupCheckArgs, type SetupGuidePlace, type ToolHandler, type ToolSpec } from "@capybara-hq/plugin-sdk";
2
2
  import type { Redis } from "ioredis";
3
3
  import { Kysely } from "kysely";
4
4
  import { type RegisteredHook } from "../extensions/hooks.js";
5
5
  import { RegistrationLedger } from "../extensions/ledger.js";
6
6
  import type { LockService } from "../infra/lock/lock.service.js";
7
7
  import type { ModelEmbeddings } from "../models/embeddings.js";
8
+ import type { OrgRole } from "../orgs/roles.js";
8
9
  import type { HookRunner } from "../runtime/hook-calls.js";
9
10
  import type { EmbedTokens } from "../ui/embed-token.js";
10
11
  import { type UiActionHandler, type UiRender } from "../ui/registry.js";
@@ -41,11 +42,24 @@ export interface KernelDeps {
41
42
  debug?(msg: string, fields?: Record<string, unknown>): void;
42
43
  };
43
44
  }
44
- /** 插件 HTTP 路由;`path` 已含 `/plugins/<name>` 前缀。 */
45
+ /**
46
+ * What `ctx.ui.verifyEmbedToken` returns for a valid token: the signed claims, with an org
47
+ * token's `role` replaced by the caller's role at verification time.
48
+ */
49
+ export type VerifiedEmbedClaims = EmbedClaims;
50
+ /**
51
+ * An extension HTTP route as registered through `ctx.http.route`. `path` is the full mounted path:
52
+ * `/plugins/<name>/orgs/:orgId<path>` for `member` / `admin`, `/plugins/<name><path>` for `public`
53
+ * / `embed`. `verifyEmbed` is the extension's own `ctx.ui.verifyEmbedToken` (the dispatch checks
54
+ * an `embed` route's token with it).
55
+ */
45
56
  export type Route = {
57
+ plugin: string;
46
58
  method: "GET" | "POST" | "PUT" | "DELETE";
47
59
  path: string;
48
- handler: (req: Request) => Promise<Response>;
60
+ access: HttpAccess;
61
+ handler: (req: Request, caller: RouteCaller) => Promise<Response>;
62
+ verifyEmbed: (token: string) => Promise<VerifiedEmbedClaims | null>;
49
63
  };
50
64
  /** 插件经 `ctx.tools.register` 注册的工具。 */
51
65
  export type RegisteredTool = {
@@ -81,6 +95,13 @@ export interface ExtensionPointAccess {
81
95
  * required bootstrap plugins, see `extensions/enabled.ts`), not cached.
82
96
  */
83
97
  export declare function queryEnabledPlugins(db: Kysely<any>, orgId: string): Promise<Set<string>>;
98
+ /**
99
+ * One query for a person's live org role on behalf of an extension: the extension enabled in the
100
+ * org, the org not deleted, the account active and still a member; returns the role now, or
101
+ * undefined when any of that fails. An embed token's verification and the `member` / `admin`
102
+ * route check (plugin-route-access.ts) both use it.
103
+ */
104
+ export declare function currentOrgRole(db: KernelDeps["db"], plugin: string, orgId: string, accountId: string): Promise<OrgRole | undefined>;
84
105
  /**
85
106
  * Whether the account is, right now, an active super admin (one query): what a platform embed
86
107
  * token and the platform refresh stream re-check.
@@ -139,7 +160,8 @@ export declare class LiveConfig {
139
160
  * - Granted automatically: `kv`, `lock`, `bus`, `queue`, `log`, `db`, `config`, `provide`;
140
161
  * - `secrets` only with `permissions.secrets`, `storage` only with `permissions.storage`, `models`
141
162
  * only with `permissions.models` (and only its `embedding` purposes, through `deps.models`); `http.route`
142
- * only the method + path declared in `permissions.http`; `tools.register` only names declared in
163
+ * only the method + path declared in `permissions.http` (the record carries the declared access and
164
+ * its mount, see {@link Route}); `tools.register` only names declared in
143
165
  * `permissions.tools`; `ui.view` / `ui.action` only ids declared in `permissions.ui.views` or
144
166
  * `permissions.ui.components` (a component's server view; during setup only); `setup.check` only
145
167
  * ids declared in `permissions.setupChecks` (during setup only, `place` and `run` read once and
@@ -23,9 +23,12 @@ export async function queryEnabledPlugins(db, orgId) {
23
23
  return new Set(rows.map((r) => r.plugin));
24
24
  }
25
25
  /**
26
- * 嵌入令牌校验时的一条查询:插件在该组织启用、组织未删除、账号 active、仍是成员;返回此刻的角色,不满足返回 undefined。
26
+ * One query for a person's live org role on behalf of an extension: the extension enabled in the
27
+ * org, the org not deleted, the account active and still a member; returns the role now, or
28
+ * undefined when any of that fails. An embed token's verification and the `member` / `admin`
29
+ * route check (plugin-route-access.ts) both use it.
27
30
  */
28
- async function currentEmbedRole(db, plugin, orgId, accountId) {
31
+ export async function currentOrgRole(db, plugin, orgId, accountId) {
29
32
  const row = await kernelDb(db)
30
33
  .selectFrom("memberships")
31
34
  .innerJoin("orgs", "orgs.id", "memberships.org_id")
@@ -180,7 +183,8 @@ export class LiveConfig {
180
183
  * - Granted automatically: `kv`, `lock`, `bus`, `queue`, `log`, `db`, `config`, `provide`;
181
184
  * - `secrets` only with `permissions.secrets`, `storage` only with `permissions.storage`, `models`
182
185
  * only with `permissions.models` (and only its `embedding` purposes, through `deps.models`); `http.route`
183
- * only the method + path declared in `permissions.http`; `tools.register` only names declared in
186
+ * only the method + path declared in `permissions.http` (the record carries the declared access and
187
+ * its mount, see {@link Route}); `tools.register` only names declared in
184
188
  * `permissions.tools`; `ui.view` / `ui.action` only ids declared in `permissions.ui.views` or
185
189
  * `permissions.ui.components` (a component's server view; during setup only); `setup.check` only
186
190
  * ids declared in `permissions.setupChecks` (during setup only, `place` and `run` read once and
@@ -253,7 +257,8 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
253
257
  },
254
258
  }
255
259
  : undefined;
256
- const declaredRoutes = new Set((perms.http ?? []).map((r) => `${r.method} ${r.path}`));
260
+ // "METHOD path" -> the access the manifest declares for it (the approved manifest)
261
+ const declaredRoutes = new Map((perms.http ?? []).map((r) => [`${r.method} ${r.path}`, r.access]));
257
262
  const declaredTools = new Set(perms.tools ?? []);
258
263
  const declaredHooks = new Set(perms.hooks ?? []);
259
264
  const declaredPolicyHooks = new Set(perms.policyHooks ?? []);
@@ -268,6 +273,36 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
268
273
  const embedTokens = deps.embedTokens;
269
274
  const uiResolution = resolveUiSlots(manifest.ui);
270
275
  const uiSlots = new Map(uiResolution.resolved.map((r) => [r.contribution.id, r.slot]));
276
+ // `ctx.ui.verifyEmbedToken`, also every route record's `verifyEmbed`. Accepts only a token signed
277
+ // for this extension, unexpired and untampered (see ui/embed-token.ts); then one query checks the
278
+ // present: the extension still enabled in that org, the org not deleted, the account active and
279
+ // still a member (PG every time, never cached: tokens already issued stop working at once when the
280
+ // extension is switched off, the member leaves or the account is disabled). The returned role is
281
+ // the current one; a token whose current role is below the minRole of its contribution's slot is
282
+ // refused (A38, UI slots spec §7). A platform token: the contribution is a `platform.page` and the
283
+ // account is still an active super admin. A token of one scope never verifies for the other's
284
+ // slots. Anything else is null.
285
+ const verifyEmbedToken = async (token) => {
286
+ const claims = embedTokens.verify(token, name);
287
+ if (claims === null)
288
+ return null;
289
+ const slot = uiSlots.get(claims.contribution);
290
+ if (claims.scope === "platform") {
291
+ if (slot?.id !== "platform.page")
292
+ return null;
293
+ return (await currentPlatformAccount(deps.db, claims.accountId)) ? claims : null;
294
+ }
295
+ if (claims.scope !== "org" || claims.orgId === undefined)
296
+ return null;
297
+ // the contribution's slot as loaded now: never `platform.page` through an org token, and the
298
+ // current role still meets the slot's minRole (a demoted caller's token stops working)
299
+ if (slot === undefined || slot.id === "platform.page")
300
+ return null;
301
+ const role = await currentOrgRole(deps.db, name, claims.orgId, claims.accountId);
302
+ if (role === undefined || !canUseSlot(slot, role))
303
+ return null;
304
+ return { ...claims, role };
305
+ };
271
306
  /** Ids of the extension's `platform.page` contributions (their invalidate takes no orgId). */
272
307
  const platformUi = new Set([...uiSlots].filter(([, s]) => s.id === "platform.page").map(([id]) => id));
273
308
  /** 校验能力可取用(非 brokered、已在清单声明),返回其登记信息。 */
@@ -400,13 +435,23 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
400
435
  if (typeof path !== "string" || !path.startsWith("/")) {
401
436
  throw new Error(`plugin ${name}: route path "${path}" must start with "/"`);
402
437
  }
403
- if (!declaredRoutes.has(`${method} ${path}`))
404
- deny(`permissions.http ${method} ${path}`);
405
- const full = `/plugins/${name}${path}`;
438
+ const access = declaredRoutes.get(`${method} ${path}`);
439
+ if (access === undefined)
440
+ return deny(`permissions.http ${method} ${path}`);
441
+ const full = access === "member" || access === "admin"
442
+ ? `/plugins/${name}/orgs/:orgId${path}`
443
+ : `/plugins/${name}${path}`;
406
444
  if (routes.some((r) => r.method === method && r.path === full)) {
407
445
  throw new Error(`plugin ${name}: duplicate route ${method} ${path}`);
408
446
  }
409
- const route = { method, path: full, handler };
447
+ const route = {
448
+ plugin: name,
449
+ method,
450
+ path: full,
451
+ access,
452
+ handler,
453
+ verifyEmbed: verifyEmbedToken,
454
+ };
410
455
  routes.push(route);
411
456
  ledger.add({
412
457
  kind: "route",
@@ -568,32 +613,7 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
568
613
  ? conversationTopic(t.conversationId)
569
614
  : orgUiTopic(t.orgId), msg);
570
615
  },
571
- // 只认签给本插件、未过期、未篡改的令牌(见 ui/embed-token.ts);再用一条查询核对此刻:本插件仍在该组织
572
- // 启用、组织未删除、账号 active 且仍是成员(每次查 PG、不缓存:停用插件、离职、停用账号后已签出的令牌立即失效)。
573
- // 返回的 role 是此刻的角色;令牌在此刻的角色低于贡献所在位置的 minRole 时失效(A38, UI slots spec §7)。
574
- // A platform token: the contribution is a `platform.page` and the account is still an active
575
- // super admin. A token of one scope never verifies for the other's slots. 其余一律 null
576
- async verifyEmbedToken(token) {
577
- const claims = embedTokens.verify(token, name);
578
- if (claims === null)
579
- return null;
580
- const slot = uiSlots.get(claims.contribution);
581
- if (claims.scope === "platform") {
582
- if (slot?.id !== "platform.page")
583
- return null;
584
- return (await currentPlatformAccount(deps.db, claims.accountId)) ? claims : null;
585
- }
586
- if (claims.scope !== "org" || claims.orgId === undefined)
587
- return null;
588
- // the contribution's slot as loaded now: never `platform.page` through an org token, and the
589
- // current role still meets the slot's minRole (a demoted caller's token stops working)
590
- if (slot === undefined || slot.id === "platform.page")
591
- return null;
592
- const role = await currentEmbedRole(deps.db, name, claims.orgId, claims.accountId);
593
- if (role === undefined || !canUseSlot(slot, role))
594
- return null;
595
- return { ...claims, role };
596
- },
616
+ verifyEmbedToken,
597
617
  },
598
618
  provide(extensionPoint, impl) {
599
619
  if (!manifest.provides.includes(extensionPoint)) {
@@ -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
@@ -15,9 +15,11 @@ import { KernelDb } from "../infra/database/kernel-db.js";
15
15
  import { TransactionHost } from "../infra/database/transaction-host.js";
16
16
  import { Transactional } from "../infra/database/transactional.decorator.js";
17
17
  import { isInternalProvider, SandboxProviders } from "../sandbox/providers.js";
18
+ import { homeOf } from "../sandbox/review/rules.js";
18
19
  import { deviceNotFound, sandboxUnavailable } from "../sandbox/sandbox.service.js";
19
20
  import { DeviceAccess } from "./access.js";
20
21
  import { DevicesService } from "./devices.service.js";
22
+ import { workingRootOf } from "./working-root.js";
21
23
  /** `details[0].reason` of the error an anonymous IM conversation's sandbox call gets. */
22
24
  export const ANONYMOUS_NO_DEVICE = "anonymous";
23
25
  /** Anonymous IM senders have no device (spec §4.2 item 8): their sandbox tools are off. */
@@ -89,21 +91,68 @@ let ConversationDevices = class ConversationDevices {
89
91
  ]);
90
92
  if (device === undefined)
91
93
  return null;
92
- const workspace = (await this.recordedWorkspace(conversationId)) ??
93
- (conversationId === rootConversationId
94
- ? null
95
- : await this.recordedWorkspace(rootConversationId)) ??
96
- (await this.machineWorkspace(deviceId)) ??
97
- DEFAULT_SANDBOX_ROOTS.workspace;
94
+ const mode = level?.mode ?? "sandbox";
95
+ const { workspace, home, project } = await this.workingFacts(orgId, rootConversationId, conversationId, deviceId);
98
96
  return {
99
97
  deviceId,
100
98
  deviceName: device.name ?? deviceId,
101
99
  ownerAccountId: conv.account_id,
102
- mode: level?.mode ?? "sandbox",
100
+ mode,
103
101
  allowedMode: level?.allowedMode ?? "sandbox",
104
102
  workspace,
103
+ home,
104
+ deviceHome: homeOf(workspace),
105
+ workingRoot: workingRootOf(project, { mode, workspace, home }),
105
106
  };
106
107
  }
108
+ /**
109
+ * The {@link WorkingFacts} of a call in `deviceId` by `conversationId` of the tree rooted at
110
+ * `rootConversationId`: the one source of the workspace, home and project snapshot that the
111
+ * sandbox tools and the command review decide the working root from.
112
+ */
113
+ async workingFacts(orgId, rootConversationId, conversationId, deviceId) {
114
+ const [recorded, recordedRoot, machine, project] = await Promise.all([
115
+ this.recordedWorkspace(conversationId),
116
+ conversationId === rootConversationId ? null : this.recordedWorkspace(rootConversationId),
117
+ this.machineRoots(deviceId),
118
+ this.workingProject(orgId, rootConversationId),
119
+ ]);
120
+ const workspace = recorded ?? recordedRoot ?? machine?.workspace ?? DEFAULT_SANDBOX_ROOTS.workspace;
121
+ // never from a project root: the machine's home, else the device workspace's home prefix
122
+ const reported = machine?.home;
123
+ const home = reported?.startsWith("/") ? reported : homeOf(workspace);
124
+ return { workspace, home, project };
125
+ }
126
+ /**
127
+ * The project snapshot that decides the working root of the conversation tree rooted at
128
+ * `rootConversationId` (project root spec §4.3): its latest `project_root` event, read only when
129
+ * the conversation is bound to a project (a free conversation reads one row by its key). Null:
130
+ * free, or bound with no snapshot recorded yet.
131
+ */
132
+ async workingProject(orgId, rootConversationId) {
133
+ const conv = await this.db
134
+ .selectFrom("conversations")
135
+ .select("project_path")
136
+ .where("id", "=", rootConversationId)
137
+ .where("org_id", "=", orgId)
138
+ .executeTakeFirst();
139
+ if (conv?.project_path == null)
140
+ return null;
141
+ const row = await this.db
142
+ .selectFrom("conversation_events")
143
+ .select([
144
+ sql `payload->>'root'`.as("root"),
145
+ sql `payload ? 'unavailable'`.as("unavailable"),
146
+ ])
147
+ .where("conversation_id", "=", rootConversationId)
148
+ .where("type", "=", "project_root")
149
+ .orderBy("seq", "desc")
150
+ .limit(1)
151
+ .executeTakeFirst();
152
+ if (row === undefined || typeof row.root !== "string")
153
+ return null;
154
+ return { root: row.root, unavailable: row.unavailable !== false };
155
+ }
107
156
  /** The workspace root of a conversation's latest `device_paths` event, or null. */
108
157
  async recordedWorkspace(conversationId) {
109
158
  const row = await this.db
@@ -116,15 +165,18 @@ let ConversationDevices = class ConversationDevices {
116
165
  .executeTakeFirst();
117
166
  return row?.workspace ?? null;
118
167
  }
119
- /** The workspace root the device's active machine last reported, or null (cloud: none). */
120
- async machineWorkspace(deviceId) {
168
+ /**
169
+ * The workspace root and the owner's home the device's active machine last reported, or null
170
+ * (cloud: no machine).
171
+ */
172
+ async machineRoots(deviceId) {
121
173
  const row = await this.db
122
174
  .selectFrom("device_machines")
123
- .select(sql `roots->>'workspace'`.as("workspace"))
175
+ .select([sql `roots->>'workspace'`.as("workspace"), "home"])
124
176
  .where("device_id", "=", deviceId)
125
177
  .where("revoked_at", "is", null)
126
178
  .executeTakeFirst();
127
- return row?.workspace ?? null;
179
+ return row === undefined ? null : { workspace: row.workspace ?? null, home: row.home ?? null };
128
180
  }
129
181
  /**
130
182
  * The device a new conversation of `accountId` is bound to: the chosen one when it is