@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
@@ -13,7 +13,8 @@ import { OwnedItems } from "../../catalog/owned-items.js";
13
13
  import { AttachmentsService, SKILL_PACKAGE_CONTENT_TYPE, SKILL_PACKAGE_UPLOAD_MAX_BYTES, } from "../../conversations/attachments.service.js";
14
14
  import { assertCustomAllowed } from "../../identity/settings.js";
15
15
  import { KernelDb } from "../../infra/database/kernel-db.js";
16
- import { SkillCreateBody, SkillIdParams, SkillPathParams, SkillShareableSchema, } from "../../skills/skills.schemas.js";
16
+ import { SkillFiles } from "../../skills/skill-files.js";
17
+ import { SkillCreateBody, SkillFilesQuery, SkillIdParams, SkillPathParams, SkillShareableSchema, } from "../../skills/skills.schemas.js";
17
18
  import { SkillsService } from "../../skills/skills.service.js";
18
19
  import { FileRefSchema } from "../file-ref.js";
19
20
  import { defineOperation } from "../operation.js";
@@ -30,12 +31,14 @@ const OwnedSkillId = z.object({ skillId: SkillIdParams.shape.id }).strict();
30
31
  let SkillsOperations = class SkillsOperations {
31
32
  registry;
32
33
  skills;
34
+ files;
33
35
  owned;
34
36
  attachments;
35
37
  db;
36
- constructor(registry, skills, owned, attachments, db) {
38
+ constructor(registry, skills, files, owned, attachments, db) {
37
39
  this.registry = registry;
38
40
  this.skills = skills;
41
+ this.files = files;
39
42
  this.owned = owned;
40
43
  this.attachments = attachments;
41
44
  this.db = db;
@@ -67,6 +70,27 @@ let SkillsOperations = class SkillsOperations {
67
70
  confirm: "read",
68
71
  run: async (input, ctx) => this.skills.get(ctx.orgId, input.skillId),
69
72
  }),
73
+ defineOperation({
74
+ id: "skills.list-files",
75
+ description: "List the files of one version of a skill: path, size, content type and the built-in preview kind (image, text or null). Takes the skill id from skills.list and an optional version (default: the current one; skills.get lists the versions). The model reads a skill's files through the Skill tool; this listing is for telling the person what a version holds.",
76
+ input: OwnedSkillId.extend({ version: SkillFilesQuery.shape.version }).strict(),
77
+ example: { skillId: "0b9f2c4e-1d3a-4c55-9e0a-7a2f6d1c8b11" },
78
+ authz: { orgAction: "skills.read" },
79
+ mirrors: ["GET /api/v1/orgs/:orgId/skills/:id/files"],
80
+ renames: { skillId: "id" },
81
+ errors: [
82
+ {
83
+ code: "skill.not_found",
84
+ next: "Check the skill id with skills.list: only the org's skills and platform skills switched on in it can be read.",
85
+ },
86
+ {
87
+ code: "skill.file_not_found",
88
+ next: "The skill has no such version; read its versions with skills.get, or leave version out for the current one.",
89
+ },
90
+ ],
91
+ confirm: "read",
92
+ run: async (input, ctx) => this.files.list(ctx.orgId, input.skillId, input.version),
93
+ }),
70
94
  defineOperation({
71
95
  id: "skills.create-from-file",
72
96
  description: "Create an org skill from a skill package, or add the next version of the org skill with the same name (org admins): a zip file of this conversation (an attachment, or a zip you built in the sandbox and delivered with Deliver), passed as file: { fileId }. The zip has SKILL.md at its root or in one top-level folder (frontmatter name and description, then the instructions), plus any scripts or references, at most 50 MiB. Every agent of the org has the skill unless it turns it off; shareable lets other orgs use it. The person sees the file on the card.",
@@ -247,8 +271,9 @@ SkillsOperations = __decorate([
247
271
  Injectable(),
248
272
  __param(0, Inject(PlatformOperations)),
249
273
  __param(1, Inject(SkillsService)),
250
- __param(2, Inject(OwnedItems)),
251
- __param(3, Inject(AttachmentsService)),
252
- __param(4, Inject(KernelDb))
274
+ __param(2, Inject(SkillFiles)),
275
+ __param(3, Inject(OwnedItems)),
276
+ __param(4, Inject(AttachmentsService)),
277
+ __param(5, Inject(KernelDb))
253
278
  ], SkillsOperations);
254
279
  export { SkillsOperations };
@@ -1,6 +1,8 @@
1
1
  import { type DeviceServiceSpec, type DeviceServiceStatus } from "@capybara-hq/plugin-sdk";
2
2
  import { SandboxService } from "./sandbox.service.js";
3
3
  import type { SandboxUseContext } from "./use-context.js";
4
+ /** The budget of the `ifRunning` ensure after a refresh applied new limits (a service restart). */
5
+ export declare const POST_APPLY_ENSURE_TIMEOUT_MS = 30000;
4
6
  /**
5
7
  * Device services (browser use spec §5): one long-lived named process per device, started on an
6
8
  * extension's behalf in the device's own sandbox with its own state directory, reached by
@@ -23,12 +25,20 @@ export declare class DeviceServices {
23
25
  ifRunning?: boolean;
24
26
  }): Promise<DeviceServiceStatus>;
25
27
  /**
26
- * Applies the device's current limits to the service again when it runs (an `ifRunning`
27
- * ensure; the device's allowlist changed); nothing when the instance or the service is not
28
- * running, and it never resumes or starts anything. The status, or null without a running
29
- * instance.
28
+ * Applies the device's current limits to the service when it runs (the device's allowlist
29
+ * changed outside a tool call). An `ifRunning` ensure first: a stopped service needs nothing
30
+ * now (the next use applies the limits), so it answers that status and the instance is left as
31
+ * it is. A running one: the limits go to the running instance as a use's exclusive step applies
32
+ * them ({@link SandboxService.applyLimitsIfRunning}: the provider's `update`, or a recreate on
33
+ * the kept files, which ends the services with the old instance); once applied, a second
34
+ * `ifRunning` ensure on the instance as it is recorded now, on its own budget
35
+ * ({@link POST_APPLY_ENSURE_TIMEOUT_MS}, not `signal`: a provider that restarts a service on a
36
+ * network change does it there). It never resumes or starts anything. The status, or null
37
+ * without a running instance.
30
38
  */
31
39
  refresh(use: SandboxUseContext, name: string, signal: AbortSignal): Promise<DeviceServiceStatus | null>;
40
+ /** An `ifRunning` ensure on the instance recorded now; null without a running instance. */
41
+ private ifRunningEnsure;
32
42
  /** One request to the service's socket; resolves its answer (throws when it is not running). */
33
43
  request(use: SandboxUseContext, name: string, body: Uint8Array, timeoutMs: number, signal: AbortSignal): Promise<Uint8Array>;
34
44
  /**
@@ -10,6 +10,8 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { DEVICE_SERVICE_NAME_RE, DeviceAccessError, } from "@capybara-hq/plugin-sdk";
11
11
  import { Inject, Injectable } from "@nestjs/common";
12
12
  import { SandboxService } from "./sandbox.service.js";
13
+ /** The budget of the `ifRunning` ensure after a refresh applied new limits (a service restart). */
14
+ export const POST_APPLY_ENSURE_TIMEOUT_MS = 30_000;
13
15
  /**
14
16
  * Device services (browser use spec §5): one long-lived named process per device, started on an
15
17
  * extension's behalf in the device's own sandbox with its own state directory, reached by
@@ -39,21 +41,36 @@ let DeviceServices = class DeviceServices {
39
41
  : p.ensureService(h, spec, sig), signal);
40
42
  }
41
43
  /**
42
- * Applies the device's current limits to the service again when it runs (an `ifRunning`
43
- * ensure; the device's allowlist changed); nothing when the instance or the service is not
44
- * running, and it never resumes or starts anything. The status, or null without a running
45
- * instance.
44
+ * Applies the device's current limits to the service when it runs (the device's allowlist
45
+ * changed outside a tool call). An `ifRunning` ensure first: a stopped service needs nothing
46
+ * now (the next use applies the limits), so it answers that status and the instance is left as
47
+ * it is. A running one: the limits go to the running instance as a use's exclusive step applies
48
+ * them ({@link SandboxService.applyLimitsIfRunning}: the provider's `update`, or a recreate on
49
+ * the kept files, which ends the services with the old instance); once applied, a second
50
+ * `ifRunning` ensure on the instance as it is recorded now, on its own budget
51
+ * ({@link POST_APPLY_ENSURE_TIMEOUT_MS}, not `signal`: a provider that restarts a service on a
52
+ * network change does it there). It never resumes or starts anything. The status, or null
53
+ * without a running instance.
46
54
  */
47
55
  async refresh(use, name, signal) {
48
56
  assertServiceName(name);
57
+ const found = await this.ifRunningEnsure(use, name, signal);
58
+ if (found === null || found.state !== "running")
59
+ return found;
60
+ if ((await this.sandbox.applyLimitsIfRunning(use, signal)) !== "applied")
61
+ return found;
62
+ // its own budget, never what the wait left of the caller's: a provider restarts the service
63
+ // on the new network here (device-local), so a spent caller signal must not skip it
64
+ return this.ifRunningEnsure(use, name, AbortSignal.timeout(POST_APPLY_ENSURE_TIMEOUT_MS));
65
+ }
66
+ /** An `ifRunning` ensure on the instance recorded now; null without a running instance. */
67
+ async ifRunningEnsure(use, name, signal) {
49
68
  const current = await this.sandbox.currentInstance(use.deviceId);
50
69
  if (!current)
51
70
  return null;
52
71
  const r = await this.sandbox.ifRunning(use.deviceId, { createdAt: current.createdAt }, async (p, h, sig) => {
53
72
  requireServices(p);
54
- return p.ensureService(h, nameOnlySpec(name), sig, {
55
- ifRunning: true,
56
- });
73
+ return p.ensureService(h, nameOnlySpec(name), sig, { ifRunning: true });
57
74
  }, signal);
58
75
  return r.kind === "ran" ? r.value : null;
59
76
  }
@@ -549,6 +549,27 @@ export declare class SandboxService {
549
549
  * in it; what the start caused is kept for the holder's next use to tell (as a silent use).
550
550
  */
551
551
  ensureRunning(use: SandboxUseContext, signal: AbortSignal): Promise<void>;
552
+ /**
553
+ * Applies the device's current limits to its running instance now, as the exclusive step of a
554
+ * use does ({@link ensure}: the fence moves, then {@link applyLimits}, the provider's `update`
555
+ * or a recreate on the kept files), without waiting for the next use: a device allowlist written
556
+ * outside a tool call (the panel's allow, browser use spec §7) reaches the running services. It
557
+ * never creates, resumes or rebuilds an instance: without a running one (none, suspended, being
558
+ * created or destroyed, files lost) there is nothing to apply and the next use's resume applies
559
+ * the limits. Nothing is done when the limits already apply (no lease is taken, so open viewers
560
+ * stay), or while the device carries a retirement obligation (only a use's gate settles it).
561
+ *
562
+ * The exclusive lease is taken with intent. Only the wait is bounded by `signal` and by
563
+ * `sandbox.lockWaitSeconds` (`sandbox.busy` after that: a tool call holding the device keeps
564
+ * it, and the next use applies the limits); an abort there reaches no provider. The apply under
565
+ * the lease has its own budget (the lifecycle steps' {@link SWEEP_OP_TIMEOUT_MS} and the lease's
566
+ * signal), never what is left of the caller's, so a long wait does not cut an `update` or a
567
+ * recreate short. Taking the lease ends the device's stream holds (ruling R7), so viewers
568
+ * reconnect to the service as it runs afterwards. A device deleted meanwhile is left alone.
569
+ * `applied` with the instance now recorded (a new one after a recreate), `unchanged` when
570
+ * nothing had to be applied, `not_running` without a running instance.
571
+ */
572
+ applyLimitsIfRunning(use: SandboxUseContext, signal: AbortSignal): Promise<"applied" | "unchanged" | "not_running">;
552
573
  /**
553
574
  * A run start's kernel read of the bound project (permission activation L2, Hook 1): the use
554
575
  * a tool call's would be (the instance made or resumed, the read silent for the holder), whose
@@ -988,6 +988,82 @@ let SandboxService = class SandboxService {
988
988
  await this.leave(use.deviceId, e);
989
989
  }
990
990
  }
991
+ /**
992
+ * Applies the device's current limits to its running instance now, as the exclusive step of a
993
+ * use does ({@link ensure}: the fence moves, then {@link applyLimits}, the provider's `update`
994
+ * or a recreate on the kept files), without waiting for the next use: a device allowlist written
995
+ * outside a tool call (the panel's allow, browser use spec §7) reaches the running services. It
996
+ * never creates, resumes or rebuilds an instance: without a running one (none, suspended, being
997
+ * created or destroyed, files lost) there is nothing to apply and the next use's resume applies
998
+ * the limits. Nothing is done when the limits already apply (no lease is taken, so open viewers
999
+ * stay), or while the device carries a retirement obligation (only a use's gate settles it).
1000
+ *
1001
+ * The exclusive lease is taken with intent. Only the wait is bounded by `signal` and by
1002
+ * `sandbox.lockWaitSeconds` (`sandbox.busy` after that: a tool call holding the device keeps
1003
+ * it, and the next use applies the limits); an abort there reaches no provider. The apply under
1004
+ * the lease has its own budget (the lifecycle steps' {@link SWEEP_OP_TIMEOUT_MS} and the lease's
1005
+ * signal), never what is left of the caller's, so a long wait does not cut an `update` or a
1006
+ * recreate short. Taking the lease ends the device's stream holds (ruling R7), so viewers
1007
+ * reconnect to the service as it runs afterwards. A device deleted meanwhile is left alone.
1008
+ * `applied` with the instance now recorded (a new one after a recreate), `unchanged` when
1009
+ * nothing had to be applied, `not_running` without a running instance.
1010
+ */
1011
+ async applyLimitsIfRunning(use, signal) {
1012
+ const p = await this.require(use.deviceId, use.orgId);
1013
+ const env = use.deviceId;
1014
+ // a first look without a lease: nothing to apply leaves the device and its viewers alone
1015
+ const before = await this.readRow(use);
1016
+ if (!this.usable(before, p, null))
1017
+ return "not_running";
1018
+ if (!this.mustApply(before, p, await this.wantedLimits(use)))
1019
+ return "unchanged";
1020
+ if (await this.retirement.hasUnresolved(env))
1021
+ return "unchanged";
1022
+ const lease = await this.leases.acquireExclusive(env, signal, this.config.get().sandbox.lockWaitSeconds * 1000, { intent: true });
1023
+ try {
1024
+ // the apply's own budget: the caller's signal bounded only the wait (an abort mid-update
1025
+ // would quarantine the instance, one mid-recreate would leave it `creating`)
1026
+ const sig = AbortSignal.any([AbortSignal.timeout(SWEEP_OP_TIMEOUT_MS), lease.signal]);
1027
+ // under the lease the B1 snapshot writer needs: no limits change on a device carrying the
1028
+ // reconcile marker (B-11)
1029
+ await this.facts.assertCloudReconciled(use.orgId, env);
1030
+ // under the lease, as `ensure` checks: a device deleted while this waited gets nothing
1031
+ // recreated on it
1032
+ const live = await this.db
1033
+ .selectFrom("devices")
1034
+ .select("id")
1035
+ .where("id", "=", env)
1036
+ .where("org_id", "=", use.orgId)
1037
+ .where("deleted_at", "is", null)
1038
+ .executeTakeFirst();
1039
+ if (!live)
1040
+ return "not_running";
1041
+ // read again under the lease: another holder may have applied, suspended or replaced it
1042
+ const row = await this.readRow(use);
1043
+ if (!this.usable(row, p, null))
1044
+ return "not_running";
1045
+ if (await this.retirement.hasUnresolved(env))
1046
+ return "unchanged";
1047
+ const fence = { gen: row.generation };
1048
+ // every acquisition first does a fenced increment, so a holder whose lease ended unnoticed
1049
+ // fails its next write; the provider calls below carry this holder's token
1050
+ await this.fenced(lease, env, fence, {});
1051
+ const want = await this.wantedLimits(use);
1052
+ const must = this.mustApply(row, p, want);
1053
+ const installed = !must && (await this.installedNetworkWider(env, p, row, row.handle, sig, want));
1054
+ if (installed && sig.aborted)
1055
+ throw abortReason(sig);
1056
+ if (!must && !installed)
1057
+ return "unchanged";
1058
+ const created = await this.applyLimits(use, p, lease, row, row.handle, fence, sig, want, installed);
1059
+ // B-15: evidence recorded for the old limits or the old instance is read again
1060
+ await this.refreshCloudSupport(use, p, created ?? { handle: row.handle, createdAt: row.created_at.getTime() }, sig, false);
1061
+ return "applied";
1062
+ }
1063
+ finally {
1064
+ await lease.release();
1065
+ }
1066
+ }
991
1067
  /**
992
1068
  * A run start's kernel read of the bound project (permission activation L2, Hook 1): the use
993
1069
  * a tool call's would be (the instance made or resumed, the read silent for the holder), whose
@@ -0,0 +1,91 @@
1
+ import type { ObjectStore } from "@capybara-hq/plugin-sdk";
2
+ import { type FileOutput } from "../conversations/files.js";
3
+ import { StorageService } from "../storage/storage.service.js";
4
+ import { SkillsService } from "./skills.service.js";
5
+ /** One file of a skill version, as `GET /skills/:id/files` lists it. */
6
+ export interface SkillFileEntry {
7
+ path: string;
8
+ size: number;
9
+ /** By the file's extension (the kernel's lookup; unknown: `application/octet-stream`). */
10
+ contentType: string;
11
+ /** The built-in preview kind, the rule of the conversation file list. */
12
+ previewable: FileOutput["previewable"];
13
+ }
14
+ /** `GET /skills/:id/files`: the files of one version of the skill. */
15
+ export interface SkillFileList {
16
+ version: number;
17
+ files: SkillFileEntry[];
18
+ }
19
+ /**
20
+ * A skill file resolved for a read (kernel-internal: the store and key never reach a client or an
21
+ * extension). Read it with {@link SkillFiles.read}, which checks size and sha256.
22
+ */
23
+ export interface ResolvedSkillFile {
24
+ store: ObjectStore;
25
+ key: string;
26
+ path: string;
27
+ version: number;
28
+ size: number;
29
+ sha256: string;
30
+ contentType: string;
31
+ }
32
+ /** The bytes of a skill file, at most the asked limit. */
33
+ export interface SkillFileBytes {
34
+ file: ResolvedSkillFile;
35
+ body: Buffer;
36
+ /** The file is longer than `body`. */
37
+ truncated: boolean;
38
+ }
39
+ /**
40
+ * The content type a skill file is sent with: its own for an inline raster image, `text/plain`
41
+ * for text and code, `application/octet-stream` otherwise (never `text/html` or `image/svg+xml`).
42
+ */
43
+ export declare function skillFileSentType(contentType: string, inline: boolean): string;
44
+ /** The last segment of a skill file's path (its download name). */
45
+ export declare const skillFileName: (path: string) => string;
46
+ /**
47
+ * Read-only access to a skill version's files (skill file browser spec, "Kernel"). The skill is
48
+ * the one `GET /skills/:id` shows the org ({@link SkillsService.resolve}: its own skill, or a
49
+ * platform skill on in the org; otherwise `skill.not_found`). A file is addressed only by a path of
50
+ * that version's manifest, so no storage key is ever built from input; an unknown version or path
51
+ * is `skill.file_not_found`. Every read checks the object against the manifest (size, sha256, as
52
+ * the Skill tool does): missing or different is 409 `skill.file_changed`.
53
+ */
54
+ export declare class SkillFiles {
55
+ private readonly skills;
56
+ private readonly storage;
57
+ constructor(skills: SkillsService, storage: StorageService);
58
+ /** The files of version `version` of the skill (default: its current version). */
59
+ list(orgId: string, skillId: string, version?: number): Promise<SkillFileList>;
60
+ /**
61
+ * Where file `path` of version `version` (default: current) of the skill lives, with its manifest
62
+ * size and sha256. Visibility as {@link list}; an unknown version or a path not in the manifest →
63
+ * `skill.file_not_found` (nothing is read).
64
+ */
65
+ resolve(orgId: string, skillId: string, version: number | undefined, path: string): Promise<ResolvedSkillFile>;
66
+ /**
67
+ * The bytes of a skill file, verified against its manifest entry (409 `skill.file_changed` when
68
+ * the object is missing or differs), cut to `limit` bytes when given (a text file is never cut
69
+ * inside a UTF-8 character). The whole object is hashed; only `limit` bytes are kept in memory.
70
+ */
71
+ read(orgId: string, skillId: string, version: number | undefined, path: string, limit?: number): Promise<SkillFileBytes>;
72
+ /**
73
+ * A short-lived presigned download URL for a skill file (ruling R3: a native shell's Download
74
+ * hands it to the system browser, as conversation files do). The object is checked against its
75
+ * manifest first (409 `skill.file_changed`); the URL is for that one object, always an
76
+ * attachment, with the type {@link skillFileSentType} gives and the last path segment as its
77
+ * name. It reaches the browser only, never an extension.
78
+ */
79
+ downloadUrl(orgId: string, skillId: string, version: number | undefined, path: string): Promise<{
80
+ url: string;
81
+ }>;
82
+ /**
83
+ * The verified bytes of a resolved file (the whole object hashed against the manifest; 409
84
+ * `skill.file_changed` when it is missing or differs), at most `keepBytes` of them.
85
+ */
86
+ bytes(file: ResolvedSkillFile, opts?: {
87
+ keepBytes?: number;
88
+ signal?: AbortSignal;
89
+ }): Promise<Uint8Array>;
90
+ private version;
91
+ }
@@ -0,0 +1,144 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { Inject, Injectable } from "@nestjs/common";
11
+ import { ARTIFACT_DOWNLOAD_TTL_SECONDS, isInlineArtifactType, isTextArtifactType, } from "../conversations/artifacts.js";
12
+ import { previewKind, trimUtf8 } from "../conversations/files.js";
13
+ import { ApiError } from "../errors.js";
14
+ import { StorageService } from "../storage/storage.service.js";
15
+ import { contentTypeFor } from "../tools/builtins/sandbox/deliver.js";
16
+ import { readSkillFile, SkillIntegrityError } from "../tools/builtins/skill-load.js";
17
+ import { SkillsService } from "./skills.service.js";
18
+ import { skillFileStore } from "./usable.js";
19
+ /**
20
+ * The content type a skill file is sent with: its own for an inline raster image, `text/plain`
21
+ * for text and code, `application/octet-stream` otherwise (never `text/html` or `image/svg+xml`).
22
+ */
23
+ export function skillFileSentType(contentType, inline) {
24
+ if (inline && isInlineArtifactType(contentType))
25
+ return contentType;
26
+ return isTextArtifactType(contentType) ? "text/plain; charset=utf-8" : "application/octet-stream";
27
+ }
28
+ /** The last segment of a skill file's path (its download name). */
29
+ export const skillFileName = (path) => path.slice(path.lastIndexOf("/") + 1);
30
+ const fileNotFound = () => new ApiError("skill.file_not_found", "Skill file not found");
31
+ /** Whether `path` could never be a manifest path (absolute, `.` / `..` / empty segments). */
32
+ const unsafePath = (path) => path.startsWith("/") ||
33
+ path.includes("\\") ||
34
+ path.split("/").some((seg) => seg === "" || seg === "." || seg === "..");
35
+ /**
36
+ * Read-only access to a skill version's files (skill file browser spec, "Kernel"). The skill is
37
+ * the one `GET /skills/:id` shows the org ({@link SkillsService.resolve}: its own skill, or a
38
+ * platform skill on in the org; otherwise `skill.not_found`). A file is addressed only by a path of
39
+ * that version's manifest, so no storage key is ever built from input; an unknown version or path
40
+ * is `skill.file_not_found`. Every read checks the object against the manifest (size, sha256, as
41
+ * the Skill tool does): missing or different is 409 `skill.file_changed`.
42
+ */
43
+ let SkillFiles = class SkillFiles {
44
+ skills;
45
+ storage;
46
+ constructor(skills, storage) {
47
+ this.skills = skills;
48
+ this.storage = storage;
49
+ }
50
+ /** The files of version `version` of the skill (default: its current version). */
51
+ async list(orgId, skillId, version) {
52
+ const v = await this.version(orgId, skillId, version);
53
+ return {
54
+ version: v.version,
55
+ files: v.manifest.files.map((f) => {
56
+ const contentType = contentTypeFor(f.path);
57
+ return { path: f.path, size: f.size, contentType, previewable: previewKind(contentType) };
58
+ }),
59
+ };
60
+ }
61
+ /**
62
+ * Where file `path` of version `version` (default: current) of the skill lives, with its manifest
63
+ * size and sha256. Visibility as {@link list}; an unknown version or a path not in the manifest →
64
+ * `skill.file_not_found` (nothing is read).
65
+ */
66
+ async resolve(orgId, skillId, version, path) {
67
+ const v = await this.version(orgId, skillId, version);
68
+ // only an exact manifest path; the shape check is a second guard, manifests never hold such
69
+ const entry = unsafePath(path) ? undefined : v.manifest.files.find((f) => f.path === path);
70
+ if (!entry)
71
+ throw fileNotFound();
72
+ const { store, prefix } = skillFileStore(this.storage, orgId, v.object_prefix);
73
+ return {
74
+ store,
75
+ key: `${prefix}${entry.path}`,
76
+ path: entry.path,
77
+ version: v.version,
78
+ size: entry.size,
79
+ sha256: entry.sha256,
80
+ contentType: contentTypeFor(entry.path),
81
+ };
82
+ }
83
+ /**
84
+ * The bytes of a skill file, verified against its manifest entry (409 `skill.file_changed` when
85
+ * the object is missing or differs), cut to `limit` bytes when given (a text file is never cut
86
+ * inside a UTF-8 character). The whole object is hashed; only `limit` bytes are kept in memory.
87
+ */
88
+ async read(orgId, skillId, version, path, limit) {
89
+ const file = await this.resolve(orgId, skillId, version, path);
90
+ const bytes = await this.bytes(file, limit !== undefined ? { keepBytes: limit } : {});
91
+ let body = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
92
+ const truncated = body.byteLength < file.size;
93
+ if (truncated && isTextArtifactType(file.contentType))
94
+ body = trimUtf8(body);
95
+ return { file, body, truncated };
96
+ }
97
+ /**
98
+ * A short-lived presigned download URL for a skill file (ruling R3: a native shell's Download
99
+ * hands it to the system browser, as conversation files do). The object is checked against its
100
+ * manifest first (409 `skill.file_changed`); the URL is for that one object, always an
101
+ * attachment, with the type {@link skillFileSentType} gives and the last path segment as its
102
+ * name. It reaches the browser only, never an extension.
103
+ */
104
+ async downloadUrl(orgId, skillId, version, path) {
105
+ const file = await this.resolve(orgId, skillId, version, path);
106
+ await this.bytes(file, { keepBytes: 0 });
107
+ const url = await file.store.presignGet(file.key, {
108
+ ttlSeconds: ARTIFACT_DOWNLOAD_TTL_SECONDS,
109
+ downloadName: skillFileName(file.path),
110
+ disposition: "attachment",
111
+ responseContentType: skillFileSentType(file.contentType, false),
112
+ });
113
+ return { url };
114
+ }
115
+ /**
116
+ * The verified bytes of a resolved file (the whole object hashed against the manifest; 409
117
+ * `skill.file_changed` when it is missing or differs), at most `keepBytes` of them.
118
+ */
119
+ async bytes(file, opts = {}) {
120
+ try {
121
+ return await readSkillFile(file.store, file.key, { path: file.path, size: file.size, sha256: file.sha256 }, opts);
122
+ }
123
+ catch (err) {
124
+ if (err instanceof SkillIntegrityError) {
125
+ throw new ApiError("skill.file_changed", "The stored skill file no longer matches its version; upload the skill again");
126
+ }
127
+ throw err;
128
+ }
129
+ }
130
+ async version(orgId, skillId, version) {
131
+ const { summary, versions } = await this.skills.resolve(orgId, skillId);
132
+ const want = version ?? summary.currentVersion;
133
+ const v = versions.find((x) => x.version === want);
134
+ if (!v)
135
+ throw fileNotFound();
136
+ return v;
137
+ }
138
+ };
139
+ SkillFiles = __decorate([
140
+ Injectable(),
141
+ __param(0, Inject(SkillsService)),
142
+ __param(1, Inject(StorageService))
143
+ ], SkillFiles);
144
+ export { SkillFiles };
@@ -1,9 +1,11 @@
1
+ import type { FastifyReply } from "fastify";
1
2
  import type { z } from "zod";
2
3
  import { OwnedItems, type OwnedSkillDeletePreview } from "../catalog/owned-items.js";
3
4
  import type { CreatedAttachment } from "../conversations/attachments.service.js";
4
5
  import { type Principal } from "../identity/principal.js";
5
6
  import { type OrgContext } from "../orgs/org.guard.js";
6
- import { SkillCreateBody, SkillIdParams, SkillUploadBody as UploadBody } from "./skills.schemas.js";
7
+ import { type SkillFileList, SkillFiles } from "./skill-files.js";
8
+ import { SkillCreateBody, SkillFileContentQuery, SkillFilesQuery, SkillIdParams, SkillUploadBody as UploadBody } from "./skills.schemas.js";
7
9
  import { type SkillDetail, type SkillSummary, SkillsService, type UploadedSkill } from "./skills.service.js";
8
10
  declare const ShareableBody: z.ZodObject<{
9
11
  shareable: z.ZodBoolean;
@@ -11,7 +13,7 @@ declare const ShareableBody: z.ZodObject<{
11
13
  /**
12
14
  * The org skill library (`/api/v1/orgs/:orgId/skills`, human users only):
13
15
  * - read: `skills.read` (member and up) — `GET /` list, `GET /:id` detail (versions and file
14
- * lists);
16
+ * lists), `GET /:id/files` a version's files and `GET /:id/files/content` one file's bytes;
15
17
  * - write: `skills.manage` (admin and up) —
16
18
  * 1. `POST /uploads` registers a skill package upload (`application/zip`, ≤ 50MB, returns a
17
19
  * presigned form, used like chat attachments);
@@ -29,9 +31,10 @@ export declare class SkillsController {
29
31
  private readonly skills;
30
32
  /** The org's own items: 可共享 and the delete of a promoted skill (rulings P3-3, P3-19). */
31
33
  private readonly owned;
34
+ private readonly files;
32
35
  constructor(skills: SkillsService,
33
36
  /** The org's own items: 可共享 and the delete of a promoted skill (rulings P3-3, P3-19). */
34
- owned: OwnedItems);
37
+ owned: OwnedItems, files: SkillFiles);
35
38
  createUpload(principal: Principal, org: OrgContext, body: z.infer<typeof UploadBody>): Promise<CreatedAttachment>;
36
39
  create(principal: Principal, org: OrgContext, body: z.infer<typeof SkillCreateBody>): Promise<UploadedSkill>;
37
40
  list(principal: Principal, org: OrgContext): Promise<{
@@ -40,6 +43,23 @@ export declare class SkillsController {
40
43
  get(principal: Principal, org: OrgContext, id: string): Promise<SkillDetail & {
41
44
  agentsOff: number;
42
45
  }>;
46
+ /**
47
+ * The files of a version of the skill (`?version=`, default the current one): `{ version, files:
48
+ * { path, size, contentType, previewable }[] }`. Visibility as `GET /:id`; an unknown version →
49
+ * 404 `skill.file_not_found`.
50
+ */
51
+ listFiles(principal: Principal, org: OrgContext, params: z.infer<typeof SkillIdParams>, q: z.infer<typeof SkillFilesQuery>): Promise<SkillFileList>;
52
+ /**
53
+ * One file's bytes (`?path=` a path of the version's manifest, `version=`, `limit=`, `inline=`),
54
+ * checked against the manifest (409 `skill.file_changed`); unknown version or path → 404
55
+ * `skill.file_not_found`. Never sniffed and sandboxed; `attachment` unless `inline=1` for a
56
+ * raster image (HTML and SVG never inline). A text file is sent as `text/plain`, anything not
57
+ * inline as `application/octet-stream`, the type by extension in `X-Content-Original-Type`;
58
+ * `X-Content-Truncated: true` when `limit` cut it. `as=url` (not with `limit`, 400) answers
59
+ * `{ url }` instead: a short-lived presigned attachment URL for that object, after the same
60
+ * manifest check (ruling R3: a native shell hands it to the system browser).
61
+ */
62
+ fileContent(principal: Principal, org: OrgContext, params: z.infer<typeof SkillIdParams>, q: z.infer<typeof SkillFileContentQuery>, reply: FastifyReply): Promise<void>;
43
63
  /**
44
64
  * Sets 可共享 on the org's own skill (`{ shareable }` -> 200 `{ id, shareable }`): only an org
45
65
  * skill of the org's own (P3-6: an agent's skill or a copy of another owner's platform skill ->