@capybara-hq/plugin-sdk 0.1.0-rc.9 → 0.1.0-rc.90

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 (159) hide show
  1. package/README.md +3 -1
  2. package/agent-docs/agent-templates.md +14 -2
  3. package/agent-docs/concepts.md +14 -5
  4. package/agent-docs/connector-templates.md +11 -3
  5. package/agent-docs/extension-points/channel.md +1 -1
  6. package/agent-docs/extension-points/context.md +15 -0
  7. package/agent-docs/extension-points/device-provider.md +15 -0
  8. package/agent-docs/extension-points/file-preview.md +3 -1
  9. package/agent-docs/extension-points/identity-source.md +2 -0
  10. package/agent-docs/extension-points/model-provider.md +5 -1
  11. package/agent-docs/extension-points/object-store.md +2 -0
  12. package/agent-docs/extension-points/push-provider.md +17 -0
  13. package/agent-docs/extension-points/trigger-source.md +19 -0
  14. package/agent-docs/extensions.md +98 -4
  15. package/agent-docs/plugin-format.md +45 -10
  16. package/agent-docs/setup.md +54 -0
  17. package/api/plugin-sdk.api.md +5983 -0
  18. package/dist/agent-template.d.ts +15 -6
  19. package/dist/agent-template.js +32 -13
  20. package/dist/agents-ctx.d.ts +116 -0
  21. package/dist/agents-ctx.js +22 -0
  22. package/dist/avatar-presets.d.ts +8 -0
  23. package/dist/avatar-presets.js +17 -0
  24. package/dist/bootstrap.d.ts +109 -1
  25. package/dist/bootstrap.js +185 -2
  26. package/dist/cards.d.ts +121 -13
  27. package/dist/cards.js +161 -19
  28. package/dist/channel.d.ts +133 -47
  29. package/dist/channel.js +10 -5
  30. package/dist/client-css.d.ts +36 -0
  31. package/dist/client-css.js +326 -0
  32. package/dist/client-section.d.ts +35 -0
  33. package/dist/client-section.js +133 -0
  34. package/dist/config-ui.d.ts +28 -6
  35. package/dist/config-ui.js +88 -25
  36. package/dist/config-url-fetch.d.ts +19 -0
  37. package/dist/config-url-fetch.js +43 -0
  38. package/dist/connector-auth.d.ts +13 -2
  39. package/dist/connector-auth.js +82 -8
  40. package/dist/connector.d.ts +74 -32
  41. package/dist/context.d.ts +40 -0
  42. package/dist/context.js +2 -0
  43. package/dist/ctx.d.ts +344 -31
  44. package/dist/ctx.js +9 -1
  45. package/dist/define-extension.d.ts +18 -12
  46. package/dist/define-extension.js +18 -5
  47. package/dist/device-denied-paths.d.ts +20 -0
  48. package/dist/device-denied-paths.js +118 -0
  49. package/dist/device-operation.d.ts +348 -0
  50. package/dist/device-operation.js +312 -0
  51. package/dist/device-protocol.d.ts +286 -49
  52. package/dist/device-protocol.js +766 -89
  53. package/dist/device-provider.d.ts +820 -0
  54. package/dist/device-provider.js +432 -0
  55. package/dist/device-service.d.ts +204 -0
  56. package/dist/device-service.js +291 -0
  57. package/dist/dial-in.d.ts +286 -0
  58. package/dist/dial-in.js +213 -0
  59. package/dist/directory.d.ts +15 -12
  60. package/dist/extension-point.d.ts +2 -0
  61. package/dist/extension-point.js +8 -3
  62. package/dist/field-meta.d.ts +19 -0
  63. package/dist/field-meta.js +54 -0
  64. package/dist/file-preview.d.ts +46 -9
  65. package/dist/git-hosts.d.ts +53 -0
  66. package/dist/git-hosts.js +98 -0
  67. package/dist/hooks.d.ts +185 -22
  68. package/dist/hooks.js +6 -0
  69. package/dist/http-access.d.ts +71 -0
  70. package/dist/http-access.js +12 -0
  71. package/dist/identity.d.ts +70 -9
  72. package/dist/identity.js +46 -1
  73. package/dist/inbox.d.ts +103 -0
  74. package/dist/inbox.js +173 -0
  75. package/dist/index.d.ts +30 -4
  76. package/dist/index.js +30 -4
  77. package/dist/model-params.d.ts +41 -22
  78. package/dist/model-params.js +28 -15
  79. package/dist/model.d.ts +295 -77
  80. package/dist/model.js +249 -21
  81. package/dist/native-failure.d.ts +13 -0
  82. package/dist/native-failure.js +31 -0
  83. package/dist/net.d.ts +52 -0
  84. package/dist/net.js +34 -0
  85. package/dist/network-classes.d.ts +98 -0
  86. package/dist/network-classes.js +291 -0
  87. package/dist/permissions.d.ts +95 -25
  88. package/dist/permissions.js +175 -54
  89. package/dist/platform-only.d.ts +27 -0
  90. package/dist/platform-only.js +35 -0
  91. package/dist/plugin-manifest.d.ts +30 -6
  92. package/dist/plugin-manifest.js +147 -55
  93. package/dist/plugin-package.d.ts +82 -39
  94. package/dist/plugin-package.js +68 -41
  95. package/dist/push.d.ts +75 -0
  96. package/dist/push.js +87 -0
  97. package/dist/sandbox-linux-runtime-source.d.ts +1 -0
  98. package/dist/sandbox-linux-runtime-source.js +2343 -0
  99. package/dist/sandbox-native-runtime-source.d.ts +10 -0
  100. package/dist/sandbox-native-runtime-source.js +480 -0
  101. package/dist/sandbox-runtime-source.d.ts +47 -0
  102. package/dist/sandbox-runtime-source.js +73 -0
  103. package/dist/sandbox-write-denies.d.ts +139 -0
  104. package/dist/sandbox-write-denies.js +869 -0
  105. package/dist/secret.d.ts +8 -2
  106. package/dist/secret.js +11 -4
  107. package/dist/setup-check.d.ts +128 -0
  108. package/dist/setup-check.js +142 -0
  109. package/dist/setup-guide-parse.d.ts +121 -0
  110. package/dist/setup-guide-parse.js +356 -0
  111. package/dist/setup-guide-render.d.ts +45 -0
  112. package/dist/setup-guide-render.js +351 -0
  113. package/dist/setup-guide.d.ts +86 -72
  114. package/dist/setup-guide.js +340 -108
  115. package/dist/shell-capabilities.d.ts +216 -0
  116. package/dist/shell-capabilities.js +44 -0
  117. package/dist/shell-environment.d.ts +57 -0
  118. package/dist/shell-environment.js +21 -0
  119. package/dist/skill-invocation.d.ts +5 -0
  120. package/dist/skill-invocation.js +4 -3
  121. package/dist/skill.d.ts +27 -17
  122. package/dist/skill.js +40 -26
  123. package/dist/storage.d.ts +52 -25
  124. package/dist/svg-viewbox.d.ts +10 -0
  125. package/dist/svg-viewbox.js +24 -0
  126. package/dist/theme-assets.d.ts +25 -9
  127. package/dist/theme-assets.js +87 -47
  128. package/dist/theme-tokens.generated.d.ts +40 -12
  129. package/dist/theme-tokens.generated.js +36 -8
  130. package/dist/theme.d.ts +56 -10
  131. package/dist/theme.js +117 -23
  132. package/dist/tool.d.ts +242 -28
  133. package/dist/tool.js +135 -13
  134. package/dist/trigger-source.d.ts +35 -0
  135. package/dist/trigger-source.js +2 -0
  136. package/dist/triggers.d.ts +88 -0
  137. package/dist/triggers.js +71 -0
  138. package/dist/ui-parts.d.ts +23 -0
  139. package/dist/ui-parts.js +374 -0
  140. package/dist/ui-resolve.d.ts +2 -7
  141. package/dist/ui-resolve.js +7 -19
  142. package/dist/ui-slots.d.ts +27 -5
  143. package/dist/ui-slots.js +112 -19
  144. package/dist/ui.d.ts +203 -64
  145. package/dist/ui.js +117 -23
  146. package/dist/url.d.ts +4 -1
  147. package/dist/url.js +4 -1
  148. package/dist/web.d.ts +26 -20
  149. package/package.json +13 -1
  150. package/schemas/bootstrap-extra.v1.schema.json +186 -0
  151. package/schemas/bootstrap.v1.schema.json +20 -0
  152. package/schemas/connector-template.v1.schema.json +62 -4
  153. package/schemas/plugin.v1.schema.json +74 -143
  154. package/schemas/theme.v1.schema.json +77 -0
  155. package/agent-docs/extension-points/sandbox.md +0 -15
  156. package/dist/org-access.d.ts +0 -27
  157. package/dist/org-access.js +0 -35
  158. package/dist/sandbox.d.ts +0 -254
  159. package/dist/sandbox.js +0 -153
package/dist/config-ui.js CHANGED
@@ -1,4 +1,9 @@
1
1
  import { z } from "zod";
2
+ import { withMeta } from "./field-meta.js";
3
+ import { isPlatformOnly } from "./platform-only.js";
4
+ import { isSecret } from "./secret.js";
5
+ /** Every channel inbound mode, in the order forms list them. */
6
+ export const CHANNEL_INBOUND_MODES = ["long_connection", "webhook"];
2
7
  /** Limits of config UI hints and of the JSON Schemas a plugin package carries. */
3
8
  export const CONFIG_UI_LIMITS = {
4
9
  /** Characters per language of a `label` (also `unit`, `item.addLabel`). */
@@ -23,11 +28,11 @@ export const CONFIG_UI_LIMITS = {
23
28
  };
24
29
  /**
25
30
  * Attaches config UI hints to a schema (zod meta `ui`), merging with existing meta (`secret`,
26
- * `hot`, `description`). Returns the same schema type. Convention: put `ui()` outermost, after
31
+ * `hot`, `platformOnly`, `description`), also the meta of the nodes under its wrappers. Returns the same schema type. Convention: put `ui()` outermost, after
27
32
  * `.default()` / `.optional()`.
28
33
  */
29
34
  export function ui(schema, hints) {
30
- return schema.meta({ ...(schema.meta() ?? {}), ui: hints });
35
+ return withMeta(schema, "ui", hints);
31
36
  }
32
37
  /** zod types JSON Schema cannot express: emitted as `{}` with `x-unsupported`. */
33
38
  const UNSUPPORTED = new Set([
@@ -48,10 +53,10 @@ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
48
53
  /**
49
54
  * An extension config schema as a JSON Schema for forms (the input side, defaults included, no
50
55
  * `$schema`):
51
- * - meta `secret: true` becomes `"x-secret": true`, `hot: true` becomes `"x-hot": true`, `org`
52
- * (`orgAccess`) becomes `"x-org"`, `ui`
53
- * becomes `"x-ui"` (a JSON copy of the hints); `title` / `description` are filled from
54
- * `x-ui.label.en` / `x-ui.help.en` when the node has none;
56
+ * - meta `secret: true` becomes `"x-secret": true`, `hot: true` becomes `"x-hot": true`,
57
+ * `platformOnly: true` (`platformOnly`) becomes `"x-platform-only": true`, `ui` becomes
58
+ * `"x-ui"` (a JSON copy of the hints); `title` / `description` are filled from `x-ui.label.en` /
59
+ * `x-ui.help.en` when the node has none;
55
60
  * - unrepresentable types become `{ "x-unsupported": true }` instead of throwing;
56
61
  * - under a secret node no value is published: `default` / `examples` / `const` / `enum` and
57
62
  * `x-ui.options` / `x-ui.presets` are removed from it and all its descendants.
@@ -62,16 +67,20 @@ export function configJsonSchema(schema) {
62
67
  unrepresentable: "any",
63
68
  override: (ctx) => {
64
69
  const js = ctx.jsonSchema;
65
- const def = ctx.zodSchema._zod.def;
66
- if (js.secret === true)
70
+ const node = ctx.zodSchema;
71
+ const def = node._zod.def;
72
+ // A mark on a node under a wrapper (`secret(x).nullable()`) counts for the wrapper too:
73
+ // otherwise the wrapper's `default` would be published beside an `anyOf` branch.
74
+ if (js.secret === true || isSecret(node))
67
75
  js["x-secret"] = true;
68
76
  delete js.secret;
69
77
  if (js.hot === true)
70
78
  js["x-hot"] = true;
71
79
  delete js.hot;
72
- if (js.org !== undefined)
73
- js["x-org"] = js.org;
74
- delete js.org;
80
+ if (js.platformOnly === true || isPlatformOnly(node)) {
81
+ js["x-platform-only"] = true;
82
+ }
83
+ delete js.platformOnly;
75
84
  if ("ui" in js) {
76
85
  // A JSON copy: hints are data, and the scrub must never mutate the schema's meta.
77
86
  const hints = JSON.parse(JSON.stringify(js.ui ?? null));
@@ -163,9 +172,18 @@ const HINT_KEYS = new Set([
163
172
  "secrets",
164
173
  "sections",
165
174
  "messages",
175
+ "inboundModes",
166
176
  ]);
167
177
  /** The only hints a secret node may carry. */
168
- const SECRET_HINT_KEYS = new Set(["label", "help", "placeholder", "order", "section", "advanced"]);
178
+ const SECRET_HINT_KEYS = new Set([
179
+ "label",
180
+ "help",
181
+ "placeholder",
182
+ "order",
183
+ "section",
184
+ "advanced",
185
+ "inboundModes",
186
+ ]);
169
187
  const ITEM_KEYS = new Set(["title", "subtitle", "addLabel", "reorder"]);
170
188
  const utf8Bytes = (s) => new TextEncoder().encode(s).length;
171
189
  /** The JSON types a node accepts (`type`, a type list, or the branches of a nullable `anyOf`). */
@@ -281,17 +299,13 @@ export function validateConfigUi(schema, level) {
281
299
  };
282
300
  const visit = (node, path, isRoot, depth) => {
283
301
  const report = (message) => problems.push({ path, message });
284
- if (node["x-org"] !== undefined) {
285
- const org = node["x-org"];
302
+ if (node["x-platform-only"] !== undefined) {
286
303
  if (level !== "deployment")
287
- report(`x-org is only allowed at the deployment level, not ${level}`);
288
- else if (depth !== 1)
289
- report("x-org is only allowed on a top-level field of the config");
290
- else if (org !== "readonly" && org !== "override") {
291
- report(`x-org must be "readonly" or "override", not ${JSON.stringify(org)}`);
292
- }
293
- else if (org === "readonly" && node["x-secret"] === true) {
294
- report('x-org "readonly" on a secret field: an org never sees a secret, so there is nothing to show');
304
+ report(`x-platform-only is only allowed at the deployment level, not ${level}`);
305
+ else if (depth > 1)
306
+ report("x-platform-only is only allowed on the config root or a top-level field");
307
+ else if (node["x-platform-only"] !== true) {
308
+ report(`x-platform-only must be true, not ${JSON.stringify(node["x-platform-only"])}`);
295
309
  }
296
310
  }
297
311
  const text = (value, what, max, plainOk = false) => {
@@ -326,7 +340,7 @@ export function validateConfigUi(schema, level) {
326
340
  if (!isObj(raw))
327
341
  report("x-ui must be an object");
328
342
  else
329
- checkHints(raw, node, isRoot, report, text);
343
+ checkHints(raw, node, isRoot, depth, report, text);
330
344
  }
331
345
  const shape = shapeOf(node);
332
346
  const props = shape.properties;
@@ -343,7 +357,7 @@ export function validateConfigUi(schema, level) {
343
357
  visit(shape.additionalProperties, path === "" ? "additionalProperties" : `${path}.additionalProperties`, false, depth + 1);
344
358
  }
345
359
  };
346
- const checkHints = (h, node, isRoot, report, text) => {
360
+ const checkHints = (h, node, isRoot, depth, report, text) => {
347
361
  const shape = shapeOf(node);
348
362
  const types = typesOf(node);
349
363
  const isArray = types.has("array");
@@ -356,7 +370,7 @@ export function validateConfigUi(schema, level) {
356
370
  if (node["x-secret"] === true) {
357
371
  const bad = Object.keys(h).filter((k) => HINT_KEYS.has(k) && !SECRET_HINT_KEYS.has(k));
358
372
  if (bad.length > 0) {
359
- report(`a secret field allows only label, help, placeholder, order, section and advanced hints, not ${bad.join(", ")}`);
373
+ report(`a secret field allows only label, help, placeholder, order, section, advanced and inboundModes hints, not ${bad.join(", ")}`);
360
374
  }
361
375
  }
362
376
  text(h.label, "label", L.labelChars);
@@ -369,6 +383,28 @@ export function validateConfigUi(schema, level) {
369
383
  if (h.advanced !== undefined && typeof h.advanced !== "boolean") {
370
384
  report("advanced must be a boolean");
371
385
  }
386
+ if (h.inboundModes !== undefined) {
387
+ const modes = h.inboundModes;
388
+ if (level !== "connection") {
389
+ report(`inboundModes is only allowed at the connection level, not ${level}`);
390
+ }
391
+ else if (depth !== 1) {
392
+ report("inboundModes is only allowed on a top-level field of the config");
393
+ }
394
+ else if (!Array.isArray(modes) || modes.length === 0) {
395
+ report("inboundModes must be a non-empty array");
396
+ }
397
+ else {
398
+ modes.forEach((m, i) => {
399
+ if (!CHANNEL_INBOUND_MODES.includes(m)) {
400
+ report(`inboundModes[${i}] must be one of ${CHANNEL_INBOUND_MODES.join(", ")}`);
401
+ }
402
+ else if (modes.indexOf(m) !== i) {
403
+ report(`inboundModes[${i}] "${String(m)}" is listed twice`);
404
+ }
405
+ });
406
+ }
407
+ }
372
408
  if (h.section !== undefined) {
373
409
  if (typeof h.section !== "string" || !sectionIds.has(h.section)) {
374
410
  report(`section "${String(h.section)}" is not an id of the root's sections`);
@@ -600,3 +636,30 @@ export function validateConfigUi(schema, level) {
600
636
  }
601
637
  return problems;
602
638
  }
639
+ /**
640
+ * The top-level fields of a connection config's JSON Schema ({@link configJsonSchema}) that carry
641
+ * an `inboundModes` hint, with their modes (unknown modes dropped). Pure; fields without the hint
642
+ * belong to every mode and are not listed.
643
+ */
644
+ export function inboundModeFields(schema) {
645
+ const out = {};
646
+ for (const [key, node] of Object.entries(properties(schema))) {
647
+ const hints = isObj(node) ? node["x-ui"] : undefined;
648
+ const modes = isObj(hints) ? hints.inboundModes : undefined;
649
+ if (!Array.isArray(modes))
650
+ continue;
651
+ const known = CHANNEL_INBOUND_MODES.filter((m) => modes.includes(m));
652
+ if (known.length > 0)
653
+ out[key] = known;
654
+ }
655
+ return out;
656
+ }
657
+ /**
658
+ * The fields `mode` requires ({@link inboundModeFields}) for which `has(field)` is false, in schema
659
+ * order: what the kernel refuses on a channel connection create or config / mode change.
660
+ */
661
+ export function missingInboundModeFields(schema, mode, has) {
662
+ return Object.entries(inboundModeFields(schema))
663
+ .filter(([key, modes]) => modes.includes(mode) && !has(key))
664
+ .map(([key]) => key);
665
+ }
@@ -0,0 +1,19 @@
1
+ import type { ExtensionNet } from "./net.js";
2
+ /**
3
+ * The `fetch` a plugin gives its vendor SDK for a URL taken from config that an org may override.
4
+ *
5
+ * `opts.url` is the URL in use (from the effective config of the org the call is made for) and
6
+ * `opts.platform` is the platform's own value(s) of that field, read from `ctx.config` at call
7
+ * time. When `url` equals a platform value (trailing slashes ignored) it is the platform's own
8
+ * endpoint and the global `fetch` is returned; any other URL was set by an org, so the returned
9
+ * function goes through `net.fetch` (the kernel's guarded client) with `opts.orgId`.
10
+ *
11
+ * Read `platform` from `ctx.config` each time you build the fetch: after the platform changes
12
+ * its value, an org's old copy no longer equals it and is guarded. Pass the result as the vendor
13
+ * SDK's `fetch` option.
14
+ */
15
+ export declare function configUrlFetch(net: Pick<ExtensionNet, "fetch">, opts: {
16
+ url: string;
17
+ platform?: string | readonly string[] | undefined;
18
+ orgId?: string | undefined;
19
+ }): typeof fetch;
@@ -0,0 +1,43 @@
1
+ function trimSlashes(u) {
2
+ return u.replace(/\/+$/, "");
3
+ }
4
+ /**
5
+ * The `fetch` a plugin gives its vendor SDK for a URL taken from config that an org may override.
6
+ *
7
+ * `opts.url` is the URL in use (from the effective config of the org the call is made for) and
8
+ * `opts.platform` is the platform's own value(s) of that field, read from `ctx.config` at call
9
+ * time. When `url` equals a platform value (trailing slashes ignored) it is the platform's own
10
+ * endpoint and the global `fetch` is returned; any other URL was set by an org, so the returned
11
+ * function goes through `net.fetch` (the kernel's guarded client) with `opts.orgId`.
12
+ *
13
+ * Read `platform` from `ctx.config` each time you build the fetch: after the platform changes
14
+ * its value, an org's old copy no longer equals it and is guarded. Pass the result as the vendor
15
+ * SDK's `fetch` option.
16
+ */
17
+ export function configUrlFetch(net, opts) {
18
+ const platform = opts.platform === undefined
19
+ ? []
20
+ : typeof opts.platform === "string"
21
+ ? [opts.platform]
22
+ : opts.platform;
23
+ const url = trimSlashes(opts.url);
24
+ // An empty URL ("", "/") never counts as the platform's.
25
+ if (url !== "" && platform.some((p) => trimSlashes(p) === url))
26
+ return fetch;
27
+ const netOpts = opts.orgId === undefined ? {} : { orgId: opts.orgId };
28
+ return (async (input, init) => {
29
+ if (typeof input === "string")
30
+ return net.fetch(input, init, netOpts);
31
+ if (input instanceof URL)
32
+ return net.fetch(input.href, init, netOpts);
33
+ // A Request carries its method, headers, body and signal: forward them under any explicit init.
34
+ const hasBody = input.method !== "GET" && input.method !== "HEAD";
35
+ const fromRequest = {
36
+ method: input.method,
37
+ headers: input.headers,
38
+ signal: input.signal,
39
+ ...(hasBody ? { body: await input.clone().arrayBuffer() } : {}),
40
+ };
41
+ return net.fetch(input.url, { ...fromRequest, ...init }, netOpts);
42
+ });
43
+ }
@@ -1,5 +1,15 @@
1
1
  import { z } from "zod";
2
- /** 认证方式:只有类型与非密钥字段;凭据值走内核的 `credential` / 凭据接口。 */
2
+ /**
3
+ * Authorization request parameters the kernel sets itself, or that would change what the callback
4
+ * or the token exchange relies on, or that never belong on a URL. `oauth_code`
5
+ * `authorizationParams` cannot use them, nor can the query of a manual `authorizationUrl`; the kernel
6
+ * checks the list again before it builds an authorize URL.
7
+ */
8
+ export declare const OAUTH_RESERVED_AUTHORIZATION_PARAMS: readonly ["response_type", "client_id", "redirect_uri", "state", "code_challenge", "code_challenge_method", "scope", "resource", "response_mode", "request", "request_uri", "nonce", "dpop_jkt", "authorization_details", "client_secret", "client_assertion", "client_assertion_type", "code", "code_verifier", "grant_type", "refresh_token"];
9
+ /**
10
+ * Authentication method: only the type and non-secret fields; credential values go through the
11
+ * kernel's `credential` / credentials API.
12
+ */
3
13
  export declare const ConnectorAuthSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
4
14
  type: z.ZodLiteral<"none">;
5
15
  }, z.core.$strict>, z.ZodObject<{
@@ -51,6 +61,7 @@ export declare const ConnectorAuthSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
51
61
  client_secret_post: "client_secret_post";
52
62
  }>>;
53
63
  tokenTypes: z.ZodOptional<z.ZodArray<z.ZodString>>;
64
+ authorizationParams: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
54
65
  }, z.core.$strict>, z.ZodObject<{
55
66
  type: z.ZodLiteral<"oauth_client">;
56
67
  ownership: z.ZodLiteral<"org">;
@@ -62,5 +73,5 @@ export declare const ConnectorAuthSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
62
73
  }>>;
63
74
  tokenTypes: z.ZodOptional<z.ZodArray<z.ZodString>>;
64
75
  }, z.core.$strict>], "type">;
65
- /** 认证预设({@link ConnectorAuthSchema} 的输出)。 */
76
+ /** Auth preset (the output of {@link ConnectorAuthSchema}). */
66
77
  export type ConnectorAuthPreset = z.infer<typeof ConnectorAuthSchema>;
@@ -1,21 +1,24 @@
1
1
  import { z } from "zod";
2
2
  /*
3
- * 连接器的认证方式(只有类型与非密钥字段,凭据值不在这里):内核的连接器安装接口与企业目录里的连接器模板
4
- * (`ConnectorTemplateSpec.auth`)共用这一个 schema。各分支都是 strict:多出的字段(如 `token`)一律拒绝,
5
- * 所以合法的认证预设里不可能夹带凭据。OAuth 端点是否必须 https 由内核按部署配置再校验。
3
+ * A connector's authentication method (only the type and non-secret fields; credential values are
4
+ * not here): the kernel's connector install API and the connector templates in the catalog
5
+ * (`ConnectorTemplateSpec.auth`) share this one schema. Every branch is strict: extra fields (such
6
+ * as `token`) are always rejected,
7
+ * so a valid auth preset cannot smuggle in a credential. Whether OAuth endpoints must be https is
8
+ * checked again by the kernel per deployment config.
6
9
  */
7
- /** HTTP 头名(RFC 9110 token)。 */
10
+ /** HTTP header name (RFC 9110 token). */
8
11
  const HeaderName = z
9
12
  .string()
10
13
  .min(1)
11
14
  .max(100)
12
15
  .regex(/^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/, "Invalid header name");
13
16
  const Ownership = z.enum(["org", "personal"]);
14
- /** OAuth 端点(https 等由内核按部署配置再校验)。 */
17
+ /** OAuth endpoint (https etc. is checked again by the kernel per deployment config). */
15
18
  const OAuthUrl = z.url().max(2000);
16
- /** 令牌端点的客户端认证方式(有客户端密钥时)。 */
19
+ /** Client authentication method at the token endpoint (when there is a client secret). */
17
20
  const TokenAuthMethod = z.enum(["client_secret_basic", "client_secret_post"]);
18
- /** OAuth scope(RFC 6749 §3.3 scope-token)。 */
21
+ /** OAuth scope (RFC 6749 §3.3 scope-token). */
19
22
  const Scopes = z
20
23
  .array(z
21
24
  .string()
@@ -36,7 +39,58 @@ const TokenTypes = z
36
39
  .regex(/^[A-Za-z][A-Za-z0-9_.-]*$/, "Invalid token type")
37
40
  .refine((t) => t.toLowerCase() !== "dpop", "DPoP tokens are not bearer tokens"))
38
41
  .max(5);
39
- /** 认证方式:只有类型与非密钥字段;凭据值走内核的 `credential` / 凭据接口。 */
42
+ /**
43
+ * Authorization request parameters the kernel sets itself, or that would change what the callback
44
+ * or the token exchange relies on, or that never belong on a URL. `oauth_code`
45
+ * `authorizationParams` cannot use them, nor can the query of a manual `authorizationUrl`; the kernel
46
+ * checks the list again before it builds an authorize URL.
47
+ */
48
+ export const OAUTH_RESERVED_AUTHORIZATION_PARAMS = [
49
+ // set by the kernel's authorize request
50
+ "response_type",
51
+ "client_id",
52
+ "redirect_uri",
53
+ "state",
54
+ "code_challenge",
55
+ "code_challenge_method",
56
+ "scope",
57
+ "resource",
58
+ // would change what the callback or the token exchange relies on
59
+ "response_mode",
60
+ "request",
61
+ "request_uri",
62
+ "nonce",
63
+ "dpop_jkt",
64
+ "authorization_details",
65
+ // credentials and token-endpoint names
66
+ "client_secret",
67
+ "client_assertion",
68
+ "client_assertion_type",
69
+ "code",
70
+ "code_verifier",
71
+ "grant_type",
72
+ "refresh_token",
73
+ ];
74
+ const RESERVED_PARAMS = new Set(OAUTH_RESERVED_AUTHORIZATION_PARAMS);
75
+ const reservedParamMessage = (name) => `"${name}" is set by the kernel and cannot be an authorization parameter`;
76
+ const MAX_AUTHORIZATION_PARAMS = 10;
77
+ /**
78
+ * Extra query parameters of the authorize request (e.g. Google's `access_type: "offline"`,
79
+ * `prompt: "consent"`): names `[a-z][a-z0-9_]` up to 40 characters, values 1-200 printable ASCII
80
+ * characters, at most 10, none of {@link OAUTH_RESERVED_AUTHORIZATION_PARAMS}. Not secrets: they
81
+ * are stored in plain JSON and shown in the browser's address bar.
82
+ */
83
+ const AuthorizationParams = z
84
+ .record(z.string().regex(/^[a-z][a-z0-9_]{0,39}$/, "Invalid authorization parameter name"), z.string().regex(/^[\x20-\x7E]{1,200}$/, "Invalid authorization parameter value"))
85
+ .refine((p) => Object.keys(p).length <= MAX_AUTHORIZATION_PARAMS, {
86
+ message: `At most ${MAX_AUTHORIZATION_PARAMS} authorization parameters`,
87
+ })
88
+ .describe("Extra query parameters of the OAuth authorize request (e.g. access_type, prompt). " +
89
+ "Never put a secret here.");
90
+ /**
91
+ * Authentication method: only the type and non-secret fields; credential values go through the
92
+ * kernel's `credential` / credentials API.
93
+ */
40
94
  export const ConnectorAuthSchema = z.discriminatedUnion("type", [
41
95
  z.object({ type: z.literal("none") }).strict(),
42
96
  z.object({ type: z.literal("bearer"), ownership: Ownership }).strict(),
@@ -71,9 +125,29 @@ export const ConnectorAuthSchema = z.discriminatedUnion("type", [
71
125
  client: z.enum(["dcr", "manual"]),
72
126
  tokenAuthMethod: TokenAuthMethod.optional(),
73
127
  tokenTypes: TokenTypes.optional(),
128
+ authorizationParams: AuthorizationParams.optional(),
74
129
  })
75
130
  .strict()
76
131
  .superRefine((a, ctx) => {
132
+ for (const name of Object.keys(a.authorizationParams ?? {})) {
133
+ if (RESERVED_PARAMS.has(name))
134
+ ctx.addIssue({
135
+ code: "custom",
136
+ path: ["authorizationParams", name],
137
+ message: reservedParamMessage(name),
138
+ });
139
+ }
140
+ // A query in a manual endpoint stays (RFC 6749 §3.1), but never with a name the kernel owns
141
+ if (a.authorizationUrl !== undefined && URL.canParse(a.authorizationUrl)) {
142
+ for (const name of new Set(new URL(a.authorizationUrl).searchParams.keys())) {
143
+ if (RESERVED_PARAMS.has(name.toLowerCase()))
144
+ ctx.addIssue({
145
+ code: "custom",
146
+ path: ["authorizationUrl"],
147
+ message: reservedParamMessage(name),
148
+ });
149
+ }
150
+ }
77
151
  if (a.discovery === "manual") {
78
152
  for (const k of ["authorizationUrl", "tokenUrl"]) {
79
153
  if (a[k] === undefined)
@@ -1,16 +1,19 @@
1
1
  import type { ZodTypeAny } from "zod";
2
2
  import type { FormAnswer, ToolContent, ToolResult, ToolSpec } from "./tool.js";
3
- /** 注入到出站请求的鉴权信息。 */
3
+ /** Authentication information injected into outbound requests. */
4
4
  export interface AuthInjection {
5
5
  headers: Record<string, string>;
6
6
  query?: Record<string, string>;
7
7
  }
8
- /** 连接器与远端服务的一次会话。 */
8
+ /** One session between the connector and the remote service. */
9
9
  export interface ConnectorSession {
10
10
  listTools(): Promise<ToolSpec[]>;
11
11
  /**
12
- * `ctx.spec`:内核快照里该工具已复核的定义(`connector_tools.spec`,绝不是待复核的新定义),含 listTools 时给出的
13
- * `connectorData`。连接器应按它路由调用,而不是重新读取远端描述(远端变化须先经漂移复核)。旧内核不传,须判空。
12
+ * `ctx.spec`: the already-reviewed definition of this tool in the kernel snapshot
13
+ * (`connector_tools.spec`, never a new definition awaiting review), including the `connectorData`
14
+ * given at listTools.
15
+ * The connector should route the call by it rather than re-reading the remote description (remote
16
+ * changes must pass drift review first). Old kernels do not pass it; check for absence.
14
17
  */
15
18
  callTool(name: string, input: unknown, signal: AbortSignal, ctx?: {
16
19
  spec: ToolSpec;
@@ -22,13 +25,19 @@ export interface ConnectorSession {
22
25
  mimeType?: string;
23
26
  }[]>;
24
27
  readResource?(uri: string): Promise<ToolResult>;
25
- /** 可选:远端提供的提示模板(如 MCP prompts)。不支持时不实现,内核须判空。 */
28
+ /**
29
+ * Optional: prompt templates the remote provides (e.g. MCP prompts). Do not implement when
30
+ * unsupported; the kernel must check for absence.
31
+ */
26
32
  listPrompts?(): Promise<PromptInfo[]>;
27
- /** 可选:按参数渲染一个提示模板,返回消息(如 MCP `prompts/get`)。失败抛 ToolError(英文、不含凭据)。 */
33
+ /**
34
+ * Optional: renders a prompt template with arguments and returns messages (e.g. MCP
35
+ * `prompts/get`). On failure throw ToolError (English, no credentials).
36
+ */
28
37
  getPrompt?(name: string, args: Record<string, string>): Promise<RenderedPrompt>;
29
38
  close(): Promise<void>;
30
39
  }
31
- /** 远端提示模板(`/连接器:提示名` 斜杠命令)。 */
40
+ /** A remote prompt template (the `/connector:promptName` slash command). */
32
41
  export interface PromptInfo {
33
42
  name: string;
34
43
  title?: string;
@@ -39,7 +48,10 @@ export interface PromptInfo {
39
48
  required?: boolean;
40
49
  }[];
41
50
  }
42
- /** 渲染后的提示:按顺序的消息,内容块同工具结果(非文本给类型说明)。 */
51
+ /**
52
+ * A rendered prompt: messages in order, content blocks the same as tool results (non-text gets a
53
+ * type description).
54
+ */
43
55
  export interface RenderedPrompt {
44
56
  description?: string;
45
57
  messages: {
@@ -48,9 +60,11 @@ export interface RenderedPrompt {
48
60
  }[];
49
61
  }
50
62
  /**
51
- * 远端在一次调用中途向用户要输入(MCP `elicitation/create`):
52
- * - `form`:`requestedSchema` 是远端给的扁平 JSON Schema(object + 原始类型属性),由内核映射成交互表单;
53
- * - `url`:请用户在浏览器里打开 `url` 完成某步(授权、付款、填敏感信息),完成与否由用户确认。
63
+ * The remote asks the user for input in the middle of a call (MCP `elicitation/create`):
64
+ * - `form`: `requestedSchema` is the flat JSON Schema the remote gives (object + primitive-typed
65
+ * properties), which the kernel maps to an interactive form;
66
+ * - `url`: asks the user to open `url` in a browser to complete a step (authorization, payment,
67
+ * entering sensitive information); the user confirms whether it was completed.
54
68
  */
55
69
  export type ElicitationRequest = {
56
70
  mode: "form";
@@ -62,7 +76,10 @@ export type ElicitationRequest = {
62
76
  url: string;
63
77
  elicitationId: string;
64
78
  };
65
- /** 对 elicitation 的答复(与 MCP `ElicitResult` 对应):接受(带表单内容)/ 拒绝 / 取消。 */
79
+ /**
80
+ * The reply to an elicitation (corresponds to MCP `ElicitResult`): accept (with form content) /
81
+ * decline / cancel.
82
+ */
66
83
  export type ElicitationResponse = {
67
84
  action: "accept";
68
85
  content?: FormAnswer;
@@ -71,18 +88,26 @@ export type ElicitationResponse = {
71
88
  } | {
72
89
  action: "cancel";
73
90
  };
74
- /** 内核打开会话时传给连接器的参数。 */
91
+ /** Parameters the kernel passes to the connector when it opens a session. */
75
92
  export interface ConnectorOpenArgs {
76
- /** 已按 endpointSchema 校验。 */
93
+ /** Already validated against endpointSchema. */
77
94
  endpoint: unknown;
78
- /** 每次请求前调用,凭据的刷新由内核负责。 */
95
+ /** Called before every request; refreshing credentials is the kernel's job. */
79
96
  auth: () => Promise<AuthInjection>;
80
- /** 收到 401 时调用一次;内核刷新凭据后,插件重试一次。 */
97
+ /** Called once on a 401; after the kernel refreshes credentials the plugin retries once. */
81
98
  onUnauthorized: () => Promise<void>;
82
99
  signal: AbortSignal;
83
100
  /**
84
- * 会话期间远端报告工具清单变了(如 MCP `notifications/tools/list_changed`)时调用,可能多次;内核据此安排一次
85
- * 漂移检查(新的 / 变了的工具在管理员复核前不可用)。可选:旧内核不提供,连接器须判空。不要等待它、不要因它抛错。
101
+ * The org this session serves. Pass it to `ctx.net.fetch` as `opts.orgId` for every request to
102
+ * the endpoint, so the org's allowed internal endpoints apply (and no other org's).
103
+ */
104
+ orgId: string;
105
+ /**
106
+ * Called when the remote reports during the session that its tool list changed (e.g. MCP
107
+ * `notifications/tools/list_changed`), possibly several times; the kernel schedules one
108
+ * drift check from it (new / changed tools are unavailable until an admin reviews them).
109
+ * Optional: old kernels do not provide it, so the connector must check for absence. Do not wait
110
+ * for it and do not throw because of it.
86
111
  */
87
112
  onToolsChanged?: () => void;
88
113
  /**
@@ -91,17 +116,26 @@ export interface ConnectorOpenArgs {
91
116
  * when the kernel does not provide it, the connector does not declare the MCP elicitation
92
117
  * capability (so the remote never starts one).
93
118
  *
94
- * 内核不能在等用户回答期间保持远端调用(运行会暂停、worker 释放、会话关闭):需要问用户时,内核**中止本次调用**
95
- * (经 `callTool` 的 signal)并让运行进入等待;用户回答后内核重新发起同一调用,远端再次发起同样的 elicitation 时
96
- * 由本回调立即用用户的答案答复。所以连接器只需「收到就调用、拿到就回」,不要自己缓存或重试;需要问用户时本回调
97
- * 以错误拒绝(调用已被中止),连接器让该错误原样结束本次调用即可。
119
+ * The kernel cannot hold a remote call while waiting for the user to answer (the run pauses, the
120
+ * worker is released, the session closes): when the user must be asked, the kernel **aborts this
121
+ * call**
122
+ * (via the `callTool` signal) and puts the run into waiting; after the user answers the kernel
123
+ * issues the same call again, and when the remote raises the same elicitation again
124
+ * this callback replies at once with the user's answer. So the connector only needs "call it when
125
+ * received, return what it gets"; do not cache or retry yourself; when the user must be asked
126
+ * this callback
127
+ * rejects with an error (the call has already been aborted), and the connector simply lets that
128
+ * error end this call unchanged.
98
129
  */
99
130
  onElicit?: (request: ElicitationRequest) => Promise<ElicitationResponse>;
100
131
  }
101
132
  /**
102
- * 远端描述里声明的一种认证方式,映射到内核连接器认证(ConnectorAuth)的形状,供安装向导预填。
103
- * `scheme` 是远端描述里的名字(如 OpenAPI `securitySchemes` 的键),`description` 原样给出(可能缺省)。
104
- * 只列内核支持的方式;其余(cookie 里的 API key、OpenID Connect、implicit / password 流等)不出现。
133
+ * An authentication method declared in the remote description, mapped to the shape of the kernel's
134
+ * connector auth (ConnectorAuth), to prefill the install wizard.
135
+ * `scheme` is the name in the remote description (e.g. the key of OpenAPI `securitySchemes`),
136
+ * `description` is given as is (may be absent).
137
+ * Only methods the kernel supports are listed; the rest (API keys in cookies, OpenID Connect,
138
+ * implicit / password flows, etc.) do not appear.
105
139
  */
106
140
  export type AuthHint = {
107
141
  scheme: string;
@@ -124,31 +158,39 @@ export type AuthHint = {
124
158
  tokenUrl: string;
125
159
  scopes: string[];
126
160
  });
127
- /** 远端描述里的一个操作(如 OpenAPI operation),供安装向导勾选。 */
161
+ /**
162
+ * An operation in the remote description (e.g. an OpenAPI operation), for the install wizard to
163
+ * tick.
164
+ */
128
165
  export interface ConnectorOperation {
129
- /** 端点配置里勾选用的 id(如 OpenAPI 的 operationId)。 */
166
+ /** The id used for ticking in the endpoint config (e.g. OpenAPI's operationId). */
130
167
  id: string;
131
- /** 大写 HTTP 方法。 */
168
+ /** Uppercase HTTP method. */
132
169
  method: string;
133
170
  path: string;
134
171
  summary?: string;
135
172
  }
136
- /** `Connector.inspect` 的结果。 */
173
+ /** The result of `Connector.inspect`. */
137
174
  export interface ConnectorInspection {
138
175
  authHints: AuthHint[];
139
176
  operations?: ConnectorOperation[];
140
177
  }
141
- /** `connector@1`:插件实现、内核调用。 */
178
+ /** `connector@1`: implemented by the plugin, called by the kernel. */
142
179
  export interface Connector {
143
180
  kind: string;
144
181
  endpointSchema: ZodTypeAny;
145
182
  open(args: ConnectorOpenArgs): Promise<ConnectorSession>;
146
183
  /**
147
- * 可选:不带凭据读取端点的描述(安装向导的预览用),返回声明的认证方式与可选的操作清单。
148
- * `endpoint` 已按 endpointSchema 校验。失败抛 ToolError(消息英文、不含凭据)。旧连接器不实现,内核须判空。
184
+ * Optional: reads the endpoint's description without credentials (for the install wizard
185
+ * preview), returning the declared auth methods and an optional operation list.
186
+ * `endpoint` is already validated against endpointSchema. On failure throw ToolError (message in
187
+ * English, no credentials). Old connectors do not implement it; the kernel must check for
188
+ * absence. `orgId` is the org the preview runs for: pass it to `ctx.net.fetch` as `opts.orgId`
189
+ * for every request to the endpoint, as with `ConnectorOpenArgs.orgId`.
149
190
  */
150
191
  inspect?(args: {
151
192
  endpoint: unknown;
152
193
  signal: AbortSignal;
194
+ orgId: string;
153
195
  }): Promise<ConnectorInspection>;
154
196
  }
@@ -0,0 +1,40 @@
1
+ import type { ConversationSource } from "./tool.js";
2
+ /**
3
+ * What the kernel passes to a `context@1` provider at the start of a run. The provider returns the
4
+ * text it wants the model to see, or null.
5
+ */
6
+ export interface ContextRequest {
7
+ orgId: string;
8
+ /** The run's trigger account (the person whose message started the run). */
9
+ accountId: string;
10
+ agentId: string;
11
+ agentName: string;
12
+ conversationId: string;
13
+ runId: string;
14
+ /** Where the conversation comes from. */
15
+ source: ConversationSource;
16
+ /** The trigger account's role in the org. */
17
+ role: "owner" | "admin" | "member" | "guest";
18
+ /** The conversation's owner (`conversations.account_id`); `accountId` is the run's trigger account. */
19
+ ownerAccountId: string;
20
+ ownerName: string;
21
+ /** Keys of the tools the agent has in this run. */
22
+ tools: string[];
23
+ /** The provider's effective config for the org. */
24
+ config: unknown;
25
+ /** Aborts when the call runs past {@link CONTEXT_LIMITS}.timeoutMs or the run is aborted. */
26
+ signal: AbortSignal;
27
+ }
28
+ /** The text a provider adds to the model's context, or null for nothing. */
29
+ export type ContextResult = {
30
+ text: string;
31
+ } | null;
32
+ /** The `context@1` contract: an extension that adds text to the model's context at run start. */
33
+ export interface ContextProvider {
34
+ provide(req: ContextRequest): Promise<ContextResult>;
35
+ }
36
+ /** Limits on one `provide` call: the time it may take and the bytes of text the kernel keeps. */
37
+ export declare const CONTEXT_LIMITS: {
38
+ readonly timeoutMs: 2000;
39
+ readonly maxBytes: 32768;
40
+ };
@@ -0,0 +1,2 @@
1
+ /** Limits on one `provide` call: the time it may take and the bytes of text the kernel keeps. */
2
+ export const CONTEXT_LIMITS = { timeoutMs: 2000, maxBytes: 32768 };