@capybara-hq/plugin-sdk 0.1.0-rc.84 → 0.1.0-rc.86

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.
@@ -0,0 +1,17 @@
1
+ # Authoring: extension point trigger-source
2
+
3
+ <!-- generated:extension-point -->
4
+ - Name: `trigger-source` (a ref is `trigger-source@<major>`)
5
+ - Declares the events an extension emits and which people may see their subjects.
6
+ - Providers: several
7
+ - Enabled per org: yes
8
+ - Brokered by the platform: yes (extensions use it only through `ctx`)
9
+ <!-- /generated -->
10
+
11
+ Contract: TriggerSource (`trigger-source.ts`), with `ctx.triggers` (`triggers.ts`)
12
+
13
+ Declare the event types the extension emits in `permissions.triggers.emit` (lower-case dotted names such as `item.created`, at most 64) and implement `TriggerSource.events()` with one `TriggerEventDeclaration` per type: a name, whether the event is directed at one agent, and its facts (a type, a name and whether automations may filter on it). Emit with `ctx.triggers.emit(event)`; the result says whether the `dedupeKey` was already seen (`duplicate`). An event carries the org, the subject (kind, id, title, optional url), scalar or string-list facts, a summary of at most 4096 UTF-8 bytes for the agent, and optionally the cause (the tool call or the account) and an audience for directed events. `emit` throws `TriggerError`: `type_not_declared`, `invalid_event` or `org_disabled`.
14
+
15
+ `visible` answers which of the given accounts may see a subject; the kernel only wakes agents of accounts it lists, and a throw or a missing answer means nobody. `subjectLink` optionally gives people a link to the subject. Automation filters are conjunctions over facts: `eq` compares scalars, `in` matches a scalar fact against a list, `contains` matches a list fact against a scalar, and a missing fact never matches.
16
+
17
+ See `extensions` for the rules every extension follows.
@@ -128,6 +128,7 @@ look like `channel@1`: name and major version. The registered points:
128
128
  | `file-preview` | multi | yes | Renders previews of files of given types: conversation files, shared files and skill files. |
129
129
  | `web-search` | multi | yes | Searches the web for the WebSearch tool; each org picks a default provider. |
130
130
  | `context` | multi | yes | Adds text to the model's context at run start in conversations of orgs that enable it. |
131
+ | `trigger-source` | multi | yes | Declares the events an extension emits and which people may see their subjects. |
131
132
  | `web-fetch` | multi | yes | Fetches and extracts web pages for the WebFetch tool; each org picks a default provider. |
132
133
  | `push-provider` | multi | no | Delivers push notifications to people's mobile apps through one channel (APNs, FCM, an aggregator). |
133
134
  <!-- /generated -->
package/dist/ctx.d.ts CHANGED
@@ -9,7 +9,8 @@ import type { ExtensionNet } from "./net.js";
9
9
  import type { SetupCheckDefinition } from "./setup-check.js";
10
10
  import type { ObjectHead, PresignedUpload, PresignGetOptions } from "./storage.js";
11
11
  import type { ToolCallContext, ToolHandler, ToolSpec, ToolWatcher } from "./tool.js";
12
- import type { EmbedClaims, UiActionArgs, UiActionResult, UiRenderArgs, UiView } from "./ui.js";
12
+ import type { TriggersCtx } from "./triggers.js";
13
+ import type { EmbedClaims, JsonValue, UiActionArgs, UiActionResult, UiQueryArgs, UiRenderArgs, UiView } from "./ui.js";
13
14
  /** Logger interface. */
14
15
  export interface Logger {
15
16
  info(msg: string, fields?: Record<string, unknown>): void;
@@ -378,6 +379,18 @@ export interface ExtensionContext {
378
379
  ui: {
379
380
  view(id: string, render: (args: UiRenderArgs) => Promise<UiView>): void;
380
381
  action(id: string, handler: (args: UiActionArgs) => Promise<UiActionResult>): void;
382
+ /**
383
+ * Registers the data source of `usePluginQuery` for a component (only during `setup`). `id`
384
+ * must be a component id declared in `permissions.ui.components`; the kernel refuses any other
385
+ * id. Queries work in any org-scoped component slot (`org.page`, conversation and agent slots
386
+ * alike). The result is JSON of at most `UI_LIMITS.componentQueryBytes` bytes and the call's
387
+ * params at most `UI_LIMITS.componentQueryParamsBytes`. Push refresh reaches queries only
388
+ * through org-stream invalidations (`invalidate({ orgId, contribution })` without a
389
+ * `conversationId`): a conversation-scoped invalidation does not refetch them, so a component
390
+ * in a conversation slot refetches through an action result's `invalidate` query names (or
391
+ * its own `refetch`).
392
+ */
393
+ query(id: string, handler: (args: UiQueryArgs) => Promise<JsonValue>): void;
381
394
  invalidate(target: {
382
395
  /** Required, except for a `platform.page` contribution, where it must be omitted. */
383
396
  orgId?: string;
@@ -426,6 +439,11 @@ export interface ExtensionContext {
426
439
  * see {@link DeviceAccessCtx}).
427
440
  */
428
441
  deviceAccess: DeviceAccessCtx;
442
+ /**
443
+ * Emits events automations can react to (requires `permissions.triggers`, see
444
+ * {@link TriggersCtx}).
445
+ */
446
+ triggers: TriggersCtx;
429
447
  provide(extensionPoint: ExtensionPointRef, impl: unknown): void;
430
448
  /**
431
449
  * The lifecycle signal of this plugin instance: aborted when the instance is revoked (disabled,
@@ -101,7 +101,8 @@ export declare const DEVICE_SERVICE_WORKSPACE_ENV = "CAPYBARA_SERVICE_WORKSPACE"
101
101
  * {@link DEVICE_SERVICE_INSTALL_SEAL} in it; from its next start on the directory is read only
102
102
  * for the service, so nothing the service later runs (a compromised browser included) can
103
103
  * replace what was installed. The provider empties it at every start that does not find it
104
- * sealed under the service's current files (unsealed, or a plugin upgrade since), so a service
104
+ * sealed under the service's current files (unsealed, or a plugin upgrade since; under its
105
+ * {@link DEVICE_SERVICE_INSTALL_KEY_FILE} where the service ships one), so a service
105
106
  * installs afresh while unsealed and never trusts what it finds there. The process that seals
106
107
  * keeps its write access until it exits, so a service runs no untrusted input (no web page) while
107
108
  * unsealed, seals only a complete install and then exits; the next start, reviewed again, runs it
@@ -110,6 +111,24 @@ export declare const DEVICE_SERVICE_WORKSPACE_ENV = "CAPYBARA_SERVICE_WORKSPACE"
110
111
  export declare const DEVICE_SERVICE_INSTALL_ENV = "CAPYBARA_SERVICE_INSTALL";
111
112
  /** The file that seals a service's install directory ({@link DEVICE_SERVICE_INSTALL_ENV}). */
112
113
  export declare const DEVICE_SERVICE_INSTALL_SEAL = ".sealed";
114
+ /**
115
+ * A service file naming what its install directory holds ({@link DEVICE_SERVICE_INSTALL_ENV}): one
116
+ * line matching {@link DEVICE_SERVICE_INSTALL_KEY_RE}, such as the browser revision. capybara-device
117
+ * (the device-local provider's machine program, capybara-hq/plugins#311) keeps such installs in a
118
+ * machine-wide cache of the OS user and keys them by it instead of by the service's files, so a
119
+ * plugin upgrade that keeps the key reuses the sealed install, and so do the other devices of the
120
+ * same deployment (its URL's origin and path) on that machine. Services of other deployments,
121
+ * platforms or launch environments never see it. The provider still hands an unsealed install out
122
+ * empty and private to one start, publishes it only once the service exits sealed (every link
123
+ * inside it, no hard link, no special file) and verifies it before every reuse. It assumes the
124
+ * unsealed install is the service's own code running no untrusted input, as the seal does: a
125
+ * child that left its process group could still write through an open file after the digest
126
+ * (the next reuse's verification catches it). Absent (or malformed): the install is keyed by the
127
+ * files.
128
+ */
129
+ export declare const DEVICE_SERVICE_INSTALL_KEY_FILE = "capybara-install-key";
130
+ /** What {@link DEVICE_SERVICE_INSTALL_KEY_FILE} holds: lower case, so it is one name on every file system. */
131
+ export declare const DEVICE_SERVICE_INSTALL_KEY_RE: RegExp;
113
132
  /**
114
133
  * Names the Mach service allowances the provider's sandbox gives the service (macOS: device-local
115
134
  * sets it, a spec cannot). Its value {@link DEVICE_SERVICE_MACH_CHROMIUM} means the full Chromium
@@ -119,7 +119,8 @@ export const DEVICE_SERVICE_WORKSPACE_ENV = "CAPYBARA_SERVICE_WORKSPACE";
119
119
  * {@link DEVICE_SERVICE_INSTALL_SEAL} in it; from its next start on the directory is read only
120
120
  * for the service, so nothing the service later runs (a compromised browser included) can
121
121
  * replace what was installed. The provider empties it at every start that does not find it
122
- * sealed under the service's current files (unsealed, or a plugin upgrade since), so a service
122
+ * sealed under the service's current files (unsealed, or a plugin upgrade since; under its
123
+ * {@link DEVICE_SERVICE_INSTALL_KEY_FILE} where the service ships one), so a service
123
124
  * installs afresh while unsealed and never trusts what it finds there. The process that seals
124
125
  * keeps its write access until it exits, so a service runs no untrusted input (no web page) while
125
126
  * unsealed, seals only a complete install and then exits; the next start, reviewed again, runs it
@@ -128,6 +129,24 @@ export const DEVICE_SERVICE_WORKSPACE_ENV = "CAPYBARA_SERVICE_WORKSPACE";
128
129
  export const DEVICE_SERVICE_INSTALL_ENV = "CAPYBARA_SERVICE_INSTALL";
129
130
  /** The file that seals a service's install directory ({@link DEVICE_SERVICE_INSTALL_ENV}). */
130
131
  export const DEVICE_SERVICE_INSTALL_SEAL = ".sealed";
132
+ /**
133
+ * A service file naming what its install directory holds ({@link DEVICE_SERVICE_INSTALL_ENV}): one
134
+ * line matching {@link DEVICE_SERVICE_INSTALL_KEY_RE}, such as the browser revision. capybara-device
135
+ * (the device-local provider's machine program, capybara-hq/plugins#311) keeps such installs in a
136
+ * machine-wide cache of the OS user and keys them by it instead of by the service's files, so a
137
+ * plugin upgrade that keeps the key reuses the sealed install, and so do the other devices of the
138
+ * same deployment (its URL's origin and path) on that machine. Services of other deployments,
139
+ * platforms or launch environments never see it. The provider still hands an unsealed install out
140
+ * empty and private to one start, publishes it only once the service exits sealed (every link
141
+ * inside it, no hard link, no special file) and verifies it before every reuse. It assumes the
142
+ * unsealed install is the service's own code running no untrusted input, as the seal does: a
143
+ * child that left its process group could still write through an open file after the digest
144
+ * (the next reuse's verification catches it). Absent (or malformed): the install is keyed by the
145
+ * files.
146
+ */
147
+ export const DEVICE_SERVICE_INSTALL_KEY_FILE = "capybara-install-key";
148
+ /** What {@link DEVICE_SERVICE_INSTALL_KEY_FILE} holds: lower case, so it is one name on every file system. */
149
+ export const DEVICE_SERVICE_INSTALL_KEY_RE = /^[a-z0-9][a-z0-9._+-]{0,127}$/;
131
150
  /**
132
151
  * Names the Mach service allowances the provider's sandbox gives the service (macOS: device-local
133
152
  * sets it, a spec cannot). Its value {@link DEVICE_SERVICE_MACH_CHROMIUM} means the full Chromium
@@ -21,6 +21,7 @@ export const EXTENSION_POINTS = {
21
21
  "file-preview": info([1], "Renders previews of files of given types: conversation files, shared files and skill files.", "multi", false, true),
22
22
  "web-search": info([1], "Searches the web for the WebSearch tool; each org picks a default provider.", "multi", true, true, "org-default"),
23
23
  context: info([1], "Adds text to the model's context at run start in conversations of orgs that enable it.", "multi", true, true),
24
+ "trigger-source": info([1], "Declares the events an extension emits and which people may see their subjects.", "multi", true, true),
24
25
  "web-fetch": info([1], "Fetches and extracts web pages for the WebFetch tool; each org picks a default provider.", "multi", true, true, "org-default"),
25
26
  "push-provider": info([1], "Delivers push notifications to people's mobile apps through one channel (APNs, FCM, an aggregator).", "multi", true),
26
27
  };
@@ -67,7 +67,11 @@ export interface FilePreviewConversationArgs extends FilePreviewArgsBase {
67
67
  source: "conversation";
68
68
  orgId: string;
69
69
  accountId: string;
70
- conversationId: string;
70
+ /**
71
+ * The conversation the file is previewed in; absent for a library file previewed outside a
72
+ * conversation (the Files page).
73
+ */
74
+ conversationId?: string;
71
75
  }
72
76
  /**
73
77
  * A preview on a share page: there is no account and no conversation. A previewer that needs the
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const SDK_VERSION = "0.1.0-rc.84";
1
+ export declare const SDK_VERSION = "0.1.0-rc.86";
2
2
  export * from "./agent-template.js";
3
3
  export * from "./avatar-presets.js";
4
4
  export * from "./bootstrap.js";
@@ -54,6 +54,8 @@ export * from "./theme-readability.js";
54
54
  export * from "./theme-tokens.generated.js";
55
55
  export * from "./tool.js";
56
56
  export * from "./tool-key.js";
57
+ export * from "./trigger-source.js";
58
+ export * from "./triggers.js";
57
59
  export * from "./ui.js";
58
60
  export * from "./ui-parts.js";
59
61
  export * from "./ui-resolve.js";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export const SDK_VERSION = "0.1.0-rc.84";
1
+ export const SDK_VERSION = "0.1.0-rc.86";
2
2
  export * from "./agent-template.js";
3
3
  export * from "./avatar-presets.js";
4
4
  export * from "./bootstrap.js";
@@ -54,6 +54,8 @@ export * from "./theme-readability.js";
54
54
  export * from "./theme-tokens.generated.js";
55
55
  export * from "./tool.js";
56
56
  export * from "./tool-key.js";
57
+ export * from "./trigger-source.js";
58
+ export * from "./triggers.js";
57
59
  export * from "./ui.js";
58
60
  export * from "./ui-parts.js";
59
61
  export * from "./ui-resolve.js";
package/dist/model.d.ts CHANGED
@@ -145,8 +145,8 @@ export declare const DOCUMENT_MEDIA_TYPES: readonly ["application/pdf", "text/pl
145
145
  export type ImageMediaType = (typeof IMAGE_MEDIA_TYPES)[number];
146
146
  export type DocumentMediaType = (typeof DOCUMENT_MEDIA_TYPES)[number];
147
147
  /**
148
- * The source of media content: `base64` is the bytes themselves, `ref` is a reference to a kernel
149
- * attachment.
148
+ * The source of media content: `base64` is the bytes themselves, `ref` names a kernel file by its
149
+ * id (a library file the conversation refers to, or a file the kernel stored for a tool result).
150
150
  * The event log stores only `ref` (bytes never enter the log); when building a request the kernel
151
151
  * resolves `ref` into `base64`, so plugins only ever receive `base64`.
152
152
  */
@@ -155,7 +155,7 @@ export type MediaSource = {
155
155
  data: string;
156
156
  } | {
157
157
  kind: "ref";
158
- attachmentId: string;
158
+ fileId: string;
159
159
  };
160
160
  /**
161
161
  * Upper bound on the decoded bytes of a single media block (the smaller value among mainstream
@@ -241,11 +241,13 @@ export declare function clipMediaName(name: string, max?: number): string;
241
241
  export declare function hasControlChars(s: string): boolean;
242
242
  /** Whether the attachment id is a UUID (any version, case-insensitive). */
243
243
  export declare function isAttachmentId(s: unknown): s is string;
244
+ /** Whether the file id (a media `ref`'s `fileId`) is a UUID (any version, case-insensitive). */
245
+ export declare function isFileId(s: unknown): s is string;
244
246
  /**
245
247
  * Validates an image / document / file block, returning a list of errors (empty means valid): the
246
248
  * media type is in the block kind's list (`file` accepts any non-empty `type/subtype`); `base64` is
247
249
  * standard, padded, whitespace-free base64 that decodes to at most {@link MEDIA_LIMITS}; a `ref`'s
248
- * `attachmentId` is a UUID; `name`, when present, is a string of at most
250
+ * `fileId` is a UUID; `name`, when present, is a string of at most
249
251
  * {@link MEDIA_NAME_MAX_CHARS} characters with no control characters; `size`, when present, is a
250
252
  * non-negative integer (display metadata, never sent by a plugin).
251
253
  */
package/dist/model.js CHANGED
@@ -110,6 +110,10 @@ export function hasControlChars(s) {
110
110
  export function isAttachmentId(s) {
111
111
  return typeof s === "string" && UUID_RE.test(s);
112
112
  }
113
+ /** Whether the file id (a media `ref`'s `fileId`) is a UUID (any version, case-insensitive). */
114
+ export function isFileId(s) {
115
+ return typeof s === "string" && UUID_RE.test(s);
116
+ }
113
117
  /** Any non-empty `type/subtype` (a `file` block's `mediaType`). */
114
118
  const MEDIA_TYPE_RE = /^[^/\s]+\/[^/\s]+$/;
115
119
  const MEDIA = {
@@ -123,7 +127,7 @@ const MEDIA = {
123
127
  * Validates an image / document / file block, returning a list of errors (empty means valid): the
124
128
  * media type is in the block kind's list (`file` accepts any non-empty `type/subtype`); `base64` is
125
129
  * standard, padded, whitespace-free base64 that decodes to at most {@link MEDIA_LIMITS}; a `ref`'s
126
- * `attachmentId` is a UUID; `name`, when present, is a string of at most
130
+ * `fileId` is a UUID; `name`, when present, is a string of at most
127
131
  * {@link MEDIA_NAME_MAX_CHARS} characters with no control characters; `size`, when present, is a
128
132
  * non-negative integer (display metadata, never sent by a plugin).
129
133
  */
@@ -166,8 +170,8 @@ export function validateMediaBlock(b) {
166
170
  }
167
171
  const source = src;
168
172
  if (source.kind === "ref") {
169
- if (!isAttachmentId(source.attachmentId)) {
170
- errs.push(`${o.type} source.attachmentId must be a UUID`);
173
+ if (!isFileId(source.fileId)) {
174
+ errs.push(`${o.type} source.fileId must be a UUID file id`);
171
175
  }
172
176
  }
173
177
  else if (source.kind === "base64") {
@@ -76,6 +76,13 @@ export interface ExtensionPermissions {
76
76
  deviceAccess?: {
77
77
  services: string[];
78
78
  };
79
+ /**
80
+ * `ctx.triggers`: the event types this extension may emit (at most {@link TRIGGER_MAX_TYPES},
81
+ * each matching {@link TRIGGER_TYPE_RE}). An emit of another type is refused.
82
+ */
83
+ triggers?: {
84
+ emit: string[];
85
+ };
79
86
  }
80
87
  /** The most services `permissions.deviceAccess.services` may list. */
81
88
  export declare const DEVICE_ACCESS_MAX_SERVICES = 4;
@@ -3,7 +3,8 @@ import { DIAL_IN_PROTOCOL_RE } from "./dial-in.js";
3
3
  import { POLICY_HOOKS } from "./hooks.js";
4
4
  import { HTTP_ACCESS } from "./http-access.js";
5
5
  import { SETUP_CHECK_ID_RE, SETUP_CHECK_LIMITS } from "./setup-check.js";
6
- import { UI_ICONS } from "./ui.js";
6
+ import { TRIGGER_MAX_TYPES, TRIGGER_TYPE_RE } from "./triggers.js";
7
+ import { UI_ICONS, UI_PAGE_FRAMES, UI_PAGE_NAVS } from "./ui.js";
7
8
  import { isCompactForm, parseSlotRef, uiSlot } from "./ui-slots.js";
8
9
  /** The most services `permissions.deviceAccess.services` may list. */
9
10
  export const DEVICE_ACCESS_MAX_SERVICES = 4;
@@ -50,6 +51,7 @@ const KEYS = new Set([
50
51
  "setupChecks",
51
52
  "dialIn",
52
53
  "deviceAccess",
54
+ "triggers",
53
55
  ]);
54
56
  const POLICY = new Set(POLICY_HOOKS);
55
57
  const METHODS = new Set(["GET", "POST", "PUT", "DELETE"]);
@@ -235,6 +237,20 @@ export function validatePermissions(plugin, p, provides = []) {
235
237
  }
236
238
  }
237
239
  }
240
+ if (p.triggers !== undefined) {
241
+ if (!isObj(p.triggers) || Object.keys(p.triggers).some((k) => k !== "emit")) {
242
+ errs.push("permissions.triggers must be { emit: string[] }");
243
+ }
244
+ else {
245
+ const types = strList("permissions.triggers.emit", p.triggers.emit, errs);
246
+ if (types.length > TRIGGER_MAX_TYPES)
247
+ errs.push(`permissions.triggers.emit lists at most ${TRIGGER_MAX_TYPES} types`);
248
+ for (const t of types) {
249
+ if (!TRIGGER_TYPE_RE.test(t))
250
+ errs.push(`permissions.triggers.emit entry "${t}" must match ${TRIGGER_TYPE_RE}`);
251
+ }
252
+ }
253
+ }
238
254
  return errs;
239
255
  }
240
256
  const UI_ID_RE = /^[a-z][a-z0-9-]{0,39}$/;
@@ -327,6 +343,20 @@ export function validateUiContributions(ui, permissions) {
327
343
  if (seen.has(id))
328
344
  errs.push(`ui has duplicate id "${id}"`);
329
345
  seen.set(id, c.kind);
346
+ if (c.frame !== undefined || c.nav !== undefined) {
347
+ const onPage = slotRef?.id === "org.page" && c.kind === "component";
348
+ for (const [k, allowed] of [
349
+ ["frame", UI_PAGE_FRAMES],
350
+ ["nav", UI_PAGE_NAVS],
351
+ ]) {
352
+ if (c[k] === undefined)
353
+ continue;
354
+ if (!onPage)
355
+ errs.push(`ui "${id}" ${k} is only allowed on a component of the org.page slot`);
356
+ else if (!allowed.includes(c[k]))
357
+ errs.push(`ui "${id}" ${k} must be one of ${allowed.join(", ")}`);
358
+ }
359
+ }
330
360
  if (c.kind === "view") {
331
361
  if (c.path !== undefined)
332
362
  errs.push(`ui "${id}" path is only allowed for kind embed`);
@@ -0,0 +1,35 @@
1
+ import type { ExtensionPointRef } from "./extension-point.js";
2
+ import type { LocalizedName } from "./plugin-package.js";
3
+ import type { TriggerSubject } from "./triggers.js";
4
+ /** One fact of an event type: its value type and whether automations may filter on it. */
5
+ export interface TriggerFactDeclaration {
6
+ type: "string" | "number" | "boolean" | "string[]";
7
+ name: LocalizedName;
8
+ filterable: boolean;
9
+ }
10
+ /** One event type an extension emits, shown when an org builds an automation. */
11
+ export interface TriggerEventDeclaration {
12
+ type: string;
13
+ name: LocalizedName;
14
+ /** Directed events wake one agent (`TriggerEvent.audience`) instead of every subscriber. */
15
+ directed: boolean;
16
+ facts: Record<string, TriggerFactDeclaration>;
17
+ }
18
+ /** What a `trigger-source@1` provider implements. */
19
+ export interface TriggerSource {
20
+ events(): TriggerEventDeclaration[];
21
+ /** Of `accountIds`, the accounts that may see `subject`. */
22
+ visible(args: {
23
+ orgId: string;
24
+ accountIds: string[];
25
+ subject: TriggerSubject;
26
+ config?: unknown;
27
+ }): Promise<string[]>;
28
+ /** A link a person can open for the subject, or null. */
29
+ subjectLink?(args: {
30
+ orgId: string;
31
+ subject: TriggerSubject;
32
+ }): Promise<string | null>;
33
+ }
34
+ /** Trigger source extension point ref. */
35
+ export declare const TRIGGER_SOURCE_EXTENSION_POINT: ExtensionPointRef;
@@ -0,0 +1,2 @@
1
+ /** Trigger source extension point ref. */
2
+ export const TRIGGER_SOURCE_EXTENSION_POINT = "trigger-source@1";
@@ -0,0 +1,72 @@
1
+ import type { ToolCallContext } from "./tool.js";
2
+ /** The value of one fact on a trigger event: filters compare facts, never free text. */
3
+ export type TriggerFactValue = string | number | boolean | string[];
4
+ /** What an event is about (a task, a document, ...). */
5
+ export interface TriggerSubject {
6
+ kind: string;
7
+ id: string;
8
+ title: string;
9
+ url?: string;
10
+ }
11
+ /** Who caused an event: a tool call of the extension, or an account acting outside a call. */
12
+ export type TriggerCause = {
13
+ call: ToolCallContext;
14
+ } | {
15
+ accountId: string;
16
+ };
17
+ /** An event an extension emits through `ctx.triggers.emit`. */
18
+ export interface TriggerEvent {
19
+ orgId: string;
20
+ /** One of the types the extension declares in `permissions.triggers.emit`. */
21
+ type: string;
22
+ subject: TriggerSubject;
23
+ facts: Record<string, TriggerFactValue>;
24
+ /** Short text for the agent; at most {@link TRIGGER_SUMMARY_MAX_BYTES} UTF-8 bytes. */
25
+ summary: string;
26
+ /** Idempotency key: the same key for the same type and org emits once. */
27
+ dedupeKey: string;
28
+ cause?: TriggerCause;
29
+ /** A directed event: only this agent of this account is woken. */
30
+ audience?: {
31
+ accountId: string;
32
+ agentId: string;
33
+ };
34
+ }
35
+ export interface EventFilterClause {
36
+ fact: string;
37
+ op: "eq" | "in" | "contains";
38
+ value: TriggerFactValue;
39
+ }
40
+ /** A conjunction: every clause must match. An empty filter matches every event. */
41
+ export type EventFilter = EventFilterClause[];
42
+ /** `ctx.triggers` (requires `permissions.triggers`). */
43
+ export interface TriggersCtx {
44
+ emit(event: TriggerEvent): Promise<{
45
+ eventId: string;
46
+ duplicate: boolean;
47
+ }>;
48
+ }
49
+ export type TriggerErrorCode = "type_not_declared" | "invalid_event" | "org_disabled";
50
+ /** A {@link TriggersCtx} call was refused. */
51
+ export declare class TriggerError extends Error {
52
+ readonly code: TriggerErrorCode;
53
+ constructor(code: TriggerErrorCode, message: string, opts?: {
54
+ cause?: unknown;
55
+ });
56
+ }
57
+ export declare const TRIGGER_SUMMARY_MAX_BYTES = 4096;
58
+ /** The shape of a trigger event type name (also the entries of `permissions.triggers.emit`). */
59
+ export declare const TRIGGER_TYPE_RE: RegExp;
60
+ /** Most event types one extension may declare. */
61
+ export declare const TRIGGER_MAX_TYPES = 64;
62
+ /**
63
+ * Checks an event before it is stored; returns error codes (empty = valid): `type_not_declared`,
64
+ * `summary_too_long` (UTF-8 bytes), and `missing_<field>` for each empty required field.
65
+ */
66
+ export declare function validateTriggerEvent(e: TriggerEvent, declared: readonly string[]): string[];
67
+ /**
68
+ * Whether the facts satisfy every clause. A missing fact never matches. `eq` compares scalars (an
69
+ * array fact never matches); `in` takes an array value and matches a scalar fact contained in it;
70
+ * `contains` matches an array fact containing the scalar value.
71
+ */
72
+ export declare function matchesFilter(filter: EventFilter, facts: Record<string, TriggerFactValue>): boolean;
@@ -0,0 +1,71 @@
1
+ /** A {@link TriggersCtx} call was refused. */
2
+ export class TriggerError extends Error {
3
+ code;
4
+ constructor(code, message, opts) {
5
+ super(message, opts && "cause" in opts ? { cause: opts.cause } : undefined);
6
+ this.name = "TriggerError";
7
+ this.code = code;
8
+ }
9
+ }
10
+ export const TRIGGER_SUMMARY_MAX_BYTES = 4096;
11
+ /** The shape of a trigger event type name (also the entries of `permissions.triggers.emit`). */
12
+ export const TRIGGER_TYPE_RE = /^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$/;
13
+ /** Most event types one extension may declare. */
14
+ export const TRIGGER_MAX_TYPES = 64;
15
+ /**
16
+ * Checks an event before it is stored; returns error codes (empty = valid): `type_not_declared`,
17
+ * `summary_too_long` (UTF-8 bytes), and `missing_<field>` for each empty required field.
18
+ */
19
+ export function validateTriggerEvent(e, declared) {
20
+ const errs = [];
21
+ const blank = (v) => typeof v !== "string" || v === "";
22
+ if (blank(e.orgId))
23
+ errs.push("missing_org_id");
24
+ if (blank(e.type))
25
+ errs.push("missing_type");
26
+ else if (!declared.includes(e.type))
27
+ errs.push("type_not_declared");
28
+ if (blank(e.subject?.kind))
29
+ errs.push("missing_subject_kind");
30
+ if (blank(e.subject?.id))
31
+ errs.push("missing_subject_id");
32
+ if (blank(e.subject?.title))
33
+ errs.push("missing_subject_title");
34
+ if (blank(e.dedupeKey))
35
+ errs.push("missing_dedupe_key");
36
+ if (typeof e.summary !== "string")
37
+ errs.push("missing_summary");
38
+ else if (new TextEncoder().encode(e.summary).length > TRIGGER_SUMMARY_MAX_BYTES)
39
+ errs.push("summary_too_long");
40
+ return errs;
41
+ }
42
+ /**
43
+ * Whether the facts satisfy every clause. A missing fact never matches. `eq` compares scalars (an
44
+ * array fact never matches); `in` takes an array value and matches a scalar fact contained in it;
45
+ * `contains` matches an array fact containing the scalar value.
46
+ */
47
+ export function matchesFilter(filter, facts) {
48
+ return filter.every((c) => {
49
+ if (!Object.hasOwn(facts, c.fact))
50
+ return false;
51
+ const f = facts[c.fact];
52
+ if (f === undefined)
53
+ return false;
54
+ switch (c.op) {
55
+ case "eq":
56
+ return !Array.isArray(f) && !Array.isArray(c.value) && f === c.value;
57
+ case "in":
58
+ return (Array.isArray(c.value) &&
59
+ !Array.isArray(f) &&
60
+ typeof f === "string" &&
61
+ c.value.includes(f));
62
+ case "contains":
63
+ return (Array.isArray(f) &&
64
+ !Array.isArray(c.value) &&
65
+ typeof c.value === "string" &&
66
+ f.includes(c.value));
67
+ default:
68
+ return false;
69
+ }
70
+ });
71
+ }
package/dist/ui-slots.js CHANGED
@@ -85,13 +85,13 @@ const SLOT_DATA = [
85
85
  accepts: ["view", "embed", "component"],
86
86
  cardinality: "list",
87
87
  minRole: "member",
88
- args: [],
88
+ args: ["params"],
89
89
  density: "regular",
90
90
  icon: "optional",
91
91
  compact: "kept",
92
92
  description: {
93
- en: "A full page in the organization navigation.",
94
- zh: "组织导航中的完整页面。",
93
+ en: "A full page in the organization navigation. Only component contributions receive `params` (the page query string); views and embeds do not.",
94
+ zh: "组织导航中的完整页面。只有 component 贡献会收到 `params`(页面查询串),view 与 embed 不会。",
95
95
  },
96
96
  },
97
97
  {
package/dist/ui.d.ts CHANGED
@@ -55,7 +55,26 @@ export interface UiContribution {
55
55
  * see `effectiveCompact`. Omitted = the slot's form.
56
56
  */
57
57
  compact?: CompactForm;
58
+ /**
59
+ * `org.page` component only. `"host"` (default): the host draws the page title and the page
60
+ * chrome around the component; `"page"`: the component draws the whole page itself.
61
+ */
62
+ frame?: UiPageFrame;
63
+ /**
64
+ * `org.page` component only, a suggestion an org admin's saved choice beats. `"more"`
65
+ * (default): listed under the navigation's more entry; `"primary"`: listed in the primary
66
+ * navigation (at most 3 plugin pages there).
67
+ */
68
+ nav?: UiPageNav;
58
69
  }
70
+ /** How an `org.page` component page is framed ({@link UiContribution.frame}). */
71
+ export type UiPageFrame = "host" | "page";
72
+ /** Where an `org.page` component page is listed ({@link UiContribution.nav}). */
73
+ export type UiPageNav = "primary" | "more";
74
+ /** The accepted values of {@link UiContribution.frame}. */
75
+ export declare const UI_PAGE_FRAMES: readonly UiPageFrame[];
76
+ /** The accepted values of {@link UiContribution.nav}. */
77
+ export declare const UI_PAGE_NAVS: readonly UiPageNav[];
59
78
  /**
60
79
  * Blocks of the render schema. Text is for humans and shown as is (the plugin decides the language
61
80
  * itself, usually taking `locale`).
@@ -154,6 +173,11 @@ export interface UiView {
154
173
  * - `textChars`: total characters of all text in the whole view (form JSON included);
155
174
  * - `payloadBytes`: UTF-8 bytes of a single button `payload` after JSON serialization.
156
175
  * - `componentDataBytes`: the UTF-8 bytes of a component view's `data` as JSON.
176
+ * - `componentQueryBytes`: the UTF-8 bytes of a `ctx.ui.query` result as JSON.
177
+ * - `componentQueryParamsBytes`: the UTF-8 bytes of a query's `params` as JSON.
178
+ * - `componentActionPayloadBytes`: the UTF-8 bytes of a component action's `payload` as JSON
179
+ * (view block buttons keep `payloadBytes`).
180
+ * - `pageParamsBytes`: the UTF-8 bytes of a page's URL params (all keys and values).
157
181
  */
158
182
  export declare const UI_LIMITS: {
159
183
  readonly blocks: 50;
@@ -162,6 +186,10 @@ export declare const UI_LIMITS: {
162
186
  readonly textChars: 20000;
163
187
  readonly payloadBytes: 2000;
164
188
  readonly componentDataBytes: 32768;
189
+ readonly componentQueryBytes: 1048576;
190
+ readonly componentQueryParamsBytes: 16384;
191
+ readonly componentActionPayloadBytes: 65536;
192
+ readonly pageParamsBytes: 2048;
165
193
  };
166
194
  /**
167
195
  * Validates the view a plugin returns and returns the list of problems (empty = valid). Links and
@@ -265,14 +293,29 @@ export interface UiPlatformActionArgs extends UiPlatformRenderArgs, UiActionInpu
265
293
  * `answer`.
266
294
  */
267
295
  export type UiActionArgs = UiOrgActionArgs | UiPlatformActionArgs;
268
- /** An action result: a notice, or a new view. */
296
+ /**
297
+ * The args of a `ctx.ui.query` handler: the org position of the call, the query id and its params
298
+ * (JSON of at most `UI_LIMITS.componentQueryParamsBytes` bytes). `signal` aborts when the caller
299
+ * goes away.
300
+ */
301
+ export interface UiQueryArgs extends UiOrgRenderArgs {
302
+ query: string;
303
+ params: JsonValue;
304
+ signal: AbortSignal;
305
+ }
306
+ /**
307
+ * An action result: a notice, or a new view. `invalidate` names queries the host refetches
308
+ * (component actions only).
309
+ */
269
310
  export type UiActionResult = {
270
311
  toast?: {
271
312
  zh: string;
272
313
  en: string;
273
314
  };
315
+ invalidate?: string[];
274
316
  } | {
275
317
  view: UiView;
318
+ invalidate?: string[];
276
319
  };
277
320
  /** The embed claims every scope shares. `exp` is Unix seconds. */
278
321
  export interface EmbedClaimsBase {
@@ -293,7 +336,10 @@ export interface OrgEmbedClaims extends EmbedClaimsBase {
293
336
  conversationId?: string;
294
337
  /** Only an agent embed's token (`agent.detail.section`): the agent it was issued for. */
295
338
  agentId?: string;
296
- /** Only a `file-preview` embed's token: the one file (of `conversationId`) it previews. */
339
+ /**
340
+ * Only a `file-preview` embed's token: the one file it previews, of `conversationId`, or without
341
+ * one a library file of `accountId`'s own.
342
+ */
297
343
  fileId?: string;
298
344
  /**
299
345
  * Only a `file-preview` embed's token for a skill file (no `conversationId`, `agentId` or
package/dist/ui.js CHANGED
@@ -17,6 +17,10 @@ export const UI_ICONS = [
17
17
  "globe",
18
18
  "puzzle",
19
19
  ];
20
+ /** The accepted values of {@link UiContribution.frame}. */
21
+ export const UI_PAGE_FRAMES = ["host", "page"];
22
+ /** The accepted values of {@link UiContribution.nav}. */
23
+ export const UI_PAGE_NAVS = ["primary", "more"];
20
24
  /**
21
25
  * View limits (checked uniformly by {@link validateUiView}):
22
26
  * - `blocks`: number of blocks;
@@ -26,6 +30,11 @@ export const UI_ICONS = [
26
30
  * - `textChars`: total characters of all text in the whole view (form JSON included);
27
31
  * - `payloadBytes`: UTF-8 bytes of a single button `payload` after JSON serialization.
28
32
  * - `componentDataBytes`: the UTF-8 bytes of a component view's `data` as JSON.
33
+ * - `componentQueryBytes`: the UTF-8 bytes of a `ctx.ui.query` result as JSON.
34
+ * - `componentQueryParamsBytes`: the UTF-8 bytes of a query's `params` as JSON.
35
+ * - `componentActionPayloadBytes`: the UTF-8 bytes of a component action's `payload` as JSON
36
+ * (view block buttons keep `payloadBytes`).
37
+ * - `pageParamsBytes`: the UTF-8 bytes of a page's URL params (all keys and values).
29
38
  */
30
39
  export const UI_LIMITS = {
31
40
  blocks: 50,
@@ -34,6 +43,10 @@ export const UI_LIMITS = {
34
43
  textChars: 20000,
35
44
  payloadBytes: 2000,
36
45
  componentDataBytes: 32768,
46
+ componentQueryBytes: 1048576,
47
+ componentQueryParamsBytes: 16384,
48
+ componentActionPayloadBytes: 65536,
49
+ pageParamsBytes: 2048,
37
50
  };
38
51
  const BADGE_MAX = 32;
39
52
  /** Longest item / block `id` and open target `item`. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/plugin-sdk",
3
- "version": "0.1.0-rc.84",
3
+ "version": "0.1.0-rc.86",
4
4
  "description": "Capybara plugin SDK: the types and pure functions plugins are written against",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {