@capybara-hq/plugin-sdk 0.1.0-rc.81 → 0.1.0-rc.83

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.
package/dist/cards.d.ts CHANGED
@@ -39,8 +39,12 @@ export type ChannelCard = {
39
39
  kind: "question";
40
40
  id: string;
41
41
  form: InputForm;
42
- /** `skipped`: the person sent a message instead of answering (the run went on with it). */
43
- state: "pending" | "answered" | "skipped" | "expired" | "cancelled";
42
+ /**
43
+ * `skipped`: the person sent a message instead of answering (the run went on with it).
44
+ * `woken`: a watched wait the tool's watcher ended (the condition it waited for held, or the
45
+ * wait could no longer be watched); nobody answered.
46
+ */
47
+ state: "pending" | "answered" | "skipped" | "expired" | "cancelled" | "woken";
44
48
  answerSummary?: string;
45
49
  webUrl: string;
46
50
  /**
@@ -124,6 +128,26 @@ export interface OutboundMessage {
124
128
  export declare function questionRenderableInline(form: InputForm, opts?: {
125
129
  textReply?: boolean;
126
130
  }): boolean;
131
+ /** One button of a question's `choices`, as {@link questionChoiceButtons} resolves it. */
132
+ export interface QuestionChoiceButton {
133
+ /** The answer the button submits for the form's single field. */
134
+ value: string | boolean;
135
+ /** The label in the locale. */
136
+ label: string;
137
+ /** True for the first choice only. */
138
+ primary: boolean;
139
+ }
140
+ /**
141
+ * The buttons of a form with `choices` (core#867): one per choice in order, the first primary; a
142
+ * click answers the form's single field `key` with the button's `value` at once. Undefined when
143
+ * the form has no choices (use {@link questionRenderableInline} for the enum controls).
144
+ */
145
+ export declare function questionChoiceButtons(form: InputForm, locale: Locale): {
146
+ key: string;
147
+ buttons: QuestionChoiceButton[];
148
+ } | undefined;
149
+ /** The form's body text in the locale (the explanation under its title); undefined without one. */
150
+ export declare function questionBody(form: InputForm, locale: Locale): string | undefined;
127
151
  /** Validates the card structure and returns the list of problems (empty = valid). */
128
152
  export declare function validateChannelCard(card: unknown): string[];
129
153
  /** A UI locale. */
package/dist/cards.js CHANGED
@@ -12,6 +12,8 @@ export function questionRenderableInline(form, opts) {
12
12
  if (form.fields.length !== 1)
13
13
  return false;
14
14
  const f = form.fields[0];
15
+ if (f?.choices !== undefined && f.choices.length > 0)
16
+ return true;
15
17
  if (!f || (f.allowOther && opts?.textReply !== true))
16
18
  return false;
17
19
  if (f.schema.type !== "string" || !("enum" in f.schema))
@@ -19,6 +21,29 @@ export function questionRenderableInline(form, opts) {
19
21
  const n = f.schema.enum.length;
20
22
  return f.multiSelect ? n <= MAX_INLINE_MULTI : n <= MAX_INLINE_SINGLE;
21
23
  }
24
+ const pickText = (t, locale) => typeof t === "string" ? t : (t[locale] ?? t.en);
25
+ /**
26
+ * The buttons of a form with `choices` (core#867): one per choice in order, the first primary; a
27
+ * click answers the form's single field `key` with the button's `value` at once. Undefined when
28
+ * the form has no choices (use {@link questionRenderableInline} for the enum controls).
29
+ */
30
+ export function questionChoiceButtons(form, locale) {
31
+ const f = form.fields[0];
32
+ if (form.fields.length !== 1 || !f?.choices || f.choices.length === 0)
33
+ return undefined;
34
+ return {
35
+ key: f.key,
36
+ buttons: f.choices.map((c, i) => ({
37
+ value: c.value,
38
+ label: pickText(c.label, locale),
39
+ primary: i === 0,
40
+ })),
41
+ };
42
+ }
43
+ /** The form's body text in the locale (the explanation under its title); undefined without one. */
44
+ export function questionBody(form, locale) {
45
+ return form.body === undefined ? undefined : pickText(form.body, locale);
46
+ }
22
47
  const KINDS = ["approval", "question", "connect", "bind", "progress"];
23
48
  const PROGRESS_STATES = ["running", "waiting", "finished", "stopped", "failed"];
24
49
  const SCOPES = ["once", "session", "always"];
@@ -31,7 +56,14 @@ const APPROVAL_STATES = [
31
56
  "skipped",
32
57
  ];
33
58
  const MAX_SCOPE_LABEL = 40;
34
- const QUESTION_STATES = ["pending", "answered", "skipped", "expired", "cancelled"];
59
+ const QUESTION_STATES = [
60
+ "pending",
61
+ "answered",
62
+ "skipped",
63
+ "expired",
64
+ "cancelled",
65
+ "woken",
66
+ ];
35
67
  const TEXT_REPLY = ["plain", "mention"];
36
68
  const ISO_8601 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
37
69
  const list = (xs) => xs.map((x) => JSON.stringify(x)).join(", ");
@@ -199,6 +231,7 @@ const TEXT = {
199
231
  skipped: "Skipped (replied instead)",
200
232
  expired: "Expired",
201
233
  cancelled: "Cancelled",
234
+ woken: "Wait ended",
202
235
  },
203
236
  textReply: {
204
237
  plain: "You can also just reply with text",
@@ -237,6 +270,7 @@ const TEXT = {
237
270
  skipped: "已跳过(已直接回复)",
238
271
  expired: "已过期",
239
272
  cancelled: "已取消",
273
+ woken: "等待已结束",
240
274
  },
241
275
  textReply: {
242
276
  plain: "也可以直接回复文字",
@@ -295,6 +329,12 @@ export function renderCardAsText(card, locale) {
295
329
  withCode(t.question, asCode(title)),
296
330
  line(t.status, questionStateLabel(card.state, locale)),
297
331
  ];
332
+ const body = questionBody(card.form, locale);
333
+ if (body !== undefined)
334
+ lines.push(withCode("", asCode(body)));
335
+ const choices = card.state === "pending" ? questionChoiceButtons(card.form, locale) : undefined;
336
+ if (choices)
337
+ lines.push(line(t.options, choices.buttons.map((b) => asCode(b.label)).join(" / ")));
298
338
  if (card.answerSummary)
299
339
  lines.push(line(t.answer, asCode(card.answerSummary)));
300
340
  lines.push(line(card.state === "pending" ? t.answerOnWeb : t.details, card.webUrl));
package/dist/ctx.d.ts CHANGED
@@ -8,7 +8,7 @@ import type { ImageAspectRatio, ImageMediaType, ImageSize, ModelEmbeddingInfo, M
8
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
- import type { ToolCallContext, ToolHandler, ToolSpec } from "./tool.js";
11
+ import type { ToolCallContext, ToolHandler, ToolSpec, ToolWatcher } from "./tool.js";
12
12
  import type { EmbedClaims, UiActionArgs, UiActionResult, UiRenderArgs, UiView } from "./ui.js";
13
13
  /** Logger interface. */
14
14
  export interface Logger {
@@ -195,11 +195,17 @@ export interface DeviceAccessCtx {
195
195
  * closed) and starts it through the device's provider.
196
196
  */
197
197
  ensureService(call: ToolCallContext, spec: DeviceServiceSpec): Promise<DeviceServiceStatus>;
198
- /** One request to the service's socket; resolves its answer. */
198
+ /**
199
+ * One request to the service's socket; resolves its answer. `ifRunning`: only a running
200
+ * instance with the service running answers, otherwise {@link DeviceAccessError}
201
+ * `not_running`; nothing is resumed or started (a running instance's last use is refreshed). A
202
+ * watcher's requests ({@link ToolWatcher}) always run so.
203
+ */
199
204
  request(call: ToolCallContext, req: {
200
205
  service: string;
201
206
  body: Uint8Array;
202
207
  timeoutMs: number;
208
+ ifRunning?: boolean;
203
209
  }): Promise<Uint8Array>;
204
210
  /**
205
211
  * The service saw requests to `hosts` refused by the device's network during this call, each
@@ -249,7 +255,9 @@ export interface DeviceAccessCtx {
249
255
  }): Promise<void>;
250
256
  }
251
257
  /** Why a {@link DeviceAccessCtx} call was refused. */
252
- export type DeviceAccessErrorCode = "no_device" | "provider_unavailable" | "capability_missing" | "not_owner" | "service_not_declared";
258
+ export type DeviceAccessErrorCode = "no_device" | "provider_unavailable" | "capability_missing" | "not_owner" | "service_not_declared"
259
+ /** An `ifRunning` request found the device's instance or the service not running. */
260
+ | "not_running";
253
261
  /** A {@link DeviceAccessCtx} call was refused; the message is actionable English for the model. */
254
262
  export declare class DeviceAccessError extends Error {
255
263
  readonly code: DeviceAccessErrorCode;
@@ -314,8 +322,13 @@ export interface ExtensionContext {
314
322
  route(method: "GET" | "POST" | "PUT" | "DELETE", path: string, handler: (req: Request, caller: RouteCaller) => Promise<Response>): void;
315
323
  };
316
324
  tools: {
317
- /** Registers a tool; callable only during `setup`, names must not repeat. */
318
- register(spec: ToolSpec, handler: ToolHandler): void;
325
+ /**
326
+ * Registers a tool; callable only during `setup`, names must not repeat. `opts.watch`: the
327
+ * tool's watcher for watched waits (`InputRequired.watch`, see {@link ToolWatcher}).
328
+ */
329
+ register(spec: ToolSpec, handler: ToolHandler, opts?: {
330
+ watch?: ToolWatcher;
331
+ }): void;
319
332
  };
320
333
  /**
321
334
  * Consume extension points provided by other extensions: only non-brokered refs declared in the
@@ -25,6 +25,10 @@
25
25
  * ({@link parseViewerContext}); a later message of the same shape comes from the panel and is
26
26
  * never context. Providers and the device program pass the viewer context through like any
27
27
  * stream message.
28
+ *
29
+ * **Kernel requests.** Besides the extension's own requests (`ctx.deviceAccess.request`), the
30
+ * kernel sends two request bodies of its own: the roll check ({@link DEVICE_SERVICE_ROLL_CHECK})
31
+ * and the conversation-deleted notice ({@link encodeConversationDeleted}).
28
32
  */
29
33
  /**
30
34
  * The request body the kernel sends a running service before restarting it on new files (an
@@ -47,6 +51,40 @@ export interface DeviceServiceRollCheck {
47
51
  export declare function isRollCheck(body: Uint8Array | string): boolean;
48
52
  /** Reads a service's answer to the roll check: busy only for `{"busy":true}` (never throws). */
49
53
  export declare function parseRollCheck(body: Uint8Array | string): DeviceServiceRollCheck;
54
+ /**
55
+ * How long a service may restore state it saved (after a restart, or when its device resumes):
56
+ * state saved longer ago than this is not restored. The kernel keeps a
57
+ * {@link encodeConversationDeleted} notice owed for at least this long after the deletion while
58
+ * the service is not running, so a service that restores within it still learns of the deletion.
59
+ */
60
+ export declare const DEVICE_SERVICE_RESTORE_MAX_AGE_MS: number;
61
+ /**
62
+ * The kernel's notice that a conversation was deleted: a request body the kernel sends every
63
+ * running service of an extension on the deleted conversation's device, at least once, soon after
64
+ * the deletion (a device that is offline gets it when it is back; a service that is stopped gets
65
+ * it when it runs again within {@link DEVICE_SERVICE_RESTORE_MAX_AGE_MS}). The kernel builds it
66
+ * from the deleted conversation's id. It arrives on a **request** connection only: a stream
67
+ * message of this shape is a viewer's (panel) input and never the notice, so a service parses it
68
+ * only on request connections. As with the roll check, the extension's own requests
69
+ * (`ctx.deviceAccess.request`) reach the same connection kind: a body of this shape sent by the
70
+ * extension is the extension's to answer for. The service forgets what it keeps for that
71
+ * conversation and for the conversations whose tree root it is (closes their pages, drops their
72
+ * state; never shared data such as a browser profile) and answers with any message: the kernel
73
+ * reads no more than that it answered. Handling it twice must be harmless. A service that does
74
+ * not know it ignores it, as any unknown body.
75
+ */
76
+ export interface DeviceServiceConversationDeleted {
77
+ capybara: "conversation-deleted";
78
+ conversationId: string;
79
+ }
80
+ /** The body of the kernel's conversation-deleted notice (UTF-8 JSON; the provider frames it). */
81
+ export declare function encodeConversationDeleted(conversationId: string): Uint8Array;
82
+ /**
83
+ * Reads a request body as the kernel's conversation-deleted notice: `capybara` is
84
+ * `"conversation-deleted"` and `conversationId` a non-empty string. Null for anything else (not
85
+ * UTF-8, not JSON, another shape, the roll check); never throws.
86
+ */
87
+ export declare function parseConversationDeleted(body: Uint8Array | string): DeviceServiceConversationDeleted | null;
50
88
  /** Names the unix socket path the service listens on. */
51
89
  export declare const DEVICE_SERVICE_SOCKET_ENV = "CAPYBARA_SERVICE_SOCKET";
52
90
  /** Names the service's state directory (its own data, its write root; not where its code is). */
@@ -25,6 +25,10 @@
25
25
  * ({@link parseViewerContext}); a later message of the same shape comes from the panel and is
26
26
  * never context. Providers and the device program pass the viewer context through like any
27
27
  * stream message.
28
+ *
29
+ * **Kernel requests.** Besides the extension's own requests (`ctx.deviceAccess.request`), the
30
+ * kernel sends two request bodies of its own: the roll check ({@link DEVICE_SERVICE_ROLL_CHECK})
31
+ * and the conversation-deleted notice ({@link encodeConversationDeleted}).
28
32
  */
29
33
  /**
30
34
  * The request body the kernel sends a running service before restarting it on new files (an
@@ -63,6 +67,42 @@ export function parseRollCheck(body) {
63
67
  }
64
68
  return { busy: false };
65
69
  }
70
+ /**
71
+ * How long a service may restore state it saved (after a restart, or when its device resumes):
72
+ * state saved longer ago than this is not restored. The kernel keeps a
73
+ * {@link encodeConversationDeleted} notice owed for at least this long after the deletion while
74
+ * the service is not running, so a service that restores within it still learns of the deletion.
75
+ */
76
+ export const DEVICE_SERVICE_RESTORE_MAX_AGE_MS = 10 * 60_000;
77
+ /** The body of the kernel's conversation-deleted notice (UTF-8 JSON; the provider frames it). */
78
+ export function encodeConversationDeleted(conversationId) {
79
+ if (typeof conversationId !== "string" || conversationId === "")
80
+ throw new TypeError("encodeConversationDeleted needs a conversation id");
81
+ return new TextEncoder().encode(JSON.stringify({ capybara: "conversation-deleted", conversationId }));
82
+ }
83
+ /**
84
+ * Reads a request body as the kernel's conversation-deleted notice: `capybara` is
85
+ * `"conversation-deleted"` and `conversationId` a non-empty string. Null for anything else (not
86
+ * UTF-8, not JSON, another shape, the roll check); never throws.
87
+ */
88
+ export function parseConversationDeleted(body) {
89
+ let msg;
90
+ try {
91
+ const text = typeof body === "string" ? body : new TextDecoder("utf-8", { fatal: true }).decode(body);
92
+ msg = JSON.parse(text);
93
+ }
94
+ catch {
95
+ return null;
96
+ }
97
+ if (typeof msg !== "object" || msg === null || Array.isArray(msg))
98
+ return null;
99
+ const { capybara, conversationId } = msg;
100
+ if (capybara !== "conversation-deleted")
101
+ return null;
102
+ if (typeof conversationId !== "string" || conversationId === "")
103
+ return null;
104
+ return { capybara: "conversation-deleted", conversationId };
105
+ }
66
106
  /** Names the unix socket path the service listens on. */
67
107
  export const DEVICE_SERVICE_SOCKET_ENV = "CAPYBARA_SERVICE_SOCKET";
68
108
  /** Names the service's state directory (its own data, its write root; not where its code is). */
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const SDK_VERSION = "0.1.0-rc.81";
1
+ export declare const SDK_VERSION = "0.1.0-rc.83";
2
2
  export * from "./agent-template.js";
3
3
  export * from "./avatar-presets.js";
4
4
  export * from "./bootstrap.js";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export const SDK_VERSION = "0.1.0-rc.81";
1
+ export const SDK_VERSION = "0.1.0-rc.83";
2
2
  export * from "./agent-template.js";
3
3
  export * from "./avatar-presets.js";
4
4
  export * from "./bootstrap.js";
package/dist/tool.d.ts CHANGED
@@ -127,6 +127,8 @@ export interface ToolDisplay {
127
127
  }
128
128
  /** The most characters of `ToolResult.card.text`. */
129
129
  export declare const CARD_TEXT_MAX = 2000;
130
+ /** The most characters of `ToolResult.card.badge` (as `UiView.badge`). */
131
+ export declare const CARD_BADGE_MAX = 32;
130
132
  export interface ToolResult {
131
133
  content: ToolContent[];
132
134
  isError?: boolean;
@@ -144,12 +146,16 @@ export interface ToolResult {
144
146
  * of the run wins); `process` only inside the process block, after its call.
145
147
  * `text` is the card's Markdown text for surfaces that cannot draw the view (IM channels, the
146
148
  * pinned card of a channel's progress card), at most {@link CARD_TEXT_MAX} characters.
149
+ * `badge` (pinned only) is the card's state in a few characters, the same as its view's
150
+ * `UiView.badge` (e.g. "3/5"), at most {@link CARD_BADGE_MAX} characters: a finished run's
151
+ * process head shows it after the view's title without reading the view again.
147
152
  */
148
153
  card?: {
149
154
  view: string;
150
155
  key?: string;
151
156
  placement?: "output" | "pinned" | "process";
152
157
  text?: string;
158
+ badge?: string;
153
159
  };
154
160
  }
155
161
  /**
@@ -230,7 +236,21 @@ export interface InputRequired {
230
236
  * warning and the form is asked as usual.
231
237
  */
232
238
  open?: UiOpen;
239
+ /**
240
+ * A watched wait: besides the person's answer and the deadline, the tool's registered watcher
241
+ * ({@link ToolWatcher}, `ctx.tools.register(spec, handler, { watch })`) may settle it. The
242
+ * kernel parks the run (no model turn, no worker held) and calls the watcher every 10 s while
243
+ * the wait is pending. `deadlineMs` is a positive integer number of milliseconds (anything else
244
+ * is refused with an invalid-form result), bounded by the deployment's
245
+ * `tools.approvalTimeoutHours`; a shorter kernel deadline resumes the call with
246
+ * `outcome: "expired"`.
247
+ */
248
+ watch?: {
249
+ deadlineMs: number;
250
+ };
233
251
  }
252
+ /** How an input round ended when the handler is called again ({@link ToolCallContext.resume}). */
253
+ export type ToolResumeOutcome = "answered" | "woken" | "expired";
234
254
  export type FormAnswer = Record<string, string | number | boolean | string[]>;
235
255
  /**
236
256
  * What a tool handler gets with each invocation.
@@ -276,10 +296,17 @@ export interface ToolCallContext {
276
296
  */
277
297
  idempotencyKey?: string;
278
298
  signal: AbortSignal;
279
- /** null = the user cancelled or it timed out. */
299
+ /**
300
+ * The previous input round's state and answer. `answer` is null unless the person answered.
301
+ * `outcome`: `answered` (the person answered), `woken` (a watched wait's watcher settled it, or
302
+ * the kernel ended the watch early: the watcher failed, is gone, or the tool is no longer
303
+ * available) or `expired` (the deadline passed). A tool with its own source of truth (a watched
304
+ * condition) asks it first and uses `outcome` only for what happened otherwise.
305
+ */
280
306
  resume?: {
281
307
  state: unknown;
282
308
  answer: FormAnswer | null;
309
+ outcome: ToolResumeOutcome;
283
310
  };
284
311
  /**
285
312
  * The extension's effective deployment config for this org: the platform's deployment config
@@ -296,6 +323,28 @@ export interface ToolCallContext {
296
323
  role?: "owner" | "admin" | "member" | "guest";
297
324
  }
298
325
  export type ToolHandler = (input: unknown, ctx: ToolCallContext) => Promise<ToolResult | InputRequired>;
326
+ /**
327
+ * What a watcher gets: the call's context as the handler got it (the same `callId`,
328
+ * `idempotencyKey`, accounts, conversations and effective config), without `resume`, plus the
329
+ * state the handler returned with its watched `InputRequired`.
330
+ */
331
+ export interface ToolWatchContext extends Omit<ToolCallContext, "resume"> {
332
+ state: unknown;
333
+ }
334
+ /**
335
+ * A watched wait's watcher (`ctx.tools.register(spec, handler, { watch })`). The kernel calls it
336
+ * every 10 s while the wait is pending, never twice at once for one wait, never after it
337
+ * settled; `settle` ends the wait (the handler is called again with `resume.outcome: "woken"`),
338
+ * `pending` keeps it. It must be cheap: the kernel aborts `ctx.signal` and stops waiting for it
339
+ * after 5 s, which counts as a failure, as a throw does; 3 consecutive failures end the wait. A
340
+ * watcher that ignores the signal keeps running after that, so a later poll may overlap it, and a
341
+ * poll already running when the wait ends (the person answered) may overlap the resumed handler:
342
+ * keep the watcher read-only and honour `ctx.signal`. Its
343
+ * `ctx.deviceAccess.request` calls run as `ifRunning` (a stopped device or service answers
344
+ * `not_running`, nothing is resumed or started), `ensureService` is refused, and
345
+ * `reportBlockedHosts` calls are dropped.
346
+ */
347
+ export type ToolWatcher = (ctx: ToolWatchContext) => Promise<"settle" | "pending">;
299
348
  /**
300
349
  * Tool error categories:
301
350
  * - `error` (default): the remote is available but this call failed (bad parameters, business
package/dist/tool.js CHANGED
@@ -95,6 +95,8 @@ function validateInputView(view, props) {
95
95
  }
96
96
  /** The most characters of `ToolResult.card.text`. */
97
97
  export const CARD_TEXT_MAX = 2000;
98
+ /** The most characters of `ToolResult.card.badge` (as `UiView.badge`). */
99
+ export const CARD_BADGE_MAX = 32;
98
100
  const DISPLAY_MAX = 200;
99
101
  /**
100
102
  * Validates a {@link ToolDisplay} and returns the list of problems (empty = valid); length is
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/plugin-sdk",
3
- "version": "0.1.0-rc.81",
3
+ "version": "0.1.0-rc.83",
4
4
  "description": "Capybara plugin SDK: the types and pure functions plugins are written against",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {