@capybara-hq/kernel 0.1.0-rc.45 → 0.1.0-rc.47

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 (101) hide show
  1. package/bootstrap.json +3 -3
  2. package/dist/admin/admin.schemas.d.ts +6 -0
  3. package/dist/agents/agent-lookup.d.ts +5 -2
  4. package/dist/agents/agent-lookup.js +3 -0
  5. package/dist/catalog/marketplaces.service.d.ts +1 -1
  6. package/dist/config/schema.d.ts +7 -0
  7. package/dist/config/schema.js +27 -0
  8. package/dist/conversations/access.d.ts +14 -5
  9. package/dist/conversations/access.js +29 -20
  10. package/dist/conversations/conversations.service.d.ts +6 -1
  11. package/dist/conversations/conversations.service.js +12 -2
  12. package/dist/conversations/files.d.ts +43 -0
  13. package/dist/conversations/files.js +80 -3
  14. package/dist/ctx/create-ctx.d.ts +7 -0
  15. package/dist/ctx/create-ctx.js +9 -2
  16. package/dist/db/kernel-schema.d.ts +30 -0
  17. package/dist/errors.d.ts +22 -0
  18. package/dist/errors.js +22 -0
  19. package/dist/extensions/extensions.module.js +3 -0
  20. package/dist/extensions/host.d.ts +4 -1
  21. package/dist/extensions/host.js +15 -10
  22. package/dist/files/previewers.d.ts +44 -0
  23. package/dist/files/previewers.js +84 -30
  24. package/dist/html/csp.d.ts +13 -0
  25. package/dist/html/csp.js +33 -0
  26. package/dist/html/html-document.controller.d.ts +31 -0
  27. package/dist/html/html-document.controller.js +75 -0
  28. package/dist/html/html-document.service.d.ts +49 -0
  29. package/dist/html/html-document.service.js +143 -0
  30. package/dist/html/html-token.d.ts +58 -0
  31. package/dist/html/html-token.js +154 -0
  32. package/dist/html/html-type.d.ts +13 -0
  33. package/dist/html/html-type.js +40 -0
  34. package/dist/html/html.module.d.ts +6 -0
  35. package/dist/html/html.module.js +26 -0
  36. package/dist/http/api.module.js +14 -0
  37. package/dist/http/error.filter.d.ts +2 -0
  38. package/dist/http/error.filter.js +9 -2
  39. package/dist/http/plugin-route-access.d.ts +2 -1
  40. package/dist/http/plugin-route-access.js +16 -1
  41. package/dist/identity/settings.d.ts +26 -1
  42. package/dist/identity/settings.js +88 -2
  43. package/dist/infra/config/kernel-config.service.js +3 -0
  44. package/dist/infra/outbox/registry.d.ts +13 -0
  45. package/dist/infra/outbox/registry.js +8 -0
  46. package/dist/infra/throttler/credential-throttler.d.ts +4 -1
  47. package/dist/infra/throttler/credential-throttler.js +5 -2
  48. package/dist/infra/throttler/named-throttlers.d.ts +1 -0
  49. package/dist/infra/throttler/named-throttlers.js +14 -0
  50. package/dist/orgs/offboarding.d.ts +3 -1
  51. package/dist/orgs/offboarding.js +7 -1
  52. package/dist/orgs/settings.service.d.ts +21 -4
  53. package/dist/orgs/settings.service.js +47 -7
  54. package/dist/overrides.d.ts +3 -0
  55. package/dist/overrides.js +2 -0
  56. package/dist/platform/exclusions.js +63 -0
  57. package/dist/platform/operation.js +1 -1
  58. package/dist/platform/ops/admin.ops.js +18 -3
  59. package/dist/platform/ops/org-settings.ops.js +6 -2
  60. package/dist/platform/ops/orgs.ops.js +3 -0
  61. package/dist/platform/ops/shares.ops.d.ts +16 -0
  62. package/dist/platform/ops/shares.ops.js +107 -0
  63. package/dist/platform/platform-ops.module.d.ts +2 -1
  64. package/dist/platform/platform-ops.module.js +5 -0
  65. package/dist/platform/route-schemas.js +3 -0
  66. package/dist/roles/worker.module.js +6 -0
  67. package/dist/runtime/maintenance.d.ts +4 -2
  68. package/dist/runtime/maintenance.js +14 -4
  69. package/dist/shares/liveness.d.ts +59 -0
  70. package/dist/shares/liveness.js +163 -0
  71. package/dist/shares/revoke.d.ts +26 -0
  72. package/dist/shares/revoke.js +43 -0
  73. package/dist/shares/settings.d.ts +76 -0
  74. package/dist/shares/settings.js +117 -0
  75. package/dist/shares/share-code.d.ts +4 -0
  76. package/dist/shares/share-code.js +28 -0
  77. package/dist/shares/share-objects.d.ts +52 -0
  78. package/dist/shares/share-objects.js +123 -0
  79. package/dist/shares/share-open.controller.d.ts +35 -0
  80. package/dist/shares/share-open.controller.js +107 -0
  81. package/dist/shares/share-open.service.d.ts +107 -0
  82. package/dist/shares/share-open.service.js +287 -0
  83. package/dist/shares/share-previews.controller.d.ts +50 -0
  84. package/dist/shares/share-previews.controller.js +115 -0
  85. package/dist/shares/shares.controller.d.ts +34 -0
  86. package/dist/shares/shares.controller.js +114 -0
  87. package/dist/shares/shares.module.d.ts +8 -0
  88. package/dist/shares/shares.module.js +41 -0
  89. package/dist/shares/shares.schemas.d.ts +31 -0
  90. package/dist/shares/shares.schemas.js +25 -0
  91. package/dist/shares/shares.service.d.ts +182 -0
  92. package/dist/shares/shares.service.js +553 -0
  93. package/dist/shares/sweep.job.d.ts +72 -0
  94. package/dist/shares/sweep.job.js +330 -0
  95. package/dist/tools/builtins/sandbox/deliver.js +3 -1
  96. package/dist/ui/embed-token.d.ts +2 -2
  97. package/dist/ui/embed-token.js +38 -2
  98. package/dist/ui/views.d.ts +6 -0
  99. package/dist/ui/views.js +17 -0
  100. package/package.json +2 -2
  101. package/src/migrations/0161_file_shares.sql +35 -0
package/bootstrap.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "schemaVersion": 1,
4
4
  "marketplace": {
5
5
  "url": "https://github.com/capybara-hq/plugins.git",
6
- "commit": "d83e667fb99d3251dc148ee2583ad8b4722b711f"
6
+ "commit": "84a5307e2757bd4fc1f9f11b43be456b63f0f9c7"
7
7
  },
8
8
  "plugins": [
9
9
  {
@@ -115,8 +115,8 @@
115
115
  "name": "file-preview",
116
116
  "source": "npm",
117
117
  "npm": "@capybara-hq/plugin-file-preview",
118
- "version": "0.1.0-rc.2",
119
- "integrity": "sha512-pEV/P8ahHt2wU3xudhUmJKX6sKfJCG+q+MNo0T+AiySl31TyPl7bsg9el5Romtg3iFbFlOh7DameL5YgAAzVnw==",
118
+ "version": "0.1.0-rc.3",
119
+ "integrity": "sha512-4GMeq6gpjloCmTrEidiUHX5v6PN4oTfRDWcx+sLb5NlUoSk5DaJVVtJDc5oNDzow09OSm62DJchDOBJItLdwrA==",
120
120
  "required": false,
121
121
  "builtin": true
122
122
  }
@@ -82,6 +82,12 @@ export declare const DeploymentSettingsBody: z.ZodObject<{
82
82
  reserveTokens: z.ZodOptional<z.ZodNumber>;
83
83
  maxOutputTokens: z.ZodOptional<z.ZodNumber>;
84
84
  }, z.core.$strict>>;
85
+ externalSharing: z.ZodOptional<z.ZodNullable<z.ZodEnum<{
86
+ allow: "allow";
87
+ deny: "deny";
88
+ }>>>;
89
+ shareMaxExpiryDays: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
90
+ htmlRenderCdnAllowlist: z.ZodOptional<z.ZodArray<z.ZodType<string, unknown, z.core.$ZodTypeInternals<string, unknown>>>>;
85
91
  }, z.core.$strict>;
86
92
  export declare const PurposeParams: z.ZodObject<{
87
93
  purpose: z.ZodString;
@@ -1,4 +1,4 @@
1
- import { type ExpressionBuilder } from "kysely";
1
+ import { type Expression, type ExpressionBuilder } from "kysely";
2
2
  import type { KernelDatabase, KernelSchemaDb } from "../db/kernel-schema.js";
3
3
  import { KernelDb } from "../infra/database/kernel-db.js";
4
4
  import { type AgentDefinition } from "./definition.js";
@@ -41,8 +41,11 @@ export interface AgentProvenance {
41
41
  * 可见性判定(`canUse`)的 SQL 条件:agent 未删除、所属组织未删除,且
42
42
  * - viewer 为账号:仍是该组织成员(含访客),并且是负责人 / visibility='org' / 在 agent_members 名单中;
43
43
  * - viewer 为 null(该组织的服务令牌):只认 visibility='org'。
44
+ *
45
+ * The viewer may also be a column of the outer query (`sql.ref("file_shares.created_by")`): the
46
+ * share liveness check asks whether each share's creator still sees the agent, in one query.
44
47
  */
45
- export declare function visibleTo(viewerAccountId: string | null): (eb: ExpressionBuilder<KernelDatabase, "agents">) => import("kysely").ExpressionWrapper<KernelDatabase, "agents", import("kysely").SqlBool>;
48
+ export declare function visibleTo(viewerAccountId: string | Expression<string> | null): (eb: ExpressionBuilder<KernelDatabase, "agents">) => import("kysely").ExpressionWrapper<KernelDatabase, "agents", import("kysely").SqlBool>;
46
49
  /**
47
50
  * Whether the live agent `agentId` is visible to `accountId` under the normal visibility rule
48
51
  * ({@link visibleTo}: owner, `visibility = 'org'`, or listed in `agent_members`, while a member of
@@ -18,6 +18,9 @@ const notFound = () => new ApiError("agent.not_found", "Agent not found");
18
18
  * 可见性判定(`canUse`)的 SQL 条件:agent 未删除、所属组织未删除,且
19
19
  * - viewer 为账号:仍是该组织成员(含访客),并且是负责人 / visibility='org' / 在 agent_members 名单中;
20
20
  * - viewer 为 null(该组织的服务令牌):只认 visibility='org'。
21
+ *
22
+ * The viewer may also be a column of the outer query (`sql.ref("file_shares.created_by")`): the
23
+ * share liveness check asks whether each share's creator still sees the agent, in one query.
21
24
  */
22
25
  export function visibleTo(viewerAccountId) {
23
26
  return (eb) => {
@@ -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.32";
191
+ readonly sdk: "0.1.0-rc.33";
192
192
  };
193
193
  /** Whether this deployment satisfies the entry's `minKernel`. */
194
194
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -190,6 +190,13 @@ export declare const KernelConfigSchema: z.ZodObject<{
190
190
  unboundTtlHours: z.ZodDefault<z.ZodNumber>;
191
191
  requestMediaBytes: z.ZodDefault<z.ZodNumber>;
192
192
  }, z.core.$strict>>;
193
+ sharing: z.ZodPrefault<z.ZodObject<{
194
+ external: z.ZodOptional<z.ZodEnum<{
195
+ allow: "allow";
196
+ deny: "deny";
197
+ }>>;
198
+ maxExpiryDays: z.ZodOptional<z.ZodNumber>;
199
+ }, z.core.$strict>>;
193
200
  subagents: z.ZodPrefault<z.ZodObject<{
194
201
  maxDepth: z.ZodDefault<z.ZodNumber>;
195
202
  maxConcurrentPerConversation: z.ZodDefault<z.ZodNumber>;
@@ -1140,6 +1140,33 @@ export const KernelConfigSchema = z.strictObject({
1140
1140
  path: ["maxBytes"],
1141
1141
  })
1142
1142
  .prefault({}),
1143
+ /**
1144
+ * File sharing governance (file sharing spec §8). Both fields are also deployment settings the
1145
+ * super admin changes in the admin console (`externalSharing`, `shareMaxExpiryDays`); a field
1146
+ * set here wins and is read-only there, so neither has a schema default (an unset field means
1147
+ * no config source sets it).
1148
+ */
1149
+ sharing: z
1150
+ .strictObject({
1151
+ external: z
1152
+ .enum(["allow", "deny"])
1153
+ .optional()
1154
+ .meta(meta({
1155
+ hot: true,
1156
+ description: "Whether organizations may share conversation files with people outside the deployment through public links (default deny): allow lets each organization turn external sharing on in its own settings (it is off until it does); deny stops every external link at once. Internal links (for signed-in members) are not affected. Set here, it is read-only in the admin console",
1157
+ })),
1158
+ maxExpiryDays: z
1159
+ .number()
1160
+ .int()
1161
+ .min(1)
1162
+ .max(365)
1163
+ .optional()
1164
+ .meta(meta({
1165
+ hot: true,
1166
+ description: "The longest expiry a file share may be given, in days (1 to 365, default 30); an external share always expires, an internal one may also never expire. Set here, it is read-only in the admin console",
1167
+ })),
1168
+ })
1169
+ .prefault({}),
1143
1170
  subagents: z
1144
1171
  .strictObject({
1145
1172
  maxDepth: z
@@ -1,4 +1,4 @@
1
- import { type ExpressionBuilder } from "kysely";
1
+ import { type Expression, type ExpressionBuilder, type SqlBool } from "kysely";
2
2
  import type { KernelDatabase } from "../db/kernel-schema.js";
3
3
  import { KernelDb } from "../infra/database/kernel-db.js";
4
4
  /**
@@ -9,7 +9,17 @@ import { KernelDb } from "../infra/database/kernel-db.js";
9
9
  * that org. Any other kind passes. The child's own `agent_id` (the dispatched agent for an org
10
10
  * agent, §5.5) is checked on top by the callers.
11
11
  */
12
- export declare const parentReachable: (viewerAccountId: string) => (eb: ExpressionBuilder<KernelDatabase, "conversations">) => import("kysely").ExpressionWrapper<KernelDatabase, "conversations", import("kysely").SqlBool>;
12
+ export declare const parentReachable: (viewerAccountId: string | Expression<string>) => (eb: ExpressionBuilder<KernelDatabase, "conversations">) => import("kysely").ExpressionWrapper<KernelDatabase, "conversations", SqlBool>;
13
+ /**
14
+ * The predicate of {@link ConversationAccess.isAccessible} over the `conversations` table (the
15
+ * org is the caller's condition): the conversation belongs to the viewer and is not deleted, it is
16
+ * a chat or sub-agent conversation whose tree root is reachable ({@link parentReachable}), the
17
+ * viewer's account is active, and its agent is not deleted and still visible to the viewer
18
+ * (`visibleTo` includes "the org is not deleted, the viewer is still a member"). The viewer may be
19
+ * a column of the outer query: the share liveness check (`shares/liveness.ts`) asks it of each
20
+ * share's creator (`sql.ref("file_shares.created_by")`) in the same query.
21
+ */
22
+ export declare const accessibleTo: (viewer: string | Expression<string>) => (eb: ExpressionBuilder<KernelDatabase, "conversations">) => Expression<SqlBool>;
13
23
  /**
14
24
  * Whether a person may still see a conversation (one query, no agent view): what the event stream,
15
25
  * attachment downloads, file and output reads and the extension UI check. `ConversationsService`
@@ -20,9 +30,8 @@ export declare class ConversationAccess {
20
30
  private readonly db;
21
31
  constructor(db: KernelDb);
22
32
  /**
23
- * 轻量的可见性判定(一条查询,不加载 agent 视图),供长连接(SSE)建立时与定期复核用:
24
- * 会话属于该组织且归 viewer 所有、viewer 账号仍为 active、agent 未删除且对 viewer 仍可见
25
- * (`visibleTo` 已含「组织未删除、viewer 仍是成员」)。
33
+ * The light visibility check (one query, no agent view) used when a long connection (SSE) opens
34
+ * and on its periodic re-check: {@link accessibleTo} for a conversation of this org.
26
35
  */
27
36
  isAccessible(orgId: string, conversationId: string, viewerAccountId: string): Promise<boolean>;
28
37
  }
@@ -53,6 +53,32 @@ export const parentReachable = (viewerAccountId) => (eb) => eb.or([
53
53
  .where("agents.deleted_at", "is", null)
54
54
  .where(visibleTo(viewerAccountId))),
55
55
  ]);
56
+ /**
57
+ * The predicate of {@link ConversationAccess.isAccessible} over the `conversations` table (the
58
+ * org is the caller's condition): the conversation belongs to the viewer and is not deleted, it is
59
+ * a chat or sub-agent conversation whose tree root is reachable ({@link parentReachable}), the
60
+ * viewer's account is active, and its agent is not deleted and still visible to the viewer
61
+ * (`visibleTo` includes "the org is not deleted, the viewer is still a member"). The viewer may be
62
+ * a column of the outer query: the share liveness check (`shares/liveness.ts`) asks it of each
63
+ * share's creator (`sql.ref("file_shares.created_by")`) in the same query.
64
+ */
65
+ export const accessibleTo = (viewer) => (eb) => eb.and([
66
+ eb("conversations.account_id", "=", viewer),
67
+ eb("conversations.deleted_at", "is", null),
68
+ eb("conversations.kind", "in", ["chat", "subagent"]),
69
+ parentReachable(viewer)(eb),
70
+ eb.exists(eb
71
+ .selectFrom("accounts")
72
+ .select(sql `1`.as("one"))
73
+ .where("accounts.id", "=", viewer)
74
+ .where("accounts.status", "=", "active")),
75
+ eb.exists(eb
76
+ .selectFrom("agents")
77
+ .select(sql `1`.as("one"))
78
+ .whereRef("agents.id", "=", "conversations.agent_id")
79
+ .where("agents.deleted_at", "is", null)
80
+ .where(visibleTo(viewer))),
81
+ ]);
56
82
  /**
57
83
  * Whether a person may still see a conversation (one query, no agent view): what the event stream,
58
84
  * attachment downloads, file and output reads and the extension UI check. `ConversationsService`
@@ -65,9 +91,8 @@ let ConversationAccess = class ConversationAccess {
65
91
  this.db = db;
66
92
  }
67
93
  /**
68
- * 轻量的可见性判定(一条查询,不加载 agent 视图),供长连接(SSE)建立时与定期复核用:
69
- * 会话属于该组织且归 viewer 所有、viewer 账号仍为 active、agent 未删除且对 viewer 仍可见
70
- * (`visibleTo` 已含「组织未删除、viewer 仍是成员」)。
94
+ * The light visibility check (one query, no agent view) used when a long connection (SSE) opens
95
+ * and on its periodic re-check: {@link accessibleTo} for a conversation of this org.
71
96
  */
72
97
  async isAccessible(orgId, conversationId, viewerAccountId) {
73
98
  const row = await this.db
@@ -75,23 +100,7 @@ let ConversationAccess = class ConversationAccess {
75
100
  .select("conversations.id")
76
101
  .where("conversations.id", "=", conversationId)
77
102
  .where("conversations.org_id", "=", orgId)
78
- .where("conversations.account_id", "=", viewerAccountId)
79
- .where("conversations.deleted_at", "is", null)
80
- .where("conversations.kind", "in", ["chat", "subagent"])
81
- .where(parentReachable(viewerAccountId))
82
- .where((eb) => eb.and([
83
- eb.exists(eb
84
- .selectFrom("accounts")
85
- .select(sql `1`.as("one"))
86
- .where("accounts.id", "=", viewerAccountId)
87
- .where("accounts.status", "=", "active")),
88
- eb.exists(eb
89
- .selectFrom("agents")
90
- .select(sql `1`.as("one"))
91
- .whereRef("agents.id", "=", "conversations.agent_id")
92
- .where("agents.deleted_at", "is", null)
93
- .where(visibleTo(viewerAccountId))),
94
- ]))
103
+ .where(accessibleTo(viewerAccountId))
95
104
  .executeTakeFirst();
96
105
  return row !== undefined;
97
106
  }
@@ -8,6 +8,7 @@ import { DeviceProjectsService } from "../devices/device-projects.service.js";
8
8
  import { KernelDb } from "../infra/database/kernel-db.js";
9
9
  import { TransactionHost } from "../infra/database/transaction-host.js";
10
10
  import { KernelEvents } from "../infra/events/kernel-events.js";
11
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
11
12
  import { ProviderRegistry } from "../runtime/providers.js";
12
13
  import { RunDeletion } from "../runtime/run-deletion.js";
13
14
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
@@ -306,6 +307,8 @@ export declare class ConversationsService {
306
307
  private readonly events;
307
308
  readonly txHost: TransactionHost;
308
309
  private readonly ceilings;
310
+ /** Owes the snapshot deletions of the shares a deletion revokes (file sharing spec §9). */
311
+ private readonly outbox;
309
312
  constructor(permissions: Pick<PermissionProfilesService, "initialize" | "lockInitial">, db: KernelDb, eventLog: EventLog, agents: Pick<AgentLookup, "get">, access: Pick<ConversationAccess, "isAccessible">,
310
313
  /** Starts and stops the conversation's runs. */
311
314
  runs: RunControl,
@@ -326,7 +329,9 @@ export declare class ConversationsService {
326
329
  /** A starter's message skips the run's pending questions (reply-while-question spec §8.1). */
327
330
  questions: Pick<QuestionsService, "skipPendingIn">,
328
331
  /** ... and its pending network asks (network ask-to-allow spec §6.7). */
329
- approvals: Pick<ApprovalsService, "skipNetworkIn">, events: Pick<KernelEvents, "emit">, txHost: TransactionHost, ceilings: PermissionCeilingWrites);
332
+ approvals: Pick<ApprovalsService, "skipNetworkIn">, events: Pick<KernelEvents, "emit">, txHost: TransactionHost, ceilings: PermissionCeilingWrites,
333
+ /** Owes the snapshot deletions of the shares a deletion revokes (file sharing spec §9). */
334
+ outbox: Pick<OutboxService, "add">);
330
335
  /**
331
336
  * Creates an empty conversation bound to its device (`pick`, see
332
337
  * {@link ConversationDevices.forNew}); an agent the account cannot use →
@@ -20,12 +20,14 @@ import { KernelDb } from "../infra/database/kernel-db.js";
20
20
  import { TransactionHost, withTransactionFencePrelude, } from "../infra/database/transaction-host.js";
21
21
  import { Transactional } from "../infra/database/transactional.decorator.js";
22
22
  import { KernelEvents } from "../infra/events/kernel-events.js";
23
+ import { OutboxService } from "../infra/outbox/outbox.service.js";
23
24
  import { ProviderRegistry } from "../runtime/providers.js";
24
25
  import { RunControl as RunControlService } from "../runtime/run-control.js";
25
26
  import { RunDeletion } from "../runtime/run-deletion.js";
26
27
  import { rootConversationOf } from "../runtime/subagents/child.js";
27
28
  import { PermissionCeilingWrites } from "../sandbox/permission-ceiling-writes.js";
28
29
  import { permissionScopeHash } from "../sandbox/permission-facts.js";
30
+ import { revokeSharesIn } from "../shares/revoke.js";
29
31
  import { SkillInvoker } from "../skills/invoke.js";
30
32
  import { ApprovalsService } from "../tools/approvals.service.js";
31
33
  import { ConnectorContent } from "../tools/connector-content.js";
@@ -170,6 +172,7 @@ let ConversationsService = class ConversationsService {
170
172
  events;
171
173
  txHost;
172
174
  ceilings;
175
+ outbox;
173
176
  constructor(permissions, db, eventLog, agents, access,
174
177
  /** Starts and stops the conversation's runs. */
175
178
  runs,
@@ -190,7 +193,9 @@ let ConversationsService = class ConversationsService {
190
193
  /** A starter's message skips the run's pending questions (reply-while-question spec §8.1). */
191
194
  questions,
192
195
  /** ... and its pending network asks (network ask-to-allow spec §6.7). */
193
- approvals, events, txHost, ceilings) {
196
+ approvals, events, txHost, ceilings,
197
+ /** Owes the snapshot deletions of the shares a deletion revokes (file sharing spec §9). */
198
+ outbox) {
194
199
  this.permissions = permissions;
195
200
  this.db = db;
196
201
  this.eventLog = eventLog;
@@ -209,6 +214,7 @@ let ConversationsService = class ConversationsService {
209
214
  this.events = events;
210
215
  this.txHost = txHost;
211
216
  this.ceilings = ceilings;
217
+ this.outbox = outbox;
212
218
  }
213
219
  /**
214
220
  * Creates an empty conversation bound to its device (`pick`, see
@@ -510,6 +516,9 @@ let ConversationsService = class ConversationsService {
510
516
  .where("conversation_id", "=", conversationId)
511
517
  .execute();
512
518
  await unbindConversation(this.db.db, conversationId);
519
+ // its shares stop with it and their snapshots are owed for deletion (file sharing spec §9);
520
+ // a share being created waits on the row lock above (`FOR SHARE`) and then finds it deleted
521
+ await revokeSharesIn(this.db.db, this.outbox, { conversationId }, "conversation_deleted");
513
522
  }
514
523
  /** 读会话:非所有者、或 agent 已对所有者不可用 → `conversation.not_found`。 */
515
524
  async get(orgId, conversationId, viewerAccountId) {
@@ -1316,6 +1325,7 @@ ConversationsService = __decorate([
1316
1325
  __param(14, Inject(ApprovalsService)),
1317
1326
  __param(15, Inject(KernelEvents)),
1318
1327
  __param(16, Inject(TransactionHost)),
1319
- __param(17, Inject(PermissionCeilingWrites))
1328
+ __param(17, Inject(PermissionCeilingWrites)),
1329
+ __param(18, Inject(OutboxService))
1320
1330
  ], ConversationsService);
1321
1331
  export { ConversationsService };
@@ -41,6 +41,11 @@ export interface FileOutput {
41
41
  * `callId` is empty).
42
42
  */
43
43
  origin: "delivered" | "uploaded";
44
+ /**
45
+ * The viewer has a share of this file that is not revoked or expired (file sharing spec §5): of
46
+ * its source path for a delivered file (any version), of the attachment for an uploaded one.
47
+ */
48
+ shared: boolean;
44
49
  }
45
50
  /** Text content of one file version, at most the requested bytes. */
46
51
  export interface FileContent {
@@ -54,6 +59,12 @@ export interface FileContent {
54
59
  originalType: string;
55
60
  truncated: boolean;
56
61
  }
62
+ /** The built-in preview kind of a content type (the files list's `previewable`; share metadata too). */
63
+ export declare const previewKind: (contentType: string) => FileOutput["previewable"];
64
+ /** Drops an incomplete UTF-8 sequence at the end of a cut buffer. */
65
+ export declare function trimUtf8(b: Buffer): Buffer;
66
+ /** Reads at most `max` bytes of a stream, then cancels it. */
67
+ export declare function readPrefix(body: ReadableStream<Uint8Array>, max: number): Promise<Buffer>;
57
68
  /** Storage HEADs a files list sends at once (review M1). */
58
69
  export declare const HEAD_CONCURRENCY = 8;
59
70
  export declare class ConversationFiles {
@@ -97,6 +108,7 @@ export declare class ConversationFiles {
97
108
  * (previewers, embed grants): the key never leaves the kernel. An attachment whose stored object
98
109
  * is gone or no longer the one finalize checked → `conversation.artifact_removed`; `recorded` is
99
110
  * then what a later read of the object must still match ({@link attachmentContentMatches}).
111
+ * `sourcePath` is the version group of a delivered file, null for an attachment.
100
112
  */
101
113
  file(orgId: string, conversationId: string, viewer: string, fileId: string): Promise<{
102
114
  id: string;
@@ -104,11 +116,42 @@ export declare class ConversationFiles {
104
116
  contentType: string;
105
117
  size: number;
106
118
  objectKey: string;
119
+ /** The version group of a delivered file; null for an attachment. */
120
+ sourcePath: string | null;
107
121
  recorded?: {
108
122
  size: number;
109
123
  etag: string | null;
110
124
  };
111
125
  }>;
126
+ /**
127
+ * Which file a file id names (any version's id, or an attachment sent in the conversation), after
128
+ * checking the viewer can read the conversation; storage is not read, so a removed file still
129
+ * resolves (its shares are listed and revoked by it).
130
+ */
131
+ identify(orgId: string, conversationId: string, viewer: string, fileId: string): Promise<{
132
+ id: string;
133
+ sourcePath: string | null;
134
+ }>;
135
+ /**
136
+ * The newest delivered version of `sourcePath` whose object is still stored, after checking the
137
+ * viewer can read the conversation (a share's "update to latest", file sharing spec §2); with
138
+ * `after` (a version id), only versions delivered after it. Versions whose object is gone are
139
+ * skipped; at most {@link FILE_VERSIONS_MAX} are looked at. Null when none is available.
140
+ */
141
+ latestAvailable(orgId: string, conversationId: string, viewer: string, sourcePath: string, opts?: {
142
+ after?: string;
143
+ }): Promise<{
144
+ id: string;
145
+ name: string;
146
+ contentType: string;
147
+ size: number;
148
+ objectKey: string;
149
+ } | null>;
150
+ /**
151
+ * The source paths and attachments the viewer has a share of in the conversation that is not
152
+ * revoked or expired ({@link FileOutput.shared}).
153
+ */
154
+ private viewerShares;
112
155
  /**
113
156
  * The first `limit` bytes of a text file version (any version's id, or an attachment sent in the
114
157
  * conversation). Not text, or NUL bytes in
@@ -34,9 +34,10 @@ const artifactNotFound = () => new ApiError("conversation.artifact_not_found", "
34
34
  const removed = () => new ApiError("conversation.artifact_removed", "The file is no longer available");
35
35
  /** Whether `a` lists before `b`: newer first, then the larger id (a total, stable order). */
36
36
  const before = (a, b) => a.at.getTime() !== b.at.getTime() ? a.at.getTime() > b.at.getTime() : a.id > b.id;
37
- const previewKind = (contentType) => isInlineArtifactType(contentType) ? "image" : isTextArtifactType(contentType) ? "text" : null;
37
+ /** The built-in preview kind of a content type (the files list's `previewable`; share metadata too). */
38
+ export const previewKind = (contentType) => isInlineArtifactType(contentType) ? "image" : isTextArtifactType(contentType) ? "text" : null;
38
39
  /** Drops an incomplete UTF-8 sequence at the end of a cut buffer. */
39
- function trimUtf8(b) {
40
+ export function trimUtf8(b) {
40
41
  let i = b.length - 1;
41
42
  let cont = 0;
42
43
  while (i >= 0 && cont < 3 && (b[i] & 0xc0) === 0x80) {
@@ -49,7 +50,8 @@ function trimUtf8(b) {
49
50
  const need = lead >= 0xf0 ? 3 : lead >= 0xe0 ? 2 : lead >= 0xc0 ? 1 : 0;
50
51
  return need > cont ? b.subarray(0, i) : b;
51
52
  }
52
- async function readPrefix(body, max) {
53
+ /** Reads at most `max` bytes of a stream, then cancels it. */
54
+ export async function readPrefix(body, max) {
53
55
  const reader = body.getReader();
54
56
  const chunks = [];
55
57
  let n = 0;
@@ -144,6 +146,7 @@ let ConversationFiles = class ConversationFiles {
144
146
  contentType: a.contentType,
145
147
  size: a.size,
146
148
  objectKey: a.objectKey,
149
+ sourcePath: a.sourcePath,
147
150
  };
148
151
  }
149
152
  const [u] = await this.attachments.boundRows(orgId, conversationId, fileId);
@@ -155,6 +158,7 @@ let ConversationFiles = class ConversationFiles {
155
158
  contentType: u.contentType,
156
159
  size: u.size,
157
160
  objectKey: u.objectKey,
161
+ sourcePath: null,
158
162
  upload: u,
159
163
  };
160
164
  }
@@ -211,6 +215,7 @@ let ConversationFiles = class ConversationFiles {
211
215
  start = at + 1;
212
216
  }
213
217
  const page = ordered.slice(start, start + opts.limit);
218
+ const shares = await this.viewerShares(conversationId, viewer);
214
219
  const store = this.storage.kernel(orgId);
215
220
  const files = await mapLimit(page, HEAD_CONCURRENCY, async (e) => {
216
221
  if (e.origin === "uploaded") {
@@ -230,6 +235,7 @@ let ConversationFiles = class ConversationFiles {
230
235
  status: same ? "available" : "removed",
231
236
  previewable: previewKind(u.contentType),
232
237
  origin: "uploaded",
238
+ shared: shares.uploads.has(u.id),
233
239
  };
234
240
  }
235
241
  const g = e.group;
@@ -251,6 +257,7 @@ let ConversationFiles = class ConversationFiles {
251
257
  status: head ? "available" : "removed",
252
258
  previewable: previewKind(latest.contentType),
253
259
  origin: "delivered",
260
+ shared: shares.paths.has(latest.sourcePath),
254
261
  };
255
262
  });
256
263
  const next = start + opts.limit < ordered.length ? (files.at(-1)?.id ?? null) : null;
@@ -262,6 +269,7 @@ let ConversationFiles = class ConversationFiles {
262
269
  * (previewers, embed grants): the key never leaves the kernel. An attachment whose stored object
263
270
  * is gone or no longer the one finalize checked → `conversation.artifact_removed`; `recorded` is
264
271
  * then what a later read of the object must still match ({@link attachmentContentMatches}).
272
+ * `sourcePath` is the version group of a delivered file, null for an attachment.
265
273
  */
266
274
  async file(orgId, conversationId, viewer, fileId) {
267
275
  await this.checkAccess(orgId, conversationId, viewer);
@@ -273,6 +281,75 @@ let ConversationFiles = class ConversationFiles {
273
281
  throw removed();
274
282
  return { ...f, recorded: { size: upload.size, etag: upload.etag } };
275
283
  }
284
+ /**
285
+ * Which file a file id names (any version's id, or an attachment sent in the conversation), after
286
+ * checking the viewer can read the conversation; storage is not read, so a removed file still
287
+ * resolves (its shares are listed and revoked by it).
288
+ */
289
+ async identify(orgId, conversationId, viewer, fileId) {
290
+ await this.checkAccess(orgId, conversationId, viewer);
291
+ const f = await this.resolve(orgId, conversationId, fileId);
292
+ return { id: f.id, sourcePath: f.sourcePath };
293
+ }
294
+ /**
295
+ * The newest delivered version of `sourcePath` whose object is still stored, after checking the
296
+ * viewer can read the conversation (a share's "update to latest", file sharing spec §2); with
297
+ * `after` (a version id), only versions delivered after it. Versions whose object is gone are
298
+ * skipped; at most {@link FILE_VERSIONS_MAX} are looked at. Null when none is available.
299
+ */
300
+ async latestAvailable(orgId, conversationId, viewer, sourcePath, opts = {}) {
301
+ await this.checkAccess(orgId, conversationId, viewer);
302
+ const rows = await this.db
303
+ .selectFrom("conversation_events")
304
+ .select(["payload", "seq"])
305
+ .where("conversation_id", "=", conversationId)
306
+ .where("type", "=", "artifact_created")
307
+ .where(sql `payload->>'sourcePath'`, "=", sourcePath)
308
+ .orderBy("seq", "desc")
309
+ .execute();
310
+ let candidates = rows.map((r) => r.payload);
311
+ if (opts.after !== undefined) {
312
+ const at = candidates.findIndex((d) => d.artifactId === opts.after);
313
+ if (at >= 0)
314
+ candidates = candidates.slice(0, at);
315
+ }
316
+ const store = this.storage.kernel(orgId);
317
+ for (const d of candidates.slice(0, FILE_VERSIONS_MAX)) {
318
+ if (await store.head(d.objectKey)) {
319
+ return {
320
+ id: d.artifactId,
321
+ name: d.name,
322
+ contentType: d.contentType,
323
+ size: d.size,
324
+ objectKey: d.objectKey,
325
+ };
326
+ }
327
+ }
328
+ return null;
329
+ }
330
+ /**
331
+ * The source paths and attachments the viewer has a share of in the conversation that is not
332
+ * revoked or expired ({@link FileOutput.shared}).
333
+ */
334
+ async viewerShares(conversationId, viewer) {
335
+ const rows = await this.db
336
+ .selectFrom("file_shares")
337
+ .select(["source_path", "file_id"])
338
+ .where("conversation_id", "=", conversationId)
339
+ .where("created_by", "=", viewer)
340
+ .where("revoked_at", "is", null)
341
+ .where((eb) => eb.or([eb("expires_at", "is", null), eb("expires_at", ">", sql `now()`)]))
342
+ .execute();
343
+ const paths = new Set();
344
+ const uploads = new Set();
345
+ for (const r of rows) {
346
+ if (r.source_path === null)
347
+ uploads.add(r.file_id);
348
+ else
349
+ paths.add(r.source_path);
350
+ }
351
+ return { paths, uploads };
352
+ }
276
353
  /**
277
354
  * The first `limit` bytes of a text file version (any version's id, or an attachment sent in the
278
355
  * conversation). Not text, or NUL bytes in
@@ -8,6 +8,7 @@ import type { ModelEmbeddings } from "../models/embeddings.js";
8
8
  import type { ModelImages } from "../models/images.js";
9
9
  import type { OrgRole } from "../orgs/roles.js";
10
10
  import type { HookRunner } from "../runtime/hook-calls.js";
11
+ import type { ShareLiveness } from "../shares/liveness.js";
11
12
  import type { EmbedTokens } from "../ui/embed-token.js";
12
13
  import { type UiActionHandler, type UiRender } from "../ui/registry.js";
13
14
  import { type BusSubscriber } from "./bus.js";
@@ -48,6 +49,12 @@ export interface KernelDeps {
48
49
  * construction); only a ctx built alone in a test passes `undefined` (no hooks fire).
49
50
  */
50
51
  hooks: HookRunner | undefined;
52
+ /**
53
+ * The live check of a share-scoped embed token (the one `ShareLiveness`, file sharing spec §7).
54
+ * A required key like `hooks`, so no builder drops it by omission; `undefined` (a ctx built alone
55
+ * in a test) verifies no share token (fail closed).
56
+ */
57
+ shares: Pick<ShareLiveness, "embedLive"> | undefined;
51
58
  runWorkers: boolean;
52
59
  /** 内核 logger(`debug` 可选:插件 Logger 没有它,测试可不给)。 */
53
60
  log: Logger & {
@@ -298,8 +298,10 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
298
298
  // extension is switched off, the member leaves or the account is disabled). The returned role is
299
299
  // the current one; a token whose current role is below the minRole of its contribution's slot is
300
300
  // refused (A38, UI slots spec §7). A platform token: the contribution is a `platform.page` and the
301
- // account is still an active super admin. A token of one scope never verifies for the other's
302
- // slots. Anything else is null.
301
+ // account is still an active super admin. A share token (file sharing spec §7): the contribution
302
+ // is a `file.preview` and the share is live at the token's generation in its org with this
303
+ // extension enabled there (`ShareLiveness.embedLive`); returned as is (no account, no role). A
304
+ // token of one scope never verifies for another's slots. Anything else is null.
303
305
  const verifyEmbedToken = async (token) => {
304
306
  const claims = embedTokens.verify(token, name);
305
307
  if (claims === null)
@@ -310,6 +312,11 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
310
312
  return null;
311
313
  return (await currentPlatformAccount(deps.db, claims.accountId)) ? claims : null;
312
314
  }
315
+ if (claims.scope === "share") {
316
+ if (slot?.id !== "file.preview" || deps.shares === undefined)
317
+ return null;
318
+ return (await deps.shares.embedLive(name, claims)) ? claims : null;
319
+ }
313
320
  if (claims.scope !== "org" || claims.orgId === undefined)
314
321
  return null;
315
322
  // the contribution's slot as loaded now: never `platform.page` through an org token, and the
@@ -1409,6 +1409,35 @@ export interface ScheduledTasksTable {
1409
1409
  updated_at: Ts;
1410
1410
  deleted_at: NullableTs;
1411
1411
  }
1412
+ /** Why a file share was revoked (0161). */
1413
+ export type FileShareRevokeReason = "creator" | "admin" | "conversation_deleted" | "member_offboarded" | "creator_lost_access";
1414
+ /**
1415
+ * 0161: a link to a frozen snapshot of one conversation file (file sharing spec §1). The row stays
1416
+ * after a revoke or expiry; `object_key` is null once the snapshot is freed.
1417
+ */
1418
+ export interface FileSharesTable {
1419
+ id: string;
1420
+ org_id: string;
1421
+ code: string;
1422
+ conversation_id: string;
1423
+ file_id: string;
1424
+ source_path: NullableText;
1425
+ created_by: string;
1426
+ audience: "internal" | "external";
1427
+ name: string;
1428
+ content_type: string;
1429
+ /** bigint: pg returns it as a string. */
1430
+ size: ColumnType<string, number | string, number | string>;
1431
+ object_key: NullableText;
1432
+ generation: ColumnType<number, number | undefined, number>;
1433
+ expires_at: NullableTs;
1434
+ revoked_at: NullableTs;
1435
+ revoked_by: NullableText;
1436
+ revoke_reason: ColumnType<FileShareRevokeReason | null, FileShareRevokeReason | null | undefined, FileShareRevokeReason | null>;
1437
+ last_opened_at: NullableTs;
1438
+ created_at: Ts;
1439
+ updated_at: Ts;
1440
+ }
1412
1441
  /** 0113: one tick (or trial run) of a scheduled task; unique per (task, tick) when not trial. */
1413
1442
  export interface ScheduledTaskRunsTable {
1414
1443
  id: string;
@@ -1615,6 +1644,7 @@ export interface KernelDatabase {
1615
1644
  scheduled_tasks: ScheduledTasksTable;
1616
1645
  scheduled_task_runs: ScheduledTaskRunsTable;
1617
1646
  scheduled_task_grants: ScheduledTaskGrantsTable;
1647
+ file_shares: FileSharesTable;
1618
1648
  skills: SkillsTable;
1619
1649
  skill_versions: SkillVersionsTable;
1620
1650
  skill_change_requests: SkillChangeRequestsTable;