@jini-ai/agent-plugins 0.4.6 → 0.4.8

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 (152) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +48 -0
  3. package/dist/admin-surfaces/action-dispatcher.d.ts +37 -0
  4. package/dist/admin-surfaces/action-dispatcher.js +69 -0
  5. package/dist/admin-surfaces/action-schema.d.ts +56 -0
  6. package/dist/admin-surfaces/action-schema.js +167 -0
  7. package/dist/admin-surfaces/action-tools.d.ts +40 -0
  8. package/dist/admin-surfaces/action-tools.js +52 -0
  9. package/dist/admin-surfaces/callback-field-inbox.d.ts +35 -0
  10. package/dist/admin-surfaces/callback-field-inbox.js +53 -0
  11. package/dist/admin-surfaces/capability-declarations.d.ts +41 -0
  12. package/dist/admin-surfaces/capability-declarations.js +102 -0
  13. package/dist/admin-surfaces/contribution.d.ts +49 -0
  14. package/dist/admin-surfaces/contribution.js +30 -0
  15. package/dist/admin-surfaces/delivery-bindings.d.ts +76 -0
  16. package/dist/admin-surfaces/delivery-bindings.js +99 -0
  17. package/dist/admin-surfaces/descriptor.d.ts +69 -0
  18. package/dist/admin-surfaces/descriptor.js +196 -0
  19. package/dist/admin-surfaces/external-links.d.ts +45 -0
  20. package/dist/admin-surfaces/external-links.js +70 -0
  21. package/dist/admin-surfaces/host-validator.d.ts +62 -0
  22. package/dist/admin-surfaces/host-validator.js +87 -0
  23. package/dist/admin-surfaces/index.d.ts +23 -0
  24. package/dist/admin-surfaces/index.js +21 -0
  25. package/dist/admin-surfaces/protocol.d.ts +103 -0
  26. package/dist/admin-surfaces/protocol.js +25 -0
  27. package/dist/admin-surfaces/sandbox.d.ts +78 -0
  28. package/dist/admin-surfaces/sandbox.js +92 -0
  29. package/dist/admin-surfaces/settings-value.d.ts +28 -0
  30. package/dist/admin-surfaces/settings-value.js +45 -0
  31. package/dist/admin-surfaces/surface-capabilities.d.ts +167 -0
  32. package/dist/admin-surfaces/surface-capabilities.js +215 -0
  33. package/dist/admin-surfaces/surface-client.d.ts +116 -0
  34. package/dist/admin-surfaces/surface-client.js +219 -0
  35. package/dist/admin-surfaces/surface-handlers.d.ts +111 -0
  36. package/dist/admin-surfaces/surface-handlers.js +172 -0
  37. package/dist/admin-surfaces/theme.d.ts +59 -0
  38. package/dist/admin-surfaces/theme.js +57 -0
  39. package/dist/folder-zip-node.d.ts +11 -0
  40. package/dist/folder-zip-node.js +84 -0
  41. package/dist/folder-zip.d.ts +38 -0
  42. package/dist/folder-zip.js +134 -0
  43. package/dist/lifecycle/automatic-use.d.ts +79 -0
  44. package/dist/lifecycle/automatic-use.js +165 -0
  45. package/dist/lifecycle/compatibility-metadata.d.ts +19 -0
  46. package/dist/lifecycle/compatibility-metadata.js +45 -0
  47. package/dist/lifecycle/compatibility.d.ts +52 -0
  48. package/dist/lifecycle/compatibility.js +60 -0
  49. package/dist/lifecycle/fetch-archive.js +26 -24
  50. package/dist/lifecycle/index.d.ts +14 -2
  51. package/dist/lifecycle/index.js +8 -1
  52. package/dist/lifecycle/install-errors.d.ts +14 -0
  53. package/dist/lifecycle/install-errors.js +9 -0
  54. package/dist/lifecycle/install.d.ts +2 -13
  55. package/dist/lifecycle/install.js +12 -123
  56. package/dist/lifecycle/installed-package-index.d.ts +15 -0
  57. package/dist/lifecycle/installed-package-index.js +128 -0
  58. package/dist/lifecycle/installed-package-roots.js +28 -20
  59. package/dist/lifecycle/manifest.d.ts +14 -0
  60. package/dist/lifecycle/manifest.js +115 -100
  61. package/dist/lifecycle/package-paths.js +3 -3
  62. package/dist/lifecycle/ports.d.ts +1 -1
  63. package/dist/lifecycle/provider-contribution.d.ts +65 -0
  64. package/dist/lifecycle/provider-contribution.js +93 -0
  65. package/dist/lifecycle/resolve-agent-plugin-refs.js +19 -6
  66. package/dist/lifecycle/retire-bundled.js +20 -18
  67. package/dist/lifecycle/search.d.ts +6 -1
  68. package/dist/lifecycle/search.js +45 -7
  69. package/dist/lifecycle/set-enabled.d.ts +2 -1
  70. package/dist/lifecycle/set-enabled.js +52 -8
  71. package/dist/lifecycle/skill-file-reader.js +85 -71
  72. package/dist/lifecycle/tools/capabilities.d.ts +199 -0
  73. package/dist/lifecycle/tools/capabilities.js +213 -0
  74. package/dist/lifecycle/tools/definition.d.ts +32 -0
  75. package/dist/lifecycle/tools/definition.js +33 -0
  76. package/dist/lifecycle/tools/index.d.ts +10 -0
  77. package/dist/lifecycle/tools/index.js +10 -0
  78. package/dist/lifecycle/tools/manifest.d.ts +33 -0
  79. package/dist/lifecycle/tools/manifest.js +89 -0
  80. package/dist/lifecycle/tools/projection.d.ts +90 -0
  81. package/dist/lifecycle/tools/projection.js +283 -0
  82. package/dist/lifecycle/types.d.ts +2 -0
  83. package/dist/lifecycle/uninstall.d.ts +3 -1
  84. package/dist/lifecycle/uninstall.js +51 -27
  85. package/dist/lifecycle/update-plan.d.ts +18 -0
  86. package/dist/lifecycle/update-plan.js +22 -0
  87. package/dist/lifecycle/update-store.d.ts +71 -0
  88. package/dist/lifecycle/update-store.js +150 -0
  89. package/dist/lifecycle/update.d.ts +55 -0
  90. package/dist/lifecycle/update.js +321 -0
  91. package/dist/manifest.d.ts +2 -1
  92. package/dist/manifest.js +2 -1
  93. package/package.json +50 -6
  94. package/ui-ux-design/plugin.json +8 -2
  95. package/dist/index.d.ts.map +0 -1
  96. package/dist/index.js.map +0 -1
  97. package/dist/lifecycle/activation.d.ts.map +0 -1
  98. package/dist/lifecycle/activation.js.map +0 -1
  99. package/dist/lifecycle/bundled-digests.d.ts.map +0 -1
  100. package/dist/lifecycle/bundled-digests.js.map +0 -1
  101. package/dist/lifecycle/bundled-source-archive.d.ts.map +0 -1
  102. package/dist/lifecycle/bundled-source-archive.js.map +0 -1
  103. package/dist/lifecycle/capability-projection.d.ts.map +0 -1
  104. package/dist/lifecycle/capability-projection.js.map +0 -1
  105. package/dist/lifecycle/contribution-loader.d.ts.map +0 -1
  106. package/dist/lifecycle/contribution-loader.js.map +0 -1
  107. package/dist/lifecycle/fetch-archive.d.ts.map +0 -1
  108. package/dist/lifecycle/fetch-archive.js.map +0 -1
  109. package/dist/lifecycle/index.d.ts.map +0 -1
  110. package/dist/lifecycle/index.js.map +0 -1
  111. package/dist/lifecycle/install-from-url.d.ts.map +0 -1
  112. package/dist/lifecycle/install-from-url.js.map +0 -1
  113. package/dist/lifecycle/install.d.ts.map +0 -1
  114. package/dist/lifecycle/install.js.map +0 -1
  115. package/dist/lifecycle/installed-package-roots.d.ts.map +0 -1
  116. package/dist/lifecycle/installed-package-roots.js.map +0 -1
  117. package/dist/lifecycle/layout.d.ts.map +0 -1
  118. package/dist/lifecycle/layout.js.map +0 -1
  119. package/dist/lifecycle/manifest.d.ts.map +0 -1
  120. package/dist/lifecycle/manifest.js.map +0 -1
  121. package/dist/lifecycle/mcp-provisioning.d.ts.map +0 -1
  122. package/dist/lifecycle/mcp-provisioning.js.map +0 -1
  123. package/dist/lifecycle/node.d.ts.map +0 -1
  124. package/dist/lifecycle/node.js.map +0 -1
  125. package/dist/lifecycle/package-paths.d.ts.map +0 -1
  126. package/dist/lifecycle/package-paths.js.map +0 -1
  127. package/dist/lifecycle/persistent-state.d.ts.map +0 -1
  128. package/dist/lifecycle/persistent-state.js.map +0 -1
  129. package/dist/lifecycle/ports.d.ts.map +0 -1
  130. package/dist/lifecycle/ports.js.map +0 -1
  131. package/dist/lifecycle/resolve-agent-plugin-refs.d.ts.map +0 -1
  132. package/dist/lifecycle/resolve-agent-plugin-refs.js.map +0 -1
  133. package/dist/lifecycle/retire-bundled.d.ts.map +0 -1
  134. package/dist/lifecycle/retire-bundled.js.map +0 -1
  135. package/dist/lifecycle/search.d.ts.map +0 -1
  136. package/dist/lifecycle/search.js.map +0 -1
  137. package/dist/lifecycle/seed-bundled.d.ts.map +0 -1
  138. package/dist/lifecycle/seed-bundled.js.map +0 -1
  139. package/dist/lifecycle/set-enabled.d.ts.map +0 -1
  140. package/dist/lifecycle/set-enabled.js.map +0 -1
  141. package/dist/lifecycle/skill-file-reader.d.ts.map +0 -1
  142. package/dist/lifecycle/skill-file-reader.js.map +0 -1
  143. package/dist/lifecycle/trusted-plugin-files.d.ts.map +0 -1
  144. package/dist/lifecycle/trusted-plugin-files.js.map +0 -1
  145. package/dist/lifecycle/types.d.ts.map +0 -1
  146. package/dist/lifecycle/types.js.map +0 -1
  147. package/dist/lifecycle/uninstall.d.ts.map +0 -1
  148. package/dist/lifecycle/uninstall.js.map +0 -1
  149. package/dist/lifecycle/yauzl-archive-reader.d.ts.map +0 -1
  150. package/dist/lifecycle/yauzl-archive-reader.js.map +0 -1
  151. package/dist/manifest.d.ts.map +0 -1
  152. package/dist/manifest.js.map +0 -1
@@ -6,6 +6,36 @@ const TEXT_EXTENSIONS = new Set([".md", ".mdx", ".txt", ".json", ".yaml", ".yml"
6
6
  const MAX_FILE_BYTES = 256 * 1024;
7
7
  const MAX_WALK_ENTRIES = 4096;
8
8
  const MAX_WALK_DEPTH = 32;
9
+ const TOO_LARGE = "File request refused: exceeds the 256 KiB text limit; no content returned.";
10
+ const UNREADABLE = "File request refused: file is missing or unreadable.";
11
+ /** Reads an opened regular file of at most the cap; a file that grows past it after `stat` is still refused. */
12
+ async function readOpened(handle) {
13
+ const stat = await handle.stat();
14
+ if (!stat.isFile())
15
+ return { refusal: "File request refused: only regular text files are readable." };
16
+ if (stat.size > MAX_FILE_BYTES)
17
+ return { refusal: TOO_LARGE };
18
+ const buffer = Buffer.alloc(MAX_FILE_BYTES + 1);
19
+ let length = 0;
20
+ while (length < buffer.length) {
21
+ const { bytesRead } = await handle.read(buffer, length, buffer.length - length, null);
22
+ if (!bytesRead)
23
+ break;
24
+ length += bytesRead;
25
+ }
26
+ return length > MAX_FILE_BYTES ? { refusal: TOO_LARGE } : decodeText(buffer.subarray(0, length));
27
+ }
28
+ /** Admit only control-free UTF-8 text (tab, LF and CR allowed). */
29
+ function decodeText(bytes) {
30
+ if (bytes.some(byte => (byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) || byte === 127))
31
+ return { refusal: "File request refused: binary content cannot be read as text." };
32
+ try {
33
+ return { text: new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes) };
34
+ }
35
+ catch {
36
+ return { refusal: "File request refused: binary or invalid UTF-8 content cannot be read as text." };
37
+ }
38
+ }
9
39
  /**
10
40
  * Progressive disclosure for plugin AND standalone skills, with a skill-folder trust boundary.
11
41
  * Uses the lifecycle containment owner, native bounded reads and injected async filesystem effects.
@@ -14,67 +44,48 @@ const MAX_WALK_DEPTH = 32;
14
44
  */
15
45
  export function createSkillFileReader({ skillRoot, filesystem }, _options = {}) {
16
46
  const { assertContainedOnDisk } = createPackagePathsModule({ filesystem });
17
- /** Reject traversal even when normalization would leave it inside the folder. */
47
+ /** Reject traversal even when normalization would leave it inside the folder.
48
+ * @returns The refusal message, or `undefined` for an admissible name. */
18
49
  function validateFile(file) {
19
50
  if (!file || file.includes("\0") || file.includes("\\") || path.posix.isAbsolute(file) || /^[a-zA-Z]:/.test(file) || file.split("/").some(segment => segment === "..")) {
20
- throw new Error("File request refused: use a path relative to this skill folder, without traversal or absolute paths.");
51
+ return "File request refused: use a path relative to this skill folder, without traversal or absolute paths.";
21
52
  }
22
53
  if (!TEXT_EXTENSIONS.has(path.extname(file).toLowerCase())) {
23
- throw new Error("File request refused: only supported text extensions are readable.");
54
+ return "File request refused: only supported text extensions are readable.";
24
55
  }
56
+ return undefined;
25
57
  }
26
- /** Open the resolved target with no-follow and read at most cap + 1, including growing files. */
27
- async function readText(file) {
28
- validateFile(file);
29
- let absolute;
58
+ /** The canonical contained target of `file`, or `undefined` when it is missing or escapes the folder. */
59
+ async function resolveTarget(file) {
30
60
  try {
31
- absolute = await filesystem.realpath(await assertContainedOnDisk(skillRoot, file));
61
+ const absolute = await filesystem.realpath(await assertContainedOnDisk(skillRoot, file));
32
62
  // Recheck the canonical target through the same owner before opening it.
33
63
  const relative = path.relative(await filesystem.realpath(skillRoot), absolute);
34
64
  await assertContainedOnDisk(skillRoot, relative);
35
- validateFile(relative.split(path.sep).join("/"));
65
+ return validateFile(relative.split(path.sep).join("/")) === undefined ? absolute : undefined;
36
66
  }
37
67
  catch {
38
- throw new Error("File request refused: file is missing, unreadable, or resolves outside this skill folder.");
39
- }
40
- let handle;
41
- try {
42
- handle = await filesystem.open(absolute, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
43
- const stat = await handle.stat();
44
- if (!stat.isFile())
45
- throw new Error("File request refused: only regular text files are readable.");
46
- if (stat.size > MAX_FILE_BYTES)
47
- throw new Error("File request refused: exceeds the 256 KiB text limit; no content returned.");
48
- const buffer = Buffer.alloc(MAX_FILE_BYTES + 1);
49
- let length = 0;
50
- while (length < buffer.length) {
51
- const { bytesRead } = await handle.read(buffer, length, buffer.length - length, null);
52
- if (!bytesRead)
53
- break;
54
- length += bytesRead;
55
- }
56
- if (length > MAX_FILE_BYTES)
57
- throw new Error("File request refused: exceeds the 256 KiB text limit; no content returned.");
58
- const bytes = buffer.subarray(0, length);
59
- if (bytes.some(byte => (byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) || byte === 127))
60
- throw new Error("File request refused: binary content cannot be read as text.");
61
- try {
62
- return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
63
- }
64
- catch {
65
- throw new Error("File request refused: binary or invalid UTF-8 content cannot be read as text.");
66
- }
67
- }
68
- catch (error) {
69
- // Never reflect native errors or caller paths: either can contain an absolute host path.
70
- if (error instanceof Error && error.message.startsWith("File request refused:"))
71
- throw error;
72
- throw new Error("File request refused: file is missing or unreadable.");
73
- }
74
- finally {
75
- await handle?.close().catch(() => { });
68
+ return undefined;
76
69
  }
77
70
  }
71
+ /** Validate, resolve, then read one file; every refusal is a value, never a thrown native error. */
72
+ async function readText(file) {
73
+ const invalid = validateFile(file);
74
+ if (invalid !== undefined)
75
+ return { refusal: invalid };
76
+ const absolute = await resolveTarget(file);
77
+ if (absolute === undefined)
78
+ return { refusal: "File request refused: file is missing, unreadable, or resolves outside this skill folder." };
79
+ return readContained(absolute);
80
+ }
81
+ /** Open the resolved target with no-follow and read at most cap + 1, including growing files. */
82
+ async function readContained(absolute) {
83
+ const handle = await filesystem.open(absolute, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK).catch(() => undefined);
84
+ if (!handle)
85
+ return { refusal: UNREADABLE };
86
+ // Never reflect native errors or caller paths: either can contain an absolute host path.
87
+ return readOpened(handle).catch(() => ({ refusal: UNREADABLE })).finally(() => handle.close().catch(() => { }));
88
+ }
78
89
  /** Skip directory symlinks (including cycles); contained file symlinks use the same read guard. */
79
90
  async function listFiles() {
80
91
  const files = [];
@@ -85,45 +96,48 @@ export function createSkillFileReader({ skillRoot, filesystem }, _options = {})
85
96
  incomplete = true;
86
97
  return;
87
98
  }
88
- let entries;
89
- try {
90
- const directory = relative ? await assertContainedOnDisk(skillRoot, relative) : await filesystem.realpath(skillRoot);
91
- entries = await filesystem.readdir(directory, { withFileTypes: true });
92
- }
93
- catch {
99
+ const entries = await readDirectory(relative);
100
+ if (!entries) {
94
101
  incomplete = true;
95
102
  return;
96
103
  }
97
- for (const entry of entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
104
+ for (const entry of entries) {
98
105
  if (remaining-- <= 0) {
99
106
  incomplete = true;
100
107
  break;
101
108
  }
102
- const file = relative ? `${relative}/${entry.name}` : entry.name;
103
- if (entry.isDirectory())
104
- await walk(file, depth + 1);
105
- else if (file !== "SKILL.md" && (entry.isFile() || entry.isSymbolicLink())) {
106
- try {
107
- await readText(file);
108
- files.push(file);
109
- }
110
- catch { /* Refused files must not be advertised as readable. */ }
111
- }
109
+ await visit(entry, relative ? `${relative}/${entry.name}` : entry.name, depth);
112
110
  }
113
111
  }
112
+ async function visit(entry, file, depth) {
113
+ if (entry.isDirectory())
114
+ return walk(file, depth + 1);
115
+ if (file === "SKILL.md" || !(entry.isFile() || entry.isSymbolicLink()))
116
+ return;
117
+ // Refused files must not be advertised as readable.
118
+ if ("text" in await readText(file))
119
+ files.push(file);
120
+ }
114
121
  await walk("", 0);
115
122
  return { files: files.sort(), ...(incomplete ? { note: "Supporting-file inventory is incomplete: traversal limit reached or a directory is unreadable." } : {}) };
116
123
  }
124
+ /** One directory's entries in code-unit name order, or `undefined` when it cannot be read. */
125
+ async function readDirectory(relative) {
126
+ try {
127
+ const directory = relative ? await assertContainedOnDisk(skillRoot, relative) : await filesystem.realpath(skillRoot);
128
+ return (await filesystem.readdir(directory, { withFileTypes: true })).sort((a, b) => Number(a.name > b.name) - Number(a.name < b.name));
129
+ }
130
+ catch {
131
+ return undefined;
132
+ }
133
+ }
117
134
  return {
118
135
  async read(_input, options = {}) {
119
136
  const listing = await listFiles();
120
- try {
121
- return { ...listing, text: await readText(options.file ?? "SKILL.md") };
122
- }
123
- catch (error) {
124
- const refusal = error instanceof Error ? error.message : "File request refused.";
125
- return { files: listing.files, text: "", note: [refusal, `Valid supporting files: ${listing.files.join(", ") || "(none)"}. Omit file to request SKILL.md.`, listing.note].filter(Boolean).join(" ") };
126
- }
137
+ const outcome = await readText(options.file ?? "SKILL.md");
138
+ if ("text" in outcome)
139
+ return { ...listing, text: outcome.text };
140
+ return { files: listing.files, text: "", note: [outcome.refusal, `Valid supporting files: ${listing.files.join(", ") || "(none)"}. Omit file to request SKILL.md.`, listing.note].filter(Boolean).join(" ") };
127
141
  },
128
142
  };
129
143
  }
@@ -0,0 +1,199 @@
1
+ /**
2
+ * @file Host capabilities a plugin tool receives at invocation, typed as ports: the host supplies
3
+ * every implementation (token store, guarded HTTP, limiter, artifact store) and Jini never names a
4
+ * provider. A per-call session wraps them so that (1) every capability stops working the moment the
5
+ * plugin's tools are revoked, even for a module that kept a reference, and (2) an access token the
6
+ * call obtained can never leave through the tool's result or error text. Those two gates are
7
+ * `openCapabilityGate`, shared with the admin-surface session so both enforce them identically.
8
+ *
9
+ * Plugin state reaches a tool read-only: the plugin's admin surface writes its settings (for example
10
+ * which of its products are on), and its tools must honor them, but an agent tool never changes them.
11
+ */
12
+ /** Options for guarded HTTP; mirrors `@jini-ai/platform`'s guarded fetch, buffered bodies only. */
13
+ export interface AgentPluginHttpOptions {
14
+ readonly method?: 'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
15
+ readonly headers?: Readonly<Record<string, string>>;
16
+ readonly body?: string;
17
+ readonly signal?: AbortSignal;
18
+ }
19
+ /** Mirrors `@jini-ai/http-kit`'s `RateLimitResult`, so a host can pass its limiter straight through. */
20
+ export type AgentPluginLimitResult = {
21
+ readonly allowed: true;
22
+ } | {
23
+ readonly allowed: false;
24
+ readonly retryAfterSeconds: number;
25
+ };
26
+ /** Plain JSON a plugin keeps in its plugin- and workspace-scoped state. */
27
+ export type AgentPluginStateValue = null | boolean | number | string | readonly AgentPluginStateValue[] | {
28
+ readonly [key: string]: AgentPluginStateValue;
29
+ };
30
+ /**
31
+ * The read-only view of a plugin's own state: what its tools get, and what a host hands any other
32
+ * plugin execution context (form delivery, for example) that must honor the plugin's settings. A
33
+ * host handing it elsewhere passes an object with `get` only, never its whole store.
34
+ */
35
+ export interface AgentPluginStateReader {
36
+ get(required: {
37
+ readonly key: string;
38
+ }, optional?: Record<string, never>): Promise<AgentPluginStateValue | null>;
39
+ }
40
+ export interface AgentPluginToolCapabilities {
41
+ /** Resolves a fresh access token for a connection the host has scoped to this plugin and workspace.
42
+ * Never a refresh token. The host refuses a connectionRef the calling plugin does not own. */
43
+ readonly connections: {
44
+ getAccessToken(required: {
45
+ readonly connectionRef: string;
46
+ }, optional?: Record<string, never>): Promise<string>;
47
+ };
48
+ /** Outbound HTTP through the host's guarded client (allow-list, redirect refusal, deadlines). */
49
+ readonly http: {
50
+ fetch(required: {
51
+ readonly url: string;
52
+ }, optional?: AgentPluginHttpOptions): Promise<Response>;
53
+ };
54
+ /** Plugin-declared budgets; the host keys and sizes them. */
55
+ readonly limiter: {
56
+ check(required: {
57
+ readonly key: string;
58
+ }, optional?: Record<string, never>): Promise<AgentPluginLimitResult>;
59
+ };
60
+ /** Stores a file the run can hand to the user; returns an opaque reference, never a path. Absent
61
+ * when the host has no artifact store, so a tool checks `capabilities.artifacts` before relying on it. */
62
+ readonly artifacts?: {
63
+ write(required: {
64
+ readonly name: string;
65
+ readonly mediaType: string;
66
+ readonly content: string | Uint8Array;
67
+ }, optional?: Record<string, never>): Promise<{
68
+ readonly artifactRef: string;
69
+ }>;
70
+ };
71
+ /** The SAME store the plugin's admin-surface state writes, keyed by the same plugin and workspace
72
+ * scope. Read-only here: the session exposes `get` alone whatever object the host passes. */
73
+ readonly state: AgentPluginStateReader;
74
+ }
75
+ /** Context the host uses to scope capabilities: which plugin, which workspace/principal, which call. */
76
+ export interface AgentPluginToolCapabilityScope {
77
+ readonly pluginId: string;
78
+ readonly workspaceId: string;
79
+ readonly principalId?: string;
80
+ readonly signal?: AbortSignal;
81
+ }
82
+ /** Host port: builds the capabilities for one call. Called once per invocation. */
83
+ export type AgentPluginToolCapabilitiesPort = (required: AgentPluginToolCapabilityScope, optional?: Record<string, never>) => AgentPluginToolCapabilities;
84
+ /** One limit for every reader and writer of plugin state; the admin-surface limits reuse it. */
85
+ export declare const PLUGIN_STATE_MAX_KEY_LENGTH = 128;
86
+ export declare const REVOKED_MESSAGE = "This plugin tool was disabled; its capabilities are revoked. Re-enable the plugin and retry.";
87
+ export declare const WITHHELD_OUTPUT_MESSAGE = "The plugin tool result was withheld because it contained a connection credential.";
88
+ export declare const WITHHELD_ERROR_MESSAGE = "The plugin tool failed and its error was withheld because it contained a connection credential.";
89
+ /**
90
+ * Access tokens one plugin obtained, across all of its calls: plugin code that keeps a token in module
91
+ * scope must not be able to return or store it in a later call unseen.
92
+ */
93
+ export type IssuedTokenMemory = Set<string>;
94
+ /** Newest tokens kept; access tokens are short-lived, so older ones matter less than bounded memory. */
95
+ export declare const ISSUED_TOKEN_MEMORY_LIMIT = 64;
96
+ /** The host's one source of token memories, passed to its tool projection AND its admin-surface host. */
97
+ export interface IssuedTokenMemories {
98
+ forPlugin(required: {
99
+ readonly pluginId: string;
100
+ }, optional?: Record<string, never>): IssuedTokenMemory;
101
+ }
102
+ /**
103
+ * One token memory per plugin, shared by every context that runs that plugin's code: its tools, its
104
+ * surface handlers and their state writes. Why per plugin and not per context or generation: those
105
+ * contexts can share module scope (a common lib module), and Node caches an imported module, so its
106
+ * scope outlives a re-sync; a memory per context or per generation would let a token obtained in one
107
+ * leave through the other. A host creates ONE and passes it to both seams.
108
+ * @complexity O(1) per lookup; space O(plugins * ISSUED_TOKEN_MEMORY_LIMIT).
109
+ */
110
+ export declare function createIssuedTokenMemories(_required?: Record<string, never>, _optional?: Record<string, never>): IssuedTokenMemories;
111
+ /**
112
+ * The credential scans alone, for plugin answers that need no capabilities (a tool's
113
+ * affected-resources disclosure): `mentionsToken`, and `sanitize` (an error, or a credential-free
114
+ * replacement without `cause`, since the cause may hold the token).
115
+ * @param required.issued - The plugin's token memory (see `createIssuedTokenMemories`).
116
+ * @complexity O(1) to open; the scans are O(scanned size * remembered tokens).
117
+ */
118
+ export declare function openCredentialScan(required: {
119
+ readonly issued: IssuedTokenMemory;
120
+ }, _optional?: Record<string, never>): {
121
+ mentionsToken: ({ value }: {
122
+ readonly value: unknown;
123
+ }) => boolean;
124
+ sanitize({ error }: {
125
+ readonly error: unknown;
126
+ }): unknown;
127
+ };
128
+ export type AgentPluginCredentialScan = ReturnType<typeof openCredentialScan>;
129
+ /**
130
+ * The revocation and credential gates every capability session shares: this file's tool session and
131
+ * the admin-surface session (`../../admin-surfaces/surface-capabilities.ts`), so both revoke and scan
132
+ * the same way.
133
+ * @param required.isLive - False once the contributing plugin's contributions are revoked.
134
+ * @param required.issued - The plugin's token memory (see `createIssuedTokenMemories`).
135
+ * @returns `guard` (wraps a capability so it refuses once revoked), `noteToken` (records a token the
136
+ * call obtained), `mentionsToken`, and the `release` (result) and `sanitize` (error) gates.
137
+ * @complexity O(1) to open; the scans are O(serialized size * remembered tokens).
138
+ */
139
+ export declare function openCapabilityGate(required: {
140
+ readonly isLive: () => boolean;
141
+ readonly issued: IssuedTokenMemory;
142
+ }, _optional?: Record<string, never>): {
143
+ /** The result, unless it mentions a token this plugin obtained. */
144
+ release<T>({ value }: {
145
+ readonly value: T;
146
+ }): T;
147
+ mentionsToken: ({ value }: {
148
+ readonly value: unknown;
149
+ }) => boolean;
150
+ sanitize({ error }: {
151
+ readonly error: unknown;
152
+ }): unknown;
153
+ guard: <A extends unknown[], R>(call: (...args: A) => Promise<R>) => (...args: A) => Promise<R>;
154
+ noteToken({ token }: {
155
+ readonly token: string;
156
+ }): string;
157
+ };
158
+ export type AgentPluginCapabilityGate = ReturnType<typeof openCapabilityGate>;
159
+ /** The host capabilities every session wraps the same way: guarded HTTP, limiter and artifacts
160
+ * (artifacts only when the host gives a store: absent stays absent, never a wrapper that throws). @complexity O(1). */
161
+ export declare function guardSharedCapabilities(required: {
162
+ readonly gate: AgentPluginCapabilityGate;
163
+ readonly host: Pick<AgentPluginToolCapabilities, 'http' | 'limiter' | 'artifacts'>;
164
+ }, _optional?: Record<string, never>): Pick<AgentPluginToolCapabilities, 'http' | 'limiter' | 'artifacts'>;
165
+ /** The key shape every plugin state call shares, so a key never reaches the host as a path or a scope. */
166
+ export declare function checkedStateKey(required: {
167
+ readonly key: unknown;
168
+ }, _optional?: Record<string, never>): string;
169
+ /**
170
+ * The read-only state view a session hands out: `get` alone, the key checked and passed on by itself
171
+ * (so plugin code cannot add a scope the host might honor), revoked with the session's gate.
172
+ * @complexity O(1) plus the key check.
173
+ */
174
+ export declare function guardStateReader(required: {
175
+ readonly gate: AgentPluginCapabilityGate;
176
+ readonly state: AgentPluginStateReader;
177
+ }, _optional?: Record<string, never>): AgentPluginStateReader;
178
+ /**
179
+ * Opens the capability session for one tool call.
180
+ * @param required.capabilities - The host's capabilities for this call.
181
+ * @param required.isLive - False once the contributing plugin's tools are revoked.
182
+ * @param required.issued - The plugin's token memory, shared by all its calls and its surface handlers.
183
+ * @returns Wrapped capabilities plus `release` (result gate) and `sanitize` (error gate).
184
+ * @complexity O(1) to open; gates are O(serialized size).
185
+ */
186
+ export declare function openCapabilitySession(required: {
187
+ readonly capabilities: AgentPluginToolCapabilities;
188
+ readonly isLive: () => boolean;
189
+ readonly issued: IssuedTokenMemory;
190
+ }, _optional?: Record<string, never>): {
191
+ capabilities: AgentPluginToolCapabilities;
192
+ release: <T>({ value }: {
193
+ readonly value: T;
194
+ }) => T;
195
+ sanitize: ({ error }: {
196
+ readonly error: unknown;
197
+ }) => unknown;
198
+ };
199
+ //# sourceMappingURL=capabilities.d.ts.map
@@ -0,0 +1,213 @@
1
+ /**
2
+ * @file Host capabilities a plugin tool receives at invocation, typed as ports: the host supplies
3
+ * every implementation (token store, guarded HTTP, limiter, artifact store) and Jini never names a
4
+ * provider. A per-call session wraps them so that (1) every capability stops working the moment the
5
+ * plugin's tools are revoked, even for a module that kept a reference, and (2) an access token the
6
+ * call obtained can never leave through the tool's result or error text. Those two gates are
7
+ * `openCapabilityGate`, shared with the admin-surface session so both enforce them identically.
8
+ *
9
+ * Plugin state reaches a tool read-only: the plugin's admin surface writes its settings (for example
10
+ * which of its products are on), and its tools must honor them, but an agent tool never changes them.
11
+ */
12
+ /** One limit for every reader and writer of plugin state; the admin-surface limits reuse it. */
13
+ export const PLUGIN_STATE_MAX_KEY_LENGTH = 128;
14
+ const STATE_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
15
+ export const REVOKED_MESSAGE = 'This plugin tool was disabled; its capabilities are revoked. Re-enable the plugin and retry.';
16
+ export const WITHHELD_OUTPUT_MESSAGE = 'The plugin tool result was withheld because it contained a connection credential.';
17
+ export const WITHHELD_ERROR_MESSAGE = 'The plugin tool failed and its error was withheld because it contained a connection credential.';
18
+ /** Newest tokens kept; access tokens are short-lived, so older ones matter less than bounded memory. */
19
+ export const ISSUED_TOKEN_MEMORY_LIMIT = 64;
20
+ /**
21
+ * One token memory per plugin, shared by every context that runs that plugin's code: its tools, its
22
+ * surface handlers and their state writes. Why per plugin and not per context or generation: those
23
+ * contexts can share module scope (a common lib module), and Node caches an imported module, so its
24
+ * scope outlives a re-sync; a memory per context or per generation would let a token obtained in one
25
+ * leave through the other. A host creates ONE and passes it to both seams.
26
+ * @complexity O(1) per lookup; space O(plugins * ISSUED_TOKEN_MEMORY_LIMIT).
27
+ */
28
+ export function createIssuedTokenMemories(_required = {}, _optional = {}) {
29
+ const byPlugin = new Map();
30
+ return Object.freeze({
31
+ forPlugin({ pluginId }) {
32
+ let issued = byPlugin.get(pluginId);
33
+ if (issued === undefined)
34
+ byPlugin.set(pluginId, issued = new Set());
35
+ return issued;
36
+ },
37
+ });
38
+ }
39
+ /** Records `token` as newest, dropping the oldest beyond the limit. @complexity O(1) amortized. */
40
+ function remember(issued, token) {
41
+ issued.delete(token);
42
+ issued.add(token);
43
+ if (issued.size > ISSUED_TOKEN_MEMORY_LIMIT)
44
+ issued.delete(issued.values().next().value);
45
+ }
46
+ /** True when `text` holds any issued token, raw or JSON-escaped. @complexity O(n * t). */
47
+ function textMentions(text, issued) {
48
+ for (const token of issued)
49
+ if (text.includes(token) || text.includes(JSON.stringify(token).slice(1, -1)))
50
+ return true;
51
+ return false;
52
+ }
53
+ /** True when `value` (serialized) mentions any issued token. Unserializable values fail closed.
54
+ * @complexity O(n * t) for serialized size n and t issued tokens (t ≤ ISSUED_TOKEN_MEMORY_LIMIT). */
55
+ function mentionsToken(value, issued) {
56
+ if (issued.size === 0)
57
+ return false;
58
+ let text;
59
+ try {
60
+ text = JSON.stringify(value);
61
+ }
62
+ catch {
63
+ return true;
64
+ }
65
+ return text !== undefined && textMentions(text, issued);
66
+ }
67
+ /**
68
+ * Objects an error scan visits before it gives up and withholds the error. Generous for any real
69
+ * error (a few causes, an `AggregateError` of a few dozen), small enough to bound a hostile graph.
70
+ */
71
+ const ERROR_SCAN_NODE_LIMIT = 256;
72
+ /**
73
+ * Everything one object can hold a token in: every own property, non-enumerable and symbol-keyed
74
+ * ones too (`message`, `stack`, `cause`, `AggregateError.errors`), plus Map and Set contents.
75
+ * Null when reading it threw (a hostile getter or proxy): the caller fails closed.
76
+ * @complexity O(own properties + entries).
77
+ */
78
+ function childrenOf(value) {
79
+ try {
80
+ const own = Reflect.ownKeys(value).map(key => value[key]);
81
+ if (value instanceof Map)
82
+ return [...own, ...value.keys(), ...value.values()];
83
+ return value instanceof Set ? [...own, ...value.values()] : own;
84
+ }
85
+ catch {
86
+ return null;
87
+ }
88
+ }
89
+ /**
90
+ * True when any string reachable from `error` mentions an issued token. JSON would miss the
91
+ * non-enumerable `cause` and `AggregateError.errors`, and errors held in plain objects, so this walks
92
+ * the object graph instead, to any depth. It fails closed: an unreadable object, or a graph past
93
+ * `ERROR_SCAN_NODE_LIMIT` objects, counts as mentioning a token.
94
+ * @complexity O(v * t) for v visited values (objects bounded by the node limit) and t issued tokens.
95
+ */
96
+ function errorMentionsToken(error, issued) {
97
+ if (issued.size === 0)
98
+ return false;
99
+ const seen = new Set();
100
+ const pending = [error];
101
+ while (pending.length > 0) {
102
+ const next = scanStep(pending.pop(), issued, seen);
103
+ if (next === true)
104
+ return true;
105
+ // A loop, not push(...next): a huge array would exceed the engine's argument limit.
106
+ for (const child of next)
107
+ pending.push(child);
108
+ }
109
+ return false;
110
+ }
111
+ /** One value of the scan: `true` when it mentions a token or cannot be scanned, else what it holds. */
112
+ function scanStep(value, issued, seen) {
113
+ if (typeof value === 'string')
114
+ return textMentions(value, issued) || [];
115
+ if (typeof value !== 'object' || value === null || seen.has(value))
116
+ return [];
117
+ seen.add(value);
118
+ return (seen.size > ERROR_SCAN_NODE_LIMIT ? null : childrenOf(value)) ?? true;
119
+ }
120
+ /**
121
+ * The credential scans alone, for plugin answers that need no capabilities (a tool's
122
+ * affected-resources disclosure): `mentionsToken`, and `sanitize` (an error, or a credential-free
123
+ * replacement without `cause`, since the cause may hold the token).
124
+ * @param required.issued - The plugin's token memory (see `createIssuedTokenMemories`).
125
+ * @complexity O(1) to open; the scans are O(scanned size * remembered tokens).
126
+ */
127
+ export function openCredentialScan(required, _optional = {}) {
128
+ const { issued } = required;
129
+ return {
130
+ mentionsToken: ({ value }) => mentionsToken(value, issued),
131
+ sanitize({ error }) {
132
+ return errorMentionsToken(error, issued) ? new Error(WITHHELD_ERROR_MESSAGE) : error;
133
+ },
134
+ };
135
+ }
136
+ /**
137
+ * The revocation and credential gates every capability session shares: this file's tool session and
138
+ * the admin-surface session (`../../admin-surfaces/surface-capabilities.ts`), so both revoke and scan
139
+ * the same way.
140
+ * @param required.isLive - False once the contributing plugin's contributions are revoked.
141
+ * @param required.issued - The plugin's token memory (see `createIssuedTokenMemories`).
142
+ * @returns `guard` (wraps a capability so it refuses once revoked), `noteToken` (records a token the
143
+ * call obtained), `mentionsToken`, and the `release` (result) and `sanitize` (error) gates.
144
+ * @complexity O(1) to open; the scans are O(serialized size * remembered tokens).
145
+ */
146
+ export function openCapabilityGate(required, _optional = {}) {
147
+ const { isLive, issued } = required;
148
+ return {
149
+ guard: (call) => async (...args) => {
150
+ if (!isLive())
151
+ throw new Error(REVOKED_MESSAGE);
152
+ return call(...args);
153
+ },
154
+ noteToken({ token }) {
155
+ if (token)
156
+ remember(issued, token);
157
+ return token;
158
+ },
159
+ ...openCredentialScan({ issued }),
160
+ /** The result, unless it mentions a token this plugin obtained. */
161
+ release({ value }) {
162
+ if (mentionsToken(value, issued))
163
+ throw new Error(WITHHELD_OUTPUT_MESSAGE);
164
+ return value;
165
+ },
166
+ };
167
+ }
168
+ /** The host capabilities every session wraps the same way: guarded HTTP, limiter and artifacts
169
+ * (artifacts only when the host gives a store: absent stays absent, never a wrapper that throws). @complexity O(1). */
170
+ export function guardSharedCapabilities(required, _optional = {}) {
171
+ const { gate: { guard }, host } = required;
172
+ const { artifacts } = host;
173
+ return {
174
+ http: Object.freeze({ fetch: guard((input, options) => host.http.fetch(input, options)) }),
175
+ limiter: Object.freeze({ check: guard((input) => host.limiter.check(input)) }),
176
+ ...(artifacts !== undefined && { artifacts: Object.freeze({ write: guard((input) => artifacts.write(input)) }) }),
177
+ };
178
+ }
179
+ /** The key shape every plugin state call shares, so a key never reaches the host as a path or a scope. */
180
+ export function checkedStateKey(required, _optional = {}) {
181
+ const { key } = required;
182
+ if (typeof key !== 'string' || !STATE_KEY_PATTERN.test(key))
183
+ throw new Error(`A settings key must be a short name of at most ${PLUGIN_STATE_MAX_KEY_LENGTH} characters.`);
184
+ return key;
185
+ }
186
+ /**
187
+ * The read-only state view a session hands out: `get` alone, the key checked and passed on by itself
188
+ * (so plugin code cannot add a scope the host might honor), revoked with the session's gate.
189
+ * @complexity O(1) plus the key check.
190
+ */
191
+ export function guardStateReader(required, _optional = {}) {
192
+ const { gate, state } = required;
193
+ return Object.freeze({ get: gate.guard(({ key }) => state.get({ key: checkedStateKey({ key }) })) });
194
+ }
195
+ /**
196
+ * Opens the capability session for one tool call.
197
+ * @param required.capabilities - The host's capabilities for this call.
198
+ * @param required.isLive - False once the contributing plugin's tools are revoked.
199
+ * @param required.issued - The plugin's token memory, shared by all its calls and its surface handlers.
200
+ * @returns Wrapped capabilities plus `release` (result gate) and `sanitize` (error gate).
201
+ * @complexity O(1) to open; gates are O(serialized size).
202
+ */
203
+ export function openCapabilitySession(required, _optional = {}) {
204
+ const { capabilities: host, isLive, issued } = required;
205
+ const gate = openCapabilityGate({ isLive, issued });
206
+ const capabilities = Object.freeze({
207
+ connections: Object.freeze({ getAccessToken: gate.guard(async (input) => gate.noteToken({ token: await host.connections.getAccessToken({ connectionRef: input.connectionRef }) })) }),
208
+ ...guardSharedCapabilities({ gate, host }),
209
+ state: guardStateReader({ gate, state: host.state }),
210
+ });
211
+ return { capabilities, release: gate.release, sanitize: gate.sanitize };
212
+ }
213
+ //# sourceMappingURL=capabilities.js.map
@@ -0,0 +1,32 @@
1
+ /**
2
+ * @file The executable tool contribution, defined on the lifecycle's one executable loader
3
+ * (`defineExecutablePluginContribution`) so tool modules pass the same gates as every other seam
4
+ * that runs plugin code: active plugin, bundled digest, contained `.mjs` path. No second loader.
5
+ * The filename is the host's: Jini never names a product's contribution file.
6
+ */
7
+ import { type LoadedPluginContribution, type PluginContributionDefinition } from '../contribution-loader.js';
8
+ import type { AgentPluginToolCapabilities } from './capabilities.js';
9
+ import { type AgentPluginToolDescriptor } from './manifest.js';
10
+ /** What a tool module's default export must be. `input` has already passed the declared schema. */
11
+ export interface AgentPluginToolModule {
12
+ readonly invoke: (required: {
13
+ readonly input: Readonly<Record<string, unknown>>;
14
+ readonly capabilities: AgentPluginToolCapabilities;
15
+ readonly signal?: AbortSignal;
16
+ }, optional?: Record<string, never>) => unknown;
17
+ /** Human-readable resources the call would change, shown before confirmation. Required unless `read`. */
18
+ readonly describeAffectedResources?: (required: {
19
+ readonly input: Readonly<Record<string, unknown>>;
20
+ }, optional?: Record<string, never>) => unknown;
21
+ }
22
+ export type LoadedAgentPluginTool = LoadedPluginContribution<AgentPluginToolDescriptor, AgentPluginToolModule>;
23
+ /**
24
+ * Defines the tool contribution for a host-chosen filename (e.g. `<product>-agent-tools.json`).
25
+ * @param required.filename - The file a plugin ships at its package root to contribute tools.
26
+ * @returns A definition for `loadPluginContributions`; executable, so activation is always required.
27
+ * @complexity O(1); each load is one contained import per declared tool (Node caches per file URL).
28
+ */
29
+ export declare function defineAgentPluginToolContribution(required: {
30
+ readonly filename: string;
31
+ }, _optional?: Record<string, never>): PluginContributionDefinition<AgentPluginToolDescriptor, LoadedAgentPluginTool>;
32
+ //# sourceMappingURL=definition.d.ts.map