@capybara-hq/kernel 0.1.0-rc.87 → 0.1.0-rc.88

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 (45) hide show
  1. package/dist/catalog/marketplaces.service.d.ts +1 -1
  2. package/dist/conversations/conversations.schemas.d.ts +2 -1
  3. package/dist/conversations/conversations.schemas.js +2 -1
  4. package/dist/ctx/create-ctx.d.ts +1 -1
  5. package/dist/ctx/create-ctx.js +11 -5
  6. package/dist/errors.d.ts +4 -0
  7. package/dist/errors.js +4 -0
  8. package/dist/files/files.module.d.ts +4 -1
  9. package/dist/files/files.module.js +6 -2
  10. package/dist/files/previewers.controller.d.ts +12 -0
  11. package/dist/files/previewers.controller.js +52 -0
  12. package/dist/files/previewers.d.ts +46 -3
  13. package/dist/files/previewers.js +107 -11
  14. package/dist/html/html-type.d.ts +2 -0
  15. package/dist/html/html-type.js +4 -0
  16. package/dist/http/plugin-route-access.js +1 -0
  17. package/dist/platform/exclusions.js +15 -0
  18. package/dist/platform/ops/skills.ops.d.ts +3 -1
  19. package/dist/platform/ops/skills.ops.js +30 -5
  20. package/dist/sandbox/device-services.d.ts +14 -4
  21. package/dist/sandbox/device-services.js +24 -7
  22. package/dist/sandbox/sandbox.service.d.ts +21 -0
  23. package/dist/sandbox/sandbox.service.js +76 -0
  24. package/dist/skills/skill-files.d.ts +91 -0
  25. package/dist/skills/skill-files.js +144 -0
  26. package/dist/skills/skills.controller.d.ts +23 -3
  27. package/dist/skills/skills.controller.js +74 -6
  28. package/dist/skills/skills.module.js +3 -0
  29. package/dist/skills/skills.schemas.d.ts +47 -0
  30. package/dist/skills/skills.schemas.js +67 -1
  31. package/dist/skills/skills.service.d.ts +28 -3
  32. package/dist/skills/skills.service.js +38 -34
  33. package/dist/tools/builtins/sandbox/deliver.d.ts +1 -0
  34. package/dist/tools/builtins/sandbox/deliver.js +7 -0
  35. package/dist/tools/builtins/skill-load.d.ts +8 -2
  36. package/dist/tools/builtins/skill-load.js +13 -4
  37. package/dist/ui/embed-token.d.ts +1 -1
  38. package/dist/ui/embed-token.js +43 -5
  39. package/dist/ui/ui.schemas.d.ts +3 -0
  40. package/dist/ui/ui.schemas.js +8 -0
  41. package/dist/ui/views.controller.d.ts +6 -4
  42. package/dist/ui/views.controller.js +22 -4
  43. package/dist/ui/views.d.ts +22 -1
  44. package/dist/ui/views.js +44 -1
  45. package/package.json +2 -2
@@ -208,7 +208,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
208
208
  /** The host versions (an entry's `minKernel` is judged against them). */
209
209
  export declare const HOST_VERSIONS: {
210
210
  readonly kernel: string;
211
- readonly sdk: "0.1.0-rc.70";
211
+ readonly sdk: "0.1.0-rc.71";
212
212
  };
213
213
  /** Whether this deployment satisfies the entry's `minKernel`. */
214
214
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -3,7 +3,8 @@ import type { RouteSchemas } from "../platform/route-schemas.js";
3
3
  /**
4
4
  * The download routes' answer form: `as=url` answers `{ url }` (the presigned location the 302
5
5
  * would send, never cached) so a page can hand a cookie-free URL to the system browser (a native
6
- * shell's `openExternal@1`). Shared by the attachment and the artifact download routes.
6
+ * shell's `openExternal@1`). Shared by the attachment and the artifact download routes and the
7
+ * skill file content route (there a presigned attachment URL of that file's object).
7
8
  */
8
9
  export declare const DOWNLOAD_AS: z.ZodEnum<{
9
10
  url: "url";
@@ -5,7 +5,8 @@ import { FILES_PAGE_MAX } from "./files.js";
5
5
  /**
6
6
  * The download routes' answer form: `as=url` answers `{ url }` (the presigned location the 302
7
7
  * would send, never cached) so a page can hand a cookie-free URL to the system browser (a native
8
- * shell's `openExternal@1`). Shared by the attachment and the artifact download routes.
8
+ * shell's `openExternal@1`). Shared by the attachment and the artifact download routes and the
9
+ * skill file content route (there a presigned attachment URL of that file's object).
9
10
  */
10
11
  export const DOWNLOAD_AS = z.enum(["url"]);
11
12
  /** Shared by the list and groups queries: title search, run activity and the archived list. */
@@ -8,7 +8,7 @@ import { RegistrationLedger } from "../extensions/ledger.js";
8
8
  import type { LockService } from "../infra/lock/lock.service.js";
9
9
  import type { ModelEmbeddings } from "../models/embeddings.js";
10
10
  import type { ModelImages } from "../models/images.js";
11
- import type { OrgRole } from "../orgs/roles.js";
11
+ import { type OrgRole } from "../orgs/roles.js";
12
12
  import type { HookRunner } from "../runtime/hook-calls.js";
13
13
  import type { DeviceReports } from "../sandbox/device-reports.js";
14
14
  import type { ShareLiveness } from "../shares/liveness.js";
@@ -7,6 +7,7 @@ import { enabledExtensionsQuery, isExtensionEnabled } from "../extensions/enable
7
7
  import { checkHookRegistration } from "../extensions/hooks.js";
8
8
  import { RegistrationLedger } from "../extensions/ledger.js";
9
9
  import { audit } from "../identity/audit.js";
10
+ import { can } from "../orgs/roles.js";
10
11
  import { PrefixedStorage } from "../storage/storage.service.js";
11
12
  import { canUseSlot, orgUiTopic, PLATFORM_UI_TOPIC, PluginUiRegistration, } from "../ui/registry.js";
12
13
  import { createBus } from "./bus.js";
@@ -407,11 +408,13 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
407
408
  // still a member (PG every time, never cached: tokens already issued stop working at once when the
408
409
  // extension is switched off, the member leaves or the account is disabled). The returned role is
409
410
  // the current one; a token whose current role is below the minRole of its contribution's slot is
410
- // refused (A38, UI slots spec §7). A platform token: the contribution is a `platform.page` and the
411
- // account is still an active super admin. A share token (file sharing spec §7): the contribution
412
- // is a `file.preview` and the share is live at the token's generation in its org with this
413
- // extension enabled there (`ShareLiveness.embedLive`); returned as is (no account, no role). A
414
- // token of one scope never verifies for another's slots. Anything else is null.
411
+ // refused (A38, UI slots spec §7), and a skill file's token also once the current role may no
412
+ // longer read skills (`skills.read`; the skill's visibility itself is not re-checked). A platform
413
+ // token: the contribution is a `platform.page` and the account is still an active super admin.
414
+ // A share token (file sharing spec §7): the contribution is a `file.preview` and the share is
415
+ // live at the token's generation in its org with this extension enabled there
416
+ // (`ShareLiveness.embedLive`); returned as is (no account, no role). A token of one scope never
417
+ // verifies for another's slots. Anything else is null.
415
418
  const verifyEmbedToken = async (token) => {
416
419
  const claims = embedTokens.verify(token, name);
417
420
  if (claims === null)
@@ -436,6 +439,9 @@ export function createExtensionContext(deps, manifest, deploymentConfig, extensi
436
439
  const role = await currentOrgRole(deps.db, name, claims.orgId, claims.accountId);
437
440
  if (role === undefined || !canUseSlot(slot, role))
438
441
  return null;
442
+ // a skill file's token: the current role must still read skills (the issuing route's check)
443
+ if (claims.skillFile !== undefined && !can(role, "skills.read"))
444
+ return null;
439
445
  return { ...claims, role };
440
446
  };
441
447
  /** Ids of the extension's `platform.page` contributions (their invalidate takes no orgId). */
package/dist/errors.d.ts CHANGED
@@ -565,6 +565,10 @@ export declare const ERROR_CODES: {
565
565
  /** An org admin may pause, resume and delete another person's task, never edit it. */
566
566
  readonly "schedule.forbidden": 403;
567
567
  readonly "skill.not_found": 404;
568
+ /** The skill's file routes: no such version of the skill, or no such path in that version. */
569
+ readonly "skill.file_not_found": 404;
570
+ /** A skill file's stored object is missing or no longer matches its manifest (size, sha256). */
571
+ readonly "skill.file_changed": 409;
568
572
  /** Also a skill neither the model nor a person could use (phase D: both invocation flags off). */
569
573
  readonly "skill.invalid_package": 400;
570
574
  /** An agent already has `AGENT_SKILLS_MAX` own skills. */
package/dist/errors.js CHANGED
@@ -565,6 +565,10 @@ export const ERROR_CODES = {
565
565
  /** An org admin may pause, resume and delete another person's task, never edit it. */
566
566
  "schedule.forbidden": 403,
567
567
  "skill.not_found": 404,
568
+ /** The skill's file routes: no such version of the skill, or no such path in that version. */
569
+ "skill.file_not_found": 404,
570
+ /** A skill file's stored object is missing or no longer matches its manifest (size, sha256). */
571
+ "skill.file_changed": 409,
568
572
  /** Also a skill neither the model nor a person could use (phase D: both invocation flags off). */
569
573
  "skill.invalid_package": 400,
570
574
  /** An agent already has `AGENT_SKILLS_MAX` own skills. */
@@ -1,3 +1,6 @@
1
- /** File previewers (`file-preview@1`): which previewers take a file, the org's order, rendering. */
1
+ /**
2
+ * File previewers (`file-preview@1`): which previewers take a file (a conversation file, a share's
3
+ * snapshot, a skill file), the org's order, rendering.
4
+ */
2
5
  export declare class FilesModule {
3
6
  }
@@ -7,14 +7,18 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
7
7
  import { Module } from "@nestjs/common";
8
8
  import { ConversationsModule } from "../conversations/conversations.module.js";
9
9
  import { ExtensionsModule } from "../extensions/extensions.module.js";
10
+ import { SkillsModule } from "../skills/skills.module.js";
10
11
  import { StorageModule } from "../storage/storage.module.js";
11
12
  import { PreviewerRegistry } from "./previewers.js";
12
- /** File previewers (`file-preview@1`): which previewers take a file, the org's order, rendering. */
13
+ /**
14
+ * File previewers (`file-preview@1`): which previewers take a file (a conversation file, a share's
15
+ * snapshot, a skill file), the org's order, rendering.
16
+ */
13
17
  let FilesModule = class FilesModule {
14
18
  };
15
19
  FilesModule = __decorate([
16
20
  Module({
17
- imports: [ExtensionsModule, ConversationsModule, StorageModule],
21
+ imports: [ExtensionsModule, ConversationsModule, SkillsModule, StorageModule],
18
22
  providers: [PreviewerRegistry],
19
23
  exports: [PreviewerRegistry],
20
24
  })
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { type Principal } from "../identity/principal.js";
3
3
  import { type OrgContext } from "../orgs/org.guard.js";
4
+ import { SkillFilePreviewersQuery, SkillFilePreviewParams, SkillFilePreviewQuery, SkillIdParams } from "../skills/skills.schemas.js";
4
5
  import { type OrgPreviewerItem, type PreviewerItem, PreviewerRegistry } from "./previewers.js";
5
6
  declare const PreviewQuery: z.ZodObject<{
6
7
  locale: z.ZodDefault<z.ZodEnum<{
@@ -29,6 +30,11 @@ declare const PreviewParams: z.ZodObject<{
29
30
  * render (10 s → 504 `ui.timeout`, throws → 502 `ui.render_failed`, invalid → 502
30
31
  * `ui.invalid_view`); an embed previewer gets its token from the ui embed-token route with
31
32
  * `{ conversationId, fileId }` and the file over the message bridge;
33
+ * - `GET /api/v1/orgs/:orgId/skills/:id/files/previewers?version=&path=` and
34
+ * `GET .../skills/:id/files/previews/:plugin/:previewerId?version=&path=&locale=` (`skills.read`,
35
+ * skill file browser spec): the same for one file of a skill version, visibility as
36
+ * `GET /skills/:id` (404 `skill.not_found`, `skill.file_not_found`; a changed object 409
37
+ * `skill.file_changed`); an embed previewer's token takes `{ skillId, version, path }`;
32
38
  * - `GET / PUT /api/v1/orgs/:orgId/file-previewers` (`org.extensions.manage`) → `{ items }`: the
33
39
  * org's order; PUT lists `{ plugin, id, disabled }` first-to-last, the rest follow.
34
40
  */
@@ -41,6 +47,12 @@ export declare class FilePreviewersController {
41
47
  preview(principal: Principal, org: OrgContext, id: string, fileId: string, { plugin, previewerId }: z.infer<typeof PreviewParams>, q: z.infer<typeof PreviewQuery>): Promise<{
42
48
  view: import("@capybara-hq/plugin-sdk").UiView;
43
49
  }>;
50
+ forSkillFile(principal: Principal, org: OrgContext, params: z.infer<typeof SkillIdParams>, q: z.infer<typeof SkillFilePreviewersQuery>): Promise<{
51
+ previewers: PreviewerItem[];
52
+ }>;
53
+ previewSkillFile(principal: Principal, org: OrgContext, params: z.infer<typeof SkillFilePreviewParams>, q: z.infer<typeof SkillFilePreviewQuery>): Promise<{
54
+ view: import("@capybara-hq/plugin-sdk").UiView;
55
+ }>;
44
56
  list(org: OrgContext): Promise<{
45
57
  items: OrgPreviewerItem[];
46
58
  }>;
@@ -13,6 +13,7 @@ import { CurrentPrincipal, requireUser } from "../identity/principal.js";
13
13
  import { createZodDto } from "../infra/validation/create-zod-dto.js";
14
14
  import { ZBody, ZParam, ZQuery } from "../infra/validation/zod-params.js";
15
15
  import { CurrentOrg, OrgAction } from "../orgs/org.guard.js";
16
+ import { SkillFilePreviewersQuery, SkillFilePreviewParams, SkillFilePreviewQuery, SkillIdParams, } from "../skills/skills.schemas.js";
16
17
  import { PreviewerRegistry } from "./previewers.js";
17
18
  import { FilePreviewersOrderBody } from "./previewers.schemas.js";
18
19
  const Id = z.string().min(1).max(100);
@@ -26,6 +27,14 @@ class FilePreviewParamsDto extends createZodDto(PreviewParams, "FilePreviewParam
26
27
  }
27
28
  class FilePreviewersOrderBodyDto extends createZodDto(OrderBody, "FilePreviewersOrderBody") {
28
29
  }
30
+ class SkillFilePreviewersParamsDto extends createZodDto(SkillIdParams, "SkillFilePreviewersParams") {
31
+ }
32
+ class SkillFilePreviewersQueryDto extends createZodDto(SkillFilePreviewersQuery, "SkillFilePreviewersQuery") {
33
+ }
34
+ class SkillFilePreviewParamsDto extends createZodDto(SkillFilePreviewParams, "SkillFilePreviewParams") {
35
+ }
36
+ class SkillFilePreviewQueryDto extends createZodDto(SkillFilePreviewQuery, "SkillFilePreviewQuery") {
37
+ }
29
38
  /**
30
39
  * `file-preview@1` (UI refresh B Task 11):
31
40
  * - `GET /api/v1/orgs/:orgId/conversations/:id/files/:fileId/previewers` → `{ previewers }`: the
@@ -35,6 +44,11 @@ class FilePreviewersOrderBodyDto extends createZodDto(OrderBody, "FilePreviewers
35
44
  * render (10 s → 504 `ui.timeout`, throws → 502 `ui.render_failed`, invalid → 502
36
45
  * `ui.invalid_view`); an embed previewer gets its token from the ui embed-token route with
37
46
  * `{ conversationId, fileId }` and the file over the message bridge;
47
+ * - `GET /api/v1/orgs/:orgId/skills/:id/files/previewers?version=&path=` and
48
+ * `GET .../skills/:id/files/previews/:plugin/:previewerId?version=&path=&locale=` (`skills.read`,
49
+ * skill file browser spec): the same for one file of a skill version, visibility as
50
+ * `GET /skills/:id` (404 `skill.not_found`, `skill.file_not_found`; a changed object 409
51
+ * `skill.file_changed`); an embed previewer's token takes `{ skillId, version, path }`;
38
52
  * - `GET / PUT /api/v1/orgs/:orgId/file-previewers` (`org.extensions.manage`) → `{ items }`: the
39
53
  * org's order; PUT lists `{ plugin, id, disabled }` first-to-last, the rest follow.
40
54
  */
@@ -60,6 +74,26 @@ let FilePreviewersController = class FilePreviewersController {
60
74
  });
61
75
  return { view };
62
76
  }
77
+ async forSkillFile(principal, org, params, q) {
78
+ requireUser(principal);
79
+ return {
80
+ previewers: await this.previewers.forSkillFile(org.orgId, params.id, q.version, q.path),
81
+ };
82
+ }
83
+ async previewSkillFile(principal, org, params, q) {
84
+ const p = requireUser(principal);
85
+ const view = await this.previewers.renderSkill({
86
+ orgId: org.orgId,
87
+ accountId: p.account.id,
88
+ skillId: params.id,
89
+ version: q.version,
90
+ path: q.path,
91
+ plugin: params.plugin,
92
+ id: params.previewerId,
93
+ locale: q.locale,
94
+ });
95
+ return { view };
96
+ }
63
97
  async list(org) {
64
98
  return { items: await this.previewers.list(org.orgId) };
65
99
  }
@@ -93,6 +127,24 @@ __decorate([
93
127
  __param(4, ZParam(FilePreviewParamsDto)),
94
128
  __param(5, ZQuery(FilePreviewQueryDto))
95
129
  ], FilePreviewersController.prototype, "preview", null);
130
+ __decorate([
131
+ Get("skills/:id/files/previewers"),
132
+ Header("cache-control", "private, no-store"),
133
+ OrgAction("skills.read"),
134
+ __param(0, CurrentPrincipal()),
135
+ __param(1, CurrentOrg()),
136
+ __param(2, ZParam(SkillFilePreviewersParamsDto)),
137
+ __param(3, ZQuery(SkillFilePreviewersQueryDto))
138
+ ], FilePreviewersController.prototype, "forSkillFile", null);
139
+ __decorate([
140
+ Get("skills/:id/files/previews/:plugin/:previewerId"),
141
+ Header("cache-control", "private, no-store"),
142
+ OrgAction("skills.read"),
143
+ __param(0, CurrentPrincipal()),
144
+ __param(1, CurrentOrg()),
145
+ __param(2, ZParam(SkillFilePreviewParamsDto)),
146
+ __param(3, ZQuery(SkillFilePreviewQueryDto))
147
+ ], FilePreviewersController.prototype, "previewSkillFile", null);
96
148
  __decorate([
97
149
  Get("file-previewers"),
98
150
  OrgAction("org.extensions.manage"),
@@ -4,6 +4,7 @@ import { EffectiveConfigs } from "../extensions/effective-config.js";
4
4
  import { ExtensionHost } from "../extensions/host.js";
5
5
  import { KernelDb } from "../infra/database/kernel-db.js";
6
6
  import { TransactionHost } from "../infra/database/transaction-host.js";
7
+ import { SkillFiles } from "../skills/skill-files.js";
7
8
  import { StorageService } from "../storage/storage.service.js";
8
9
  /** Time limit of a previewer's render (UI refresh spec §5.3: 10 s on the conversation page). */
9
10
  export declare const FILE_PREVIEW_TIMEOUT_MS = 10000;
@@ -46,14 +47,15 @@ export declare const FILE_PREVIEW_TIMEOUT: unique symbol;
46
47
  * (`capybara.file_previewers` rows first by position, then the rest in provider order; disabled ones
47
48
  * dropped; only extensions enabled in the org), and rendering a view previewer through a read grant
48
49
  * for that one file (valid only during the call, capped at the previewer's `maxBytes`; the extension
49
- * never gets a storage key or URL). Providers are validated when they are provided (`ctx.provide`).
50
- * No state across requests.
50
+ * never gets a storage key or URL). The file is a conversation file, a share's snapshot or a skill
51
+ * version's file (`SkillFiles`: visibility as `GET /skills/:id`, manifest paths only). Providers
52
+ * are validated when they are provided (`ctx.provide`). No state across requests.
51
53
  */
52
54
  export declare class PreviewerRegistry {
53
55
  readonly txHost: TransactionHost;
54
56
  private readonly timeoutMs;
55
57
  private readonly d;
56
- constructor(kdb: Pick<KernelDb, "db">, host: Pick<ExtensionHost, "list" | "enabledPlugins">, files: Pick<ConversationFiles, "file">, storage: Pick<StorageService, "kernel">, effective: Pick<EffectiveConfigs, "get">, log: Pick<Logger, "warn">, txHost: TransactionHost, timeoutMs?: number);
58
+ constructor(kdb: Pick<KernelDb, "db">, host: Pick<ExtensionHost, "list" | "enabledPlugins">, files: Pick<ConversationFiles, "file">, skillFiles: Pick<SkillFiles, "resolve" | "bytes">, storage: Pick<StorageService, "kernel">, effective: Pick<EffectiveConfigs, "get">, log: Pick<Logger, "warn">, txHost: TransactionHost, timeoutMs?: number);
57
59
  /** Every previewer loaded on this replica, in provider order (load order, then list order). */
58
60
  private loaded;
59
61
  /** The org's previewers (enabled extensions only) in its order, disabled ones included. */
@@ -122,6 +124,47 @@ export declare class PreviewerRegistry {
122
124
  shareEmbed(orgId: string, file: PreviewFile, plugin: string, previewerId: string): Promise<{
123
125
  contribution: string;
124
126
  } | null>;
127
+ /**
128
+ * The previewers that take file `path` of version `version` (default: current) of a skill, in
129
+ * the org's order (skill file browser spec). Visibility as `GET /skills/:id` (`skill.not_found`);
130
+ * a version or path not in the skill → `skill.file_not_found`; nothing is read.
131
+ */
132
+ forSkillFile(orgId: string, skillId: string, version: number | undefined, path: string): Promise<PreviewerItem[]>;
133
+ /**
134
+ * Renders a view previewer for a skill file: args `source: "skill"` with the viewer, the skill,
135
+ * the resolved version and the path (`file.id` is `<skillId>@<version>/<path>`). The file is read
136
+ * and checked against its manifest before the extension is called (a changed object is 409
137
+ * `skill.file_changed`, the extension is not called); the read grant hands those bytes, that one
138
+ * object only, during the call. The read and the render share one time limit (over it: 504
139
+ * `ui.timeout`). Not found and render errors as {@link render}.
140
+ */
141
+ renderSkill(t: {
142
+ orgId: string;
143
+ accountId: string;
144
+ skillId: string;
145
+ version: number | undefined;
146
+ path: string;
147
+ plugin: string;
148
+ id: string;
149
+ locale: "zh" | "en";
150
+ }): Promise<UiView>;
151
+ /**
152
+ * The skill file an embed token for a `file.preview` contribution may name: the file resolved as
153
+ * {@link forSkillFile} (its errors), and an enabled previewer of that extension with
154
+ * `embed: contribution` takes it; else null.
155
+ */
156
+ skillEmbed(t: {
157
+ orgId: string;
158
+ skillId: string;
159
+ version: number | undefined;
160
+ path: string;
161
+ plugin: string;
162
+ contribution: string;
163
+ }): Promise<{
164
+ skillId: string;
165
+ version: number;
166
+ path: string;
167
+ } | null>;
125
168
  /** The enabled view previewer that takes the file, else 404 `ui.not_found`. */
126
169
  private viewPreviewer;
127
170
  /**
@@ -15,16 +15,43 @@ import { ConversationFiles } from "../conversations/files.js";
15
15
  import { ApiError } from "../errors.js";
16
16
  import { EffectiveConfigs } from "../extensions/effective-config.js";
17
17
  import { ExtensionHost } from "../extensions/host.js";
18
+ import { isHtmlType, isSvgType } from "../html/html-type.js";
18
19
  import { audit } from "../identity/audit.js";
19
20
  import { KernelDb } from "../infra/database/kernel-db.js";
20
21
  import { TransactionHost } from "../infra/database/transaction-host.js";
21
22
  import { Transactional } from "../infra/database/transactional.decorator.js";
22
23
  import { KERNEL_LOGGER } from "../infra/tokens.js";
24
+ import { SkillFiles } from "../skills/skill-files.js";
23
25
  import { StorageService } from "../storage/storage.service.js";
24
26
  import { callExtension } from "../ui/call-extension.js";
25
27
  /** Time limit of a previewer's render (UI refresh spec §5.3: 10 s on the conversation page). */
26
28
  export const FILE_PREVIEW_TIMEOUT_MS = 10_000;
27
29
  const notFound = () => new ApiError("ui.not_found", "Previewer not found");
30
+ /** A skill file as a previewer sees it: its name is the last segment of its path. */
31
+ const skillPreviewFile = (f) => ({
32
+ name: f.path.slice(f.path.lastIndexOf("/") + 1),
33
+ contentType: f.contentType,
34
+ size: f.size,
35
+ });
36
+ /**
37
+ * A skill's HTML and SVG files show as source text only (skill file browser spec; the web's
38
+ * `skillFileSourceOnly`, the share routes refuse HTML likewise): no previewer, render or embed for
39
+ * them (404 `ui.not_found`).
40
+ */
41
+ const previewableSkillFile = (f) => {
42
+ const shown = skillPreviewFile(f);
43
+ if (isHtmlType(shown.name, shown.contentType) || isSvgType(shown.name, shown.contentType)) {
44
+ throw notFound();
45
+ }
46
+ return shown;
47
+ };
48
+ /** One chunk of bytes as a stream (what {@link PreviewerRegistry.renderWith}'s `open` returns). */
49
+ const streamOf = (bytes) => new ReadableStream({
50
+ start(c) {
51
+ c.enqueue(bytes);
52
+ c.close();
53
+ },
54
+ });
28
55
  const item = (l) => ({
29
56
  plugin: l.plugin,
30
57
  id: l.previewer.id,
@@ -66,14 +93,15 @@ export const FILE_PREVIEW_TIMEOUT = Symbol("FILE_PREVIEW_TIMEOUT");
66
93
  * (`capybara.file_previewers` rows first by position, then the rest in provider order; disabled ones
67
94
  * dropped; only extensions enabled in the org), and rendering a view previewer through a read grant
68
95
  * for that one file (valid only during the call, capped at the previewer's `maxBytes`; the extension
69
- * never gets a storage key or URL). Providers are validated when they are provided (`ctx.provide`).
70
- * No state across requests.
96
+ * never gets a storage key or URL). The file is a conversation file, a share's snapshot or a skill
97
+ * version's file (`SkillFiles`: visibility as `GET /skills/:id`, manifest paths only). Providers
98
+ * are validated when they are provided (`ctx.provide`). No state across requests.
71
99
  */
72
100
  let PreviewerRegistry = class PreviewerRegistry {
73
101
  txHost;
74
102
  timeoutMs;
75
103
  d;
76
- constructor(kdb, host, files, storage, effective, log, txHost, timeoutMs = FILE_PREVIEW_TIMEOUT_MS) {
104
+ constructor(kdb, host, files, skillFiles, storage, effective, log, txHost, timeoutMs = FILE_PREVIEW_TIMEOUT_MS) {
77
105
  this.txHost = txHost;
78
106
  this.timeoutMs = timeoutMs;
79
107
  this.d = {
@@ -83,6 +111,7 @@ let PreviewerRegistry = class PreviewerRegistry {
83
111
  host,
84
112
  enabledPlugins: (orgId) => host.enabledPlugins(orgId),
85
113
  files,
114
+ skillFiles,
86
115
  storage,
87
116
  effective,
88
117
  log,
@@ -282,6 +311,70 @@ let PreviewerRegistry = class PreviewerRegistry {
282
311
  const contribution = l?.previewer.embed;
283
312
  return contribution === undefined ? null : { contribution };
284
313
  }
314
+ /**
315
+ * The previewers that take file `path` of version `version` (default: current) of a skill, in
316
+ * the org's order (skill file browser spec). Visibility as `GET /skills/:id` (`skill.not_found`);
317
+ * a version or path not in the skill → `skill.file_not_found`; nothing is read.
318
+ */
319
+ async forSkillFile(orgId, skillId, version, path) {
320
+ const file = await this.d.skillFiles.resolve(orgId, skillId, version, path);
321
+ return (await this.accepting(orgId, previewableSkillFile(file))).map(item);
322
+ }
323
+ /**
324
+ * Renders a view previewer for a skill file: args `source: "skill"` with the viewer, the skill,
325
+ * the resolved version and the path (`file.id` is `<skillId>@<version>/<path>`). The file is read
326
+ * and checked against its manifest before the extension is called (a changed object is 409
327
+ * `skill.file_changed`, the extension is not called); the read grant hands those bytes, that one
328
+ * object only, during the call. The read and the render share one time limit (over it: 504
329
+ * `ui.timeout`). Not found and render errors as {@link render}.
330
+ */
331
+ async renderSkill(t) {
332
+ const file = await this.d.skillFiles.resolve(t.orgId, t.skillId, t.version, t.path);
333
+ const shown = previewableSkillFile(file);
334
+ const l = await this.viewPreviewer(t.orgId, shown, t.plugin, t.id);
335
+ // one deadline for the read and the render: the read uses part of the render's time limit
336
+ const deadline = Date.now() + this.timeoutMs;
337
+ const readTimeout = () => new ApiError("ui.timeout", `The skill file could not be read within ${this.timeoutMs / 1000}s`);
338
+ const signal = AbortSignal.timeout(this.timeoutMs);
339
+ let bytes;
340
+ try {
341
+ // the previewer takes the file only within its maxBytes, so this keeps the whole file
342
+ bytes = await this.d.skillFiles.bytes(file, { keepBytes: l.previewer.maxBytes, signal });
343
+ }
344
+ catch (err) {
345
+ if (!signal.aborted)
346
+ throw err;
347
+ this.d.log.warn("file preview read timed out", {
348
+ plugin: t.plugin,
349
+ previewer: t.id,
350
+ orgId: t.orgId,
351
+ timeoutMs: this.timeoutMs,
352
+ });
353
+ throw readTimeout();
354
+ }
355
+ const remaining = deadline - Date.now();
356
+ if (remaining <= 0)
357
+ throw readTimeout();
358
+ return this.renderWith(l, t, {
359
+ source: "skill",
360
+ orgId: t.orgId,
361
+ accountId: t.accountId,
362
+ skillId: t.skillId,
363
+ version: file.version,
364
+ path: file.path,
365
+ file: { id: `${t.skillId}@${file.version}/${file.path}`, ...shown },
366
+ }, async () => streamOf(bytes), remaining);
367
+ }
368
+ /**
369
+ * The skill file an embed token for a `file.preview` contribution may name: the file resolved as
370
+ * {@link forSkillFile} (its errors), and an enabled previewer of that extension with
371
+ * `embed: contribution` takes it; else null.
372
+ */
373
+ async skillEmbed(t) {
374
+ const file = await this.d.skillFiles.resolve(t.orgId, t.skillId, t.version, t.path);
375
+ const takes = (await this.accepting(t.orgId, previewableSkillFile(file))).some((l) => l.plugin === t.plugin && l.previewer.embed === t.contribution);
376
+ return takes ? { skillId: t.skillId, version: file.version, path: file.path } : null;
377
+ }
285
378
  /** The enabled view previewer that takes the file, else 404 `ui.not_found`. */
286
379
  async viewPreviewer(orgId, file, plugin, id) {
287
380
  const l = (await this.accepting(orgId, file)).find((x) => x.plugin === plugin && x.previewer.id === id);
@@ -293,7 +386,9 @@ let PreviewerRegistry = class PreviewerRegistry {
293
386
  * Calls a view previewer's render with a read grant over `open` (the file's bytes, capped at the
294
387
  * previewer's `maxBytes`, valid only during the call) and validates the view.
295
388
  */
296
- async renderWith(l, t, identity, open) {
389
+ async renderWith(l, t, identity, open,
390
+ /** The render's time limit (default the previewer limit; less when a read already used some). */
391
+ timeoutMs = this.timeoutMs) {
297
392
  const render = l.previewer.render;
298
393
  if (render === undefined)
299
394
  throw notFound();
@@ -311,7 +406,7 @@ let PreviewerRegistry = class PreviewerRegistry {
311
406
  plugin: t.plugin,
312
407
  what: "file preview",
313
408
  fields,
314
- timeoutMs: this.timeoutMs,
409
+ timeoutMs,
315
410
  failCode: "ui.render_failed",
316
411
  failMessage: `Plugin ${t.plugin} failed to preview the file with ${t.id}`,
317
412
  fn: (signal) => l.inflight.run(signal, async (s) => {
@@ -376,11 +471,12 @@ PreviewerRegistry = __decorate([
376
471
  __param(0, Inject(KernelDb)),
377
472
  __param(1, Inject(ExtensionHost)),
378
473
  __param(2, Inject(ConversationFiles)),
379
- __param(3, Inject(StorageService)),
380
- __param(4, Inject(EffectiveConfigs)),
381
- __param(5, Inject(KERNEL_LOGGER)),
382
- __param(6, Inject(TransactionHost)),
383
- __param(7, Optional()),
384
- __param(7, Inject(FILE_PREVIEW_TIMEOUT))
474
+ __param(3, Inject(SkillFiles)),
475
+ __param(4, Inject(StorageService)),
476
+ __param(5, Inject(EffectiveConfigs)),
477
+ __param(6, Inject(KERNEL_LOGGER)),
478
+ __param(7, Inject(TransactionHost)),
479
+ __param(8, Optional()),
480
+ __param(8, Inject(FILE_PREVIEW_TIMEOUT))
385
481
  ], PreviewerRegistry);
386
482
  export { PreviewerRegistry };
@@ -5,6 +5,8 @@
5
5
  */
6
6
  /** An HTML file: base type `text/html`, or a name ending in `.html` / `.htm` (any case). */
7
7
  export declare function isHtmlType(name: string, contentType: string): boolean;
8
+ /** An SVG image: base type `image/svg+xml`, or a name ending in `.svg` (any case). */
9
+ export declare function isSvgType(name: string, contentType: string): boolean;
8
10
  /**
9
11
  * `text/html; charset=<charset>`: the stored type's `charset` parameter (lower case, quotes
10
12
  * removed) when it is a valid token, else `utf-8`. The bytes are served as stored, so a file
@@ -14,6 +14,10 @@ export function isHtmlType(name, contentType) {
14
14
  const e = ext(name);
15
15
  return baseType(contentType) === "text/html" || e === "html" || e === "htm";
16
16
  }
17
+ /** An SVG image: base type `image/svg+xml`, or a name ending in `.svg` (any case). */
18
+ export function isSvgType(name, contentType) {
19
+ return baseType(contentType) === "image/svg+xml" || ext(name) === "svg";
20
+ }
17
21
  /** A charset name as a MIME token (IANA names: letters, digits and `-_.:+`), at most 40 chars. */
18
22
  const CHARSET_RE = /^[a-z0-9][a-z0-9._:+-]{0,39}$/;
19
23
  /**
@@ -134,6 +134,7 @@ let PluginRouteAccess = class PluginRouteAccess {
134
134
  role: claims.role,
135
135
  contribution: claims.contribution,
136
136
  ...(claims.conversationId !== undefined && { conversationId: claims.conversationId }),
137
+ ...(claims.skillFile !== undefined && { skillFile: claims.skillFile }),
137
138
  exp: claims.exp,
138
139
  config,
139
140
  };
@@ -575,6 +575,21 @@ export const PLATFORM_EXCLUSIONS = [
575
575
  reason: "Server-sent event stream of a conversation",
576
576
  },
577
577
  // skills
578
+ {
579
+ route: "GET /api/v1/orgs/:orgId/skills/:id/files/content",
580
+ category: "transport",
581
+ reason: "Serves a skill file's bytes for the web's preview; the Skill tool reads skill files for the model and skills.list-files lists them",
582
+ },
583
+ {
584
+ route: "GET /api/v1/orgs/:orgId/skills/:id/files/previewers",
585
+ category: "transport",
586
+ reason: "Previewer lookup feeding the skill page's file viewer",
587
+ },
588
+ {
589
+ route: "GET /api/v1/orgs/:orgId/skills/:id/files/previews/:plugin/:previewerId",
590
+ category: "transport",
591
+ reason: "Serves a rendered preview of a skill file",
592
+ },
578
593
  {
579
594
  route: "POST /api/v1/orgs/:orgId/skill-changes/:id/decide",
580
595
  category: "human-only",
@@ -2,6 +2,7 @@ import { type OnModuleInit } from "@nestjs/common";
2
2
  import { OwnedItems } from "../../catalog/owned-items.js";
3
3
  import { AttachmentsService } from "../../conversations/attachments.service.js";
4
4
  import { KernelDb } from "../../infra/database/kernel-db.js";
5
+ import { SkillFiles } from "../../skills/skill-files.js";
5
6
  import { SkillsService } from "../../skills/skills.service.js";
6
7
  import { PlatformOperations } from "../registry.js";
7
8
  /**
@@ -11,10 +12,11 @@ import { PlatformOperations } from "../registry.js";
11
12
  export declare class SkillsOperations implements OnModuleInit {
12
13
  private readonly registry;
13
14
  private readonly skills;
15
+ private readonly files;
14
16
  private readonly owned;
15
17
  private readonly attachments;
16
18
  private readonly db;
17
- constructor(registry: PlatformOperations, skills: SkillsService, owned: OwnedItems, attachments: AttachmentsService, db: KernelDb);
19
+ constructor(registry: PlatformOperations, skills: SkillsService, files: SkillFiles, owned: OwnedItems, attachments: AttachmentsService, db: KernelDb);
18
20
  /** The skill's name for a card summary; its id when it cannot be read. */
19
21
  private skillName;
20
22
  onModuleInit(): void;