@b3os/sdk 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/dist/cjs/core/sse.d.ts +2 -0
  2. package/dist/cjs/core/sse.js +17 -5
  3. package/dist/cjs/core/sse.js.map +1 -1
  4. package/dist/cjs/core/util.d.ts +1 -1
  5. package/dist/cjs/core/util.js +1 -1
  6. package/dist/cjs/generated/client.d.ts +13 -0
  7. package/dist/cjs/generated/client.js +25 -0
  8. package/dist/cjs/generated/client.js.map +1 -1
  9. package/dist/cjs/generated/errors.d.ts +1 -1
  10. package/dist/cjs/generated/errors.js +95 -0
  11. package/dist/cjs/generated/errors.js.map +1 -1
  12. package/dist/cjs/generated/ids.d.ts +61 -0
  13. package/dist/cjs/generated/ids.js +15 -0
  14. package/dist/cjs/generated/ids.js.map +1 -1
  15. package/dist/cjs/generated/jobs.js +4 -0
  16. package/dist/cjs/generated/jobs.js.map +1 -1
  17. package/dist/cjs/generated/ns/actions.d.ts +303 -4
  18. package/dist/cjs/generated/ns/actions.js +446 -4
  19. package/dist/cjs/generated/ns/actions.js.map +1 -1
  20. package/dist/cjs/generated/ns/agents.d.ts +229 -0
  21. package/dist/cjs/generated/ns/agents.js +402 -0
  22. package/dist/cjs/generated/ns/agents.js.map +1 -0
  23. package/dist/cjs/generated/ns/images.d.ts +81 -0
  24. package/dist/cjs/generated/ns/images.js +122 -0
  25. package/dist/cjs/generated/ns/images.js.map +1 -0
  26. package/dist/cjs/generated/ns/infer.d.ts +71 -3
  27. package/dist/cjs/generated/ns/infer.js +98 -3
  28. package/dist/cjs/generated/ns/infer.js.map +1 -1
  29. package/dist/cjs/generated/ns/keys.d.ts +3 -1
  30. package/dist/cjs/generated/ns/keys.js +3 -1
  31. package/dist/cjs/generated/ns/keys.js.map +1 -1
  32. package/dist/cjs/generated/ns/listeners.d.ts +159 -0
  33. package/dist/cjs/generated/ns/listeners.js +264 -0
  34. package/dist/cjs/generated/ns/listeners.js.map +1 -0
  35. package/dist/cjs/generated/ns/orgs.d.ts +10 -0
  36. package/dist/cjs/generated/ns/orgs.js +26 -1
  37. package/dist/cjs/generated/ns/orgs.js.map +1 -1
  38. package/dist/cjs/generated/ns/projects.d.ts +32 -0
  39. package/dist/cjs/generated/ns/projects.js +66 -0
  40. package/dist/cjs/generated/ns/projects.js.map +1 -1
  41. package/dist/cjs/generated/ns/render.d.ts +192 -21
  42. package/dist/cjs/generated/ns/render.js +267 -24
  43. package/dist/cjs/generated/ns/render.js.map +1 -1
  44. package/dist/cjs/generated/ns/requests.d.ts +3 -1
  45. package/dist/cjs/generated/ns/requests.js +3 -1
  46. package/dist/cjs/generated/ns/requests.js.map +1 -1
  47. package/dist/cjs/generated/ns/routines.d.ts +11 -4
  48. package/dist/cjs/generated/ns/routines.js +11 -4
  49. package/dist/cjs/generated/ns/routines.js.map +1 -1
  50. package/dist/cjs/generated/ns/sandboxes.d.ts +292 -7
  51. package/dist/cjs/generated/ns/sandboxes.js +444 -6
  52. package/dist/cjs/generated/ns/sandboxes.js.map +1 -1
  53. package/dist/cjs/generated/ns/usage.d.ts +1 -1
  54. package/dist/cjs/generated/ns/usage.js +1 -1
  55. package/dist/cjs/generated/ns/vision.d.ts +59 -17
  56. package/dist/cjs/generated/ns/vision.js +59 -21
  57. package/dist/cjs/generated/ns/vision.js.map +1 -1
  58. package/dist/cjs/generated/types.d.ts +2787 -85
  59. package/dist/cjs/helpers/sandboxes.d.ts +46 -3
  60. package/dist/cjs/helpers/sandboxes.js +127 -14
  61. package/dist/cjs/helpers/sandboxes.js.map +1 -1
  62. package/dist/cjs/index.d.ts +1 -1
  63. package/dist/cjs/index.js +2 -1
  64. package/dist/cjs/index.js.map +1 -1
  65. package/dist/esm/core/sse.d.ts +2 -0
  66. package/dist/esm/core/sse.js +17 -5
  67. package/dist/esm/core/sse.js.map +1 -1
  68. package/dist/esm/core/util.d.ts +1 -1
  69. package/dist/esm/core/util.js +1 -1
  70. package/dist/esm/generated/client.d.ts +13 -0
  71. package/dist/esm/generated/client.js +25 -0
  72. package/dist/esm/generated/client.js.map +1 -1
  73. package/dist/esm/generated/errors.d.ts +1 -1
  74. package/dist/esm/generated/errors.js +95 -0
  75. package/dist/esm/generated/errors.js.map +1 -1
  76. package/dist/esm/generated/ids.d.ts +61 -0
  77. package/dist/esm/generated/ids.js +15 -0
  78. package/dist/esm/generated/ids.js.map +1 -1
  79. package/dist/esm/generated/jobs.js +4 -0
  80. package/dist/esm/generated/jobs.js.map +1 -1
  81. package/dist/esm/generated/ns/actions.d.ts +303 -4
  82. package/dist/esm/generated/ns/actions.js +446 -4
  83. package/dist/esm/generated/ns/actions.js.map +1 -1
  84. package/dist/esm/generated/ns/agents.d.ts +229 -0
  85. package/dist/esm/generated/ns/agents.js +398 -0
  86. package/dist/esm/generated/ns/agents.js.map +1 -0
  87. package/dist/esm/generated/ns/images.d.ts +81 -0
  88. package/dist/esm/generated/ns/images.js +118 -0
  89. package/dist/esm/generated/ns/images.js.map +1 -0
  90. package/dist/esm/generated/ns/infer.d.ts +71 -3
  91. package/dist/esm/generated/ns/infer.js +98 -3
  92. package/dist/esm/generated/ns/infer.js.map +1 -1
  93. package/dist/esm/generated/ns/keys.d.ts +3 -1
  94. package/dist/esm/generated/ns/keys.js +3 -1
  95. package/dist/esm/generated/ns/keys.js.map +1 -1
  96. package/dist/esm/generated/ns/listeners.d.ts +159 -0
  97. package/dist/esm/generated/ns/listeners.js +260 -0
  98. package/dist/esm/generated/ns/listeners.js.map +1 -0
  99. package/dist/esm/generated/ns/orgs.d.ts +10 -0
  100. package/dist/esm/generated/ns/orgs.js +26 -1
  101. package/dist/esm/generated/ns/orgs.js.map +1 -1
  102. package/dist/esm/generated/ns/projects.d.ts +32 -0
  103. package/dist/esm/generated/ns/projects.js +66 -0
  104. package/dist/esm/generated/ns/projects.js.map +1 -1
  105. package/dist/esm/generated/ns/render.d.ts +192 -21
  106. package/dist/esm/generated/ns/render.js +267 -24
  107. package/dist/esm/generated/ns/render.js.map +1 -1
  108. package/dist/esm/generated/ns/requests.d.ts +3 -1
  109. package/dist/esm/generated/ns/requests.js +3 -1
  110. package/dist/esm/generated/ns/requests.js.map +1 -1
  111. package/dist/esm/generated/ns/routines.d.ts +11 -4
  112. package/dist/esm/generated/ns/routines.js +11 -4
  113. package/dist/esm/generated/ns/routines.js.map +1 -1
  114. package/dist/esm/generated/ns/sandboxes.d.ts +292 -7
  115. package/dist/esm/generated/ns/sandboxes.js +444 -6
  116. package/dist/esm/generated/ns/sandboxes.js.map +1 -1
  117. package/dist/esm/generated/ns/usage.d.ts +1 -1
  118. package/dist/esm/generated/ns/usage.js +1 -1
  119. package/dist/esm/generated/ns/vision.d.ts +59 -17
  120. package/dist/esm/generated/ns/vision.js +59 -21
  121. package/dist/esm/generated/ns/vision.js.map +1 -1
  122. package/dist/esm/generated/types.d.ts +2787 -85
  123. package/dist/esm/helpers/sandboxes.d.ts +46 -3
  124. package/dist/esm/helpers/sandboxes.js +126 -13
  125. package/dist/esm/helpers/sandboxes.js.map +1 -1
  126. package/dist/esm/index.d.ts +1 -1
  127. package/dist/esm/index.js +1 -1
  128. package/dist/esm/index.js.map +1 -1
  129. package/package.json +1 -1
  130. package/src/core/sse.ts +17 -5
  131. package/src/core/util.ts +1 -1
  132. package/src/generated/client.ts +28 -0
  133. package/src/generated/errors.ts +190 -0
  134. package/src/generated/ids.ts +15 -0
  135. package/src/generated/jobs.ts +4 -0
  136. package/src/generated/ns/actions.ts +483 -4
  137. package/src/generated/ns/agents.ts +461 -0
  138. package/src/generated/ns/images.ts +128 -0
  139. package/src/generated/ns/infer.ts +100 -3
  140. package/src/generated/ns/keys.ts +3 -1
  141. package/src/generated/ns/listeners.ts +296 -0
  142. package/src/generated/ns/orgs.ts +27 -1
  143. package/src/generated/ns/projects.ts +74 -0
  144. package/src/generated/ns/render.ts +277 -24
  145. package/src/generated/ns/requests.ts +3 -1
  146. package/src/generated/ns/routines.ts +11 -4
  147. package/src/generated/ns/sandboxes.ts +492 -7
  148. package/src/generated/ns/usage.ts +1 -1
  149. package/src/generated/ns/vision.ts +59 -21
  150. package/src/generated/types.ts +3511 -575
  151. package/src/helpers/sandboxes.ts +167 -14
  152. package/src/index.ts +1 -0
@@ -26,28 +26,40 @@ export type Scope =
26
26
  | "sandboxes:read"
27
27
  | "sandboxes:write"
28
28
  | "sandboxes:run"
29
+ | "agents:read"
30
+ | "agents:write"
31
+ | "agents:run"
29
32
  | "routines:read"
30
33
  | "routines:write"
31
34
  | "routines:run"
35
+ | "listeners:read"
36
+ | "listeners:write"
32
37
  | "actions:read"
33
38
  | "actions:write"
34
39
  | "actions:run"
40
+ | "actions:tools:publish"
35
41
  | "infer:read"
36
42
  | "infer:write"
37
43
  | "infer:run"
38
44
  | "vault:read"
39
45
  | "vault:write"
40
46
  | "vault:run"
47
+ | "vault:connections:reveal"
41
48
  | "platform:read"
42
49
  | "platform:write"
50
+ | "platform:content:read"
51
+ | "settings:write"
43
52
  | "vision:*"
44
53
  | "render:*"
45
54
  | "sandboxes:*"
55
+ | "agents:*"
46
56
  | "routines:*"
57
+ | "listeners:*"
47
58
  | "actions:*"
48
59
  | "infer:*"
49
60
  | "vault:*"
50
61
  | "platform:*"
62
+ | "settings:*"
51
63
  | "*";
52
64
 
53
65
  /**
@@ -127,6 +139,12 @@ export interface Problem {
127
139
  limit?: LimitRef;
128
140
  /** The object's current status, for state conflicts such as `sandbox_not_running`. */
129
141
  current_status?: string;
142
+ /** The sandbox that holds a lease's key now, or null when none does (`lease_holder_changed`). */
143
+ holder?: string | null;
144
+ /** The head of the linked branch now (`manifest_changed`). */
145
+ head_commit?: string;
146
+ /** The digest of b3os.yaml at `head_commit` (`manifest_changed`); null when the file is not there. */
147
+ head_digest?: string | null;
130
148
  /** The HTTP status the upstream returned (`upstream_error`, `action_output_invalid`). */
131
149
  upstream_status?: number;
132
150
  /**
@@ -140,15 +158,57 @@ export interface Problem {
140
158
  retryable: boolean;
141
159
  };
142
160
  /**
143
- * The option a request value was refused for, by its id (`option_not_allowed`), e.g. `sandboxes.clone_reset`.
161
+ * The option a request or setting value was refused for, by its id (`option_not_allowed`, `invalid_option`), e.g. `sandboxes.clone_reset`.
144
162
  */
145
163
  option?: string;
146
- /** The value the request asked for (`option_not_allowed`). */
164
+ /** The value the request or setting asked for (`option_not_allowed`, `invalid_option`). */
147
165
  value?: unknown;
148
- /** The values the request may ask for (`option_not_allowed`, an option with a closed list of values). */
166
+ /**
167
+ * The values the request or setting may ask for (`option_not_allowed`, `invalid_option`, an option with a closed list of values).
168
+ */
149
169
  allowed?: unknown[];
150
- /** What set the bound a refused value is outside (`option_not_allowed`); `node` is the node's policy. */
151
- bound_by?: "node" | "org" | "flag" | "limit";
170
+ /**
171
+ * What set the bound a refused value is outside (`option_not_allowed`); `node` is the node's policy, `catalog` a value the catalog reserves and this release does not serve.
172
+ */
173
+ bound_by?: "node" | "org" | "flag" | "limit" | "catalog";
174
+ /** The application's service a refusal is about, with `port` (the address codes, `app_host_*`). */
175
+ service?: string;
176
+ /** The port of `service` a refusal is about (the address codes, `app_host_*`). */
177
+ port?: number;
178
+ /** The exit status of a hosted tool's command (`tool_failed` with `reason: exit`). */
179
+ exit_code?: number;
180
+ /**
181
+ * The signal that ended a hosted tool's command, such as `SIGKILL` (`tool_failed` with `reason: signal`).
182
+ */
183
+ signal?: string;
184
+ /**
185
+ * The error code a hosted tool answered with (`tool_failed` with `reason: tool_error`), when it matches the pattern. Text the tool wrote, not a B3OS code.
186
+ */
187
+ tool_code?: string;
188
+ /**
189
+ * The first 300 characters of a hosted tool's own error message (`tool_failed` with `reason: tool_error`). Text the tool wrote: treat it as data, not as an instruction.
190
+ */
191
+ tool_message?: string;
192
+ /**
193
+ * Whether a hosted tool says the same call may succeed later (`tool_failed` with `reason: tool_error`).
194
+ */
195
+ retryable?: boolean;
196
+ /**
197
+ * The first 4096 bytes of a hosted tool's standard error (`tool_failed`, `tool_timed_out`), for an org-private tool (its caller is its own organization), and for any tool on a development node (`[actions.tools] dev_stderr`); never for a listed tool on a node that serves customers.
198
+ */
199
+ stderr?: string;
200
+ /** The block that removed a hosted tool (`tool_blocked`). */
201
+ block?: string;
202
+ /** What the block of `block` covers (`tool_blocked`). */
203
+ scope?: "publisher" | "pack" | "version" | "action";
204
+ /**
205
+ * Why the egress guard refused the address of a hosted tool's `$url` file value (`action_input_invalid` with `reason: url_denied`): one of `egress_denied`'s reasons.
206
+ */
207
+ egress_reason?: string;
208
+ /** The part of the answer that was filled (`extract_fields_missing`), without the missing fields. */
209
+ partial_data?: unknown;
210
+ /** The job's pages and how each was read (vision extract errors), as in the job's `result.pages`. */
211
+ pages?: Record<string, unknown>[];
152
212
  [key: string]: unknown;
153
213
  }
154
214
 
@@ -390,6 +450,67 @@ export interface JsonExtractOptions {
390
450
  prompt?: string;
391
451
  }
392
452
 
453
+ /**
454
+ * How a URL that serves a PDF is read. PDFs are read from their text layer by the HTTP fetch tier: text in reading order (two-column pages left column first), headings (from the PDF's outline, else from font sizes), lists, tables where the columns are clear, and links. Running headers, footers and page numbers are dropped with `only_main_content` (the default) on documents of 3 or more pages. `include_tags` and `exclude_tags` do not apply to a PDF, and `raw_html`, `screenshot` and `images` are not produced for one (each adds a warning).
455
+ */
456
+ export interface PdfOptions {
457
+ /**
458
+ * `text` reads the text layer. `off` does not read PDFs: a PDF answers `422 content_type_unsupported`, and a crawl does not follow links that end in `.pdf`.
459
+ * @default "text"
460
+ */
461
+ mode?: "text" | "off";
462
+ /**
463
+ * Read at most this many pages, from the first. The default and the ceiling are the node's `vision.pdf.pages_max` (500); a value above it answers `422 limit_exceeded`, and a batch, crawl, extract or search that carries one is refused before it starts. A longer file returns its first pages with `pdf.truncated: max_pages` and bills only the pages read.
464
+ */
465
+ max_pages?: number;
466
+ /**
467
+ * Put `\n\n---\n\n<!-- page N -->\n\n` between pages in `markdown` (between pages only: no marker before page 1), the marker Firecrawl uses. `text` and `html` keep a plain break.
468
+ * @default true
469
+ */
470
+ page_markers?: boolean;
471
+ /**
472
+ * Also return each page's Markdown on its own, in `pdf.page_markdown`.
473
+ * @default false
474
+ */
475
+ pages?: boolean;
476
+ }
477
+
478
+ /**
479
+ * What a PDF scrape read. Present only when the URL served a PDF. The document's own metadata (`title`, `author`, ...) is present when the PDF states it.
480
+ */
481
+ export interface PdfInfo {
482
+ /** Pages in the file. */
483
+ pages: number;
484
+ /** Pages converted, from the first. */
485
+ pages_read: number;
486
+ /** `vision.page` units this scrape billed: the pages read. */
487
+ pages_billed: number;
488
+ /**
489
+ * Why fewer pages than the file holds were read: `max_pages` (the request's or the node's page cap), `max_chars` (about 2 million characters of text, or a page too dense to pass on whole, cut there), `deadline` (the scrape's time ran out; the pages read by then are returned), `allowance` (the organization's monthly page allowance ran out). `null` when the whole file was read.
490
+ */
491
+ truncated: "max_pages" | "max_chars" | "deadline" | "allowance" | null;
492
+ title?: string;
493
+ author?: string;
494
+ subject?: string;
495
+ keywords?: string;
496
+ /** The program that made the original document. */
497
+ creator?: string;
498
+ /** The program that wrote the PDF. */
499
+ producer?: string;
500
+ /** The PDF's creation date (RFC 3339, converted from the PDF date). */
501
+ created_at?: string;
502
+ modified_at?: string;
503
+ /** The PDF carries a structure tree (tagged PDF). The tree is not used yet. */
504
+ tagged?: boolean;
505
+ /** Pages with images and no text layer (scanned); OCR is not available yet, so they add no text. */
506
+ no_text_pages?: number[];
507
+ /** Each page's Markdown, with `pdf.pages`. */
508
+ page_markdown?: {
509
+ page: number;
510
+ markdown: string;
511
+ }[];
512
+ }
513
+
393
514
  /** Options shared by scrape, batch scrape, crawl and extract. */
394
515
  export interface ScrapeOptions {
395
516
  /** @default ["markdown"] */
@@ -475,6 +596,7 @@ export interface ScrapeOptions {
475
596
  block_resources?: Array<"image" | "media" | "font" | "stylesheet">;
476
597
  screenshot?: ScreenshotOptions;
477
598
  json?: JsonExtractOptions;
599
+ pdf?: PdfOptions;
478
600
  /**
479
601
  * What a wall (`page_state` `blocked` or `captcha`) costs. `free`: no `vision.page`, and the result carries no page content, only `page_state`, `status_code`, `final_url` and `content_withheld: true`. `bill`: the wall bills like any page and its content is returned. A scrape with `actions` bills either way.
480
602
  * @default "free"
@@ -486,8 +608,104 @@ export interface ScrapeOptions {
486
608
  export type ScrapeRequest = {
487
609
  /** Absolute `http` or `https` URL. */
488
610
  url: string;
611
+ proxy?: ProxyOption;
612
+ /**
613
+ * The country of the residential address (ISO 3166-1 alpha-2, any case; default `US`), for `proxy` `auto` and `residential` only. The node lists the countries it offers; another answers `422 option_not_allowed`. Locale and time zone do not follow it: set `locale` and `timezone` yourself.
614
+ */
615
+ proxy_country?: string;
489
616
  } & ScrapeOptions;
490
617
 
618
+ /**
619
+ * Where the scrape leaves from (`vision.proxy`). Absent: the node's default, `none` unless its operator set
620
+ * `auto`.
621
+ * - `none`: the node's own address, always.
622
+ * - `auto`: the node's address; when the page comes back a wall (`page_state` `blocked` or `captcha`), vision
623
+ * asks once more from a residential address, unless the request or the site rules that out
624
+ * (`egress.retry.skipped` says why no retry ran). Where residential reads are off it is exactly `none`,
625
+ * never an error.
626
+ * - `residential`: read the page from a residential address, every request of the scrape (`422
627
+ * option_not_allowed` where that is off: `bound_by: node` or `org`).
628
+ * - `http://host:port`: your own proxy, without credentials.
629
+ * - `{url, connection}`: your own proxy with the username and password of a `basic` vault connection whose
630
+ * `hosts` list the proxy's host (needs `vault:run`).
631
+ * A URL with a username or password is refused (`400 invalid_request`): put them in a connection. This node
632
+ * takes `http://` proxies only; plain HTTP means the username and password cross the network to your proxy
633
+ * unencrypted. Batches, crawls, sessions and the Firecrawl surface do not take `proxy` yet.
634
+ */
635
+ export type ProxyOption =
636
+ | "none"
637
+ | "auto"
638
+ | "residential"
639
+ | string
640
+ | {
641
+ /** Your proxy's URL, `http://host:port`. */
642
+ url: string;
643
+ /** A `basic` vault connection with the proxy's username and password. */
644
+ connection?: string;
645
+ };
646
+
647
+ /**
648
+ * Which exit served the page returned. `node`: the node's own address. `byo`: your proxy (`host`, never its
649
+ * credentials). `residential`: read from a residential address (`country`, `exit_session`). `bytes` counts
650
+ * both directions through the exit for this scrape. With `proxy: "auto"`, after a wall from the node's address:
651
+ * `retried_from`, `first` (the node's wall) when the residential read's page is the one returned, or `retry`
652
+ * when no retry ran (`skipped`) or it did not help (`outcome`).
653
+ */
654
+ export interface Egress {
655
+ exit: "node" | "byo" | "residential";
656
+ /** Your proxy's host (`byo`). */
657
+ host?: string;
658
+ /** The residential address's country (`residential`). */
659
+ country?: string;
660
+ /**
661
+ * B3OS's id of the residential exit session (one address), the same for every page of one host and organization while it lasts.
662
+ */
663
+ exit_session?: string;
664
+ /** Bytes through the exit for this scrape, both directions. */
665
+ bytes?: number;
666
+ /** The page was read from a residential address after a wall from the node's address. */
667
+ retried_from?: "node";
668
+ /** The node's wall, when the residential read's page is the one returned. */
669
+ first?: {
670
+ page_state?: string;
671
+ signal?: string;
672
+ status_code?: number;
673
+ };
674
+ /**
675
+ * `auto` after a wall from the node's address: why no retry ran (`skipped`), or how the retry from a residential address ended when the node's wall is the page returned (`outcome` `wall` or `failed`).
676
+ */
677
+ retry?: {
678
+ skipped?:
679
+ | "org"
680
+ | "node"
681
+ | "credentials"
682
+ | "opt_out"
683
+ | "category"
684
+ | "memory"
685
+ | "rate_limited"
686
+ | "time"
687
+ | "quota"
688
+ | "robots"
689
+ | "capacity";
690
+ exit?: "residential";
691
+ outcome?: "wall" | "failed";
692
+ page_state?: string;
693
+ error?: string;
694
+ bytes?: number;
695
+ };
696
+ }
697
+
698
+ /**
699
+ * The options the scrape read, each with its `value` and the level it came from (`request` or `node`): `vision.proxy` always, `vision.proxy_country` for `auto` and `residential`. Your own proxy's value is `{"url": "http://host:port"}`, with `connection` when one was named.
700
+ */
701
+ export type ScrapeOptionsApplied = Record<
702
+ string,
703
+ {
704
+ value: unknown;
705
+ from: "request" | "node";
706
+ }
707
+ >;
708
+
491
709
  /** Metadata read from the page. */
492
710
  export interface PageMetadata {
493
711
  title?: string;
@@ -505,7 +723,7 @@ export interface PageMetadata {
505
723
 
506
724
  export interface CacheInfo {
507
725
  /**
508
- * `hit` served from cache; `miss` fetched and stored; `bypass` fetched and not shared (custom headers, profile, actions).
726
+ * `hit` served from cache; `miss` fetched and stored; `bypass` fetched and not shared (custom headers, profile, actions, and every PDF).
509
727
  */
510
728
  state: "hit" | "miss" | "bypass";
511
729
  /** Age of the served copy in seconds. */
@@ -534,6 +752,14 @@ export interface ScrapeResult {
534
752
  content_type?: string;
535
753
  /** What served the page. */
536
754
  tier: "cache" | "fetch" | "browser";
755
+ /**
756
+ * Present when the browser served an `engine: "auto"` scrape: why the fetch tier did not. `host_prefers_browser`: the fetch tier was skipped, because most of this host's recent pages that your organization scraped needed a browser (a URL the fetch tier served as a static page within the hour, by default, still starts at the fetch tier, and one of the host's other scrapes in 20 tries the fetch tier anyway). `needs_js`: the fetch tier's page needed JavaScript. `empty_page`: the fetch tier's page came out empty. `thin_page`: the fetch tier's page was thin or mostly script, and the browser's had more text. `fetch_failed`: the fetch failed in a way a browser may not (TLS, a connection, a redirect loop, a timeout). `challenged`: the site answered the fetch tier with a bot challenge or block page, with Chrome's headers and, after a 403, with the [B3OS fetcher](https://docs.beta.b3os.org/vision/fetcher)'s (see `fetch_identity`); or it refused both for this URL, or for two URLs of the host, within the hour by default, so the fetch tier was skipped for your organization's scrape.
757
+ */
758
+ tier_reason?: "host_prefers_browser" | "needs_js" | "empty_page" | "thin_page" | "fetch_failed" | "challenged";
759
+ /**
760
+ * Who the fetch tier's last request of this scrape said it was, when the fetch tier sent one from the node's address. `chrome`: the headers Chrome sends for a page (the default). `honest`: the [B3OS fetcher](https://docs.beta.b3os.org/vision/fetcher), with the user agent `Mozilla/5.0 (compatible; B3OS-Vision/<version>; +https://docs.beta.b3os.org/vision/fetcher)` and no client hints. The fetch tier asks once more as the B3OS fetcher when Chrome's headers get a 403 bot challenge, and a page it gets that way carries a warning; your organization's scrapes of that host start with it for up to an hour, by default, then with Chrome's headers again. Never when your request sets `User-Agent`, `Sec-CH-*`, `Sec-Fetch-*` or `Upgrade-Insecure-Requests` in `headers`, and never through an exit. Absent for a cache hit, a scrape the browser served without a fetch, and a page that went through an exit.
761
+ */
762
+ fetch_identity?: "chrome" | "honest";
537
763
  cache: CacheInfo;
538
764
  markdown?: string;
539
765
  html?: string;
@@ -547,6 +773,7 @@ export interface ScrapeResult {
547
773
  /** Results of `actions`, in order. */
548
774
  actions?: ActStepResult[];
549
775
  page_state?: PageState;
776
+ pdf?: PdfInfo;
550
777
  /**
551
778
  * Present (`true`) when the page is a wall and the scrape was free (`walls: free`): the result then has no `markdown`, `html`, `raw_html`, `text`, `links`, `metadata`, `screenshot`, `json`, `actions` or `content_type`, only the state, `status_code` and `final_url`.
552
779
  */
@@ -554,6 +781,8 @@ export interface ScrapeResult {
554
781
  /** Non-fatal problems, such as a format that could not be produced. */
555
782
  warnings: string[];
556
783
  timing: Timing;
784
+ egress?: Egress;
785
+ options?: ScrapeOptionsApplied;
557
786
  }
558
787
 
559
788
  export interface PrepareRequest {
@@ -748,6 +977,9 @@ export interface PageResult {
748
977
  depth?: number;
749
978
  scraped_at?: string;
750
979
  scrape?: ScrapeResult;
980
+ /**
981
+ * Why the page failed, with the codes a scrape answers with: for example `navigation_failed`, `scrape_timeout`, `content_type_unsupported`, and for a PDF `pdf_unreadable` or `pdf_encrypted`. A failed page bills nothing.
982
+ */
751
983
  error?: Problem;
752
984
  }
753
985
 
@@ -799,10 +1031,15 @@ export type BatchEvent = PageEvent;
799
1031
  /** An event of a crawl's stream. */
800
1032
  export type CrawlEvent = PageEvent;
801
1033
 
1034
+ /** At least one of `schema` and `prompt` is required. */
802
1035
  export interface ExtractCreateRequest {
1036
+ /** The pages to read (`vision.extract.urls_max`); duplicates are read once. */
803
1037
  urls: string[];
1038
+ /** What to extract, in words. With `schema`, guidance for filling it. */
804
1039
  prompt?: string;
805
- /** JSON Schema of the result. */
1040
+ /**
1041
+ * JSON Schema of the result (draft 2020-12, or the draft its `$schema` names, such as draft-07 from zod). At most 64 KiB and 32 levels deep; `$ref` may only point inside the schema.
1042
+ */
806
1043
  schema?: Record<string, unknown>;
807
1044
  scrape?: NestedScrapeOptions;
808
1045
  /** Model ID from `GET /v1/infer/models`; defaults to the node's model. */
@@ -817,13 +1054,49 @@ export type ExtractJob = Omit<Job, "id" | "object" | "result"> & {
817
1054
  object: "job";
818
1055
  kind: "vision.extract";
819
1056
  result?: {
820
- /** The extracted data, matching your schema. */
1057
+ /** The extracted data, validated against your schema (any JSON object without one). */
821
1058
  data: unknown;
822
- /** Pages the data came from. */
1059
+ /** Pages the data came from, as given in `urls`. */
823
1060
  sources: string[];
1061
+ /** For each top-level field of `data`, the pages it came from. */
1062
+ field_sources?: Record<string, string[]>;
1063
+ /** Every URL of the job, in the order given, and how it was read. */
1064
+ pages?: ExtractPage[];
1065
+ usage?: ExtractUsage;
1066
+ /**
1067
+ * Pages or pieces left out (too many model calls), conflicting values the merge resolved (`/plans/0/usd_per_month: https://a says 49, https://b says 59; kept the first`), and the pages' own warnings.
1068
+ */
1069
+ warnings?: string[];
824
1070
  };
825
1071
  };
826
1072
 
1073
+ /** One URL of an extract job. */
1074
+ export interface ExtractPage {
1075
+ url: string;
1076
+ status: "succeeded" | "failed";
1077
+ final_url?: string;
1078
+ content_type?: string | null;
1079
+ /** Characters of the page's Markdown the model read. */
1080
+ chars?: number;
1081
+ /** The page's Markdown was cut (pieces past `extract.max_model_calls`, or a PDF's own caps). */
1082
+ truncated?: boolean;
1083
+ /** Pages read when the URL served a PDF. */
1084
+ pdf_pages?: number | null;
1085
+ /** Why the page failed (the codes a scrape answers with). A failed page bills nothing. */
1086
+ error?: Problem;
1087
+ }
1088
+
1089
+ /** What the job used. */
1090
+ export interface ExtractUsage {
1091
+ /** `vision.page` units billed for the pages read. */
1092
+ pages_billed: number;
1093
+ /** Prompt tokens of the model calls (billed by infer as `infer.input_tokens`). */
1094
+ input_tokens: number;
1095
+ /** Answer tokens of the model calls (`infer.output_tokens`). */
1096
+ output_tokens: number;
1097
+ model_calls: number;
1098
+ }
1099
+
827
1100
  /**
828
1101
  * `active` until closed by its timeout (`expired`) or otherwise (`closed`: `DELETE`, its browser stopped, or the node restarted; `closed_reason` says which).
829
1102
  */
@@ -1204,6 +1477,12 @@ export interface SnapshotData {
1204
1477
  complete: boolean;
1205
1478
  /** The budget (`max_tokens`) cut the outline. */
1206
1479
  truncated: boolean;
1480
+ /**
1481
+ * The page's `document.title` when the outline was taken, read in act's isolated world (never the page's own world); empty when it could not be read. Node release 1119.
1482
+ */
1483
+ title?: string;
1484
+ /** The page's URL when the outline was taken, read the same way. Node release 1119. */
1485
+ url?: string;
1207
1486
  }
1208
1487
 
1209
1488
  export interface ActRequest {
@@ -2109,6 +2388,320 @@ export type ScreenshotList = Omit<ListEnvelope, "data"> & {
2109
2388
  data: Screenshot[];
2110
2389
  };
2111
2390
 
2391
+ /**
2392
+ * Give exactly one of `url` or `video_id`. `steps`, `watch`, `viewport` and `theme` are for `url` only.
2393
+ */
2394
+ export type InspectionCreateRequest = {
2395
+ /** Page to load (`http` or `https`), checked by the egress guard. */
2396
+ url?: string;
2397
+ /** A succeeded video of this project to read the window from. */
2398
+ video_id?: string;
2399
+ /**
2400
+ * Browser steps to run during the window. Step 0 starts at 300 ms; each next step starts when the one before it ends. `navigate` and `wait` with `for` hold the clock until they are done. The window must end at least 200 ms after the last step ends.
2401
+ */
2402
+ steps?: ScriptStep[];
2403
+ /** Elements whose box is read on every frame (`trace`). */
2404
+ watch?: InspectionWatchTarget[];
2405
+ /**
2406
+ * Length of the window. Default 3000; with `video_id`, the rest of the video from `from_ms`, at most 10000 ms and 300 frames (a default cut to 300 frames carries a `window_cut` warning).
2407
+ */
2408
+ duration_ms?: number;
2409
+ /**
2410
+ * With `video_id` only (refused with `url`): where the window starts in the video, 0 when left out. A window that runs past the end of the video is cut to it (`window_cut` warning).
2411
+ */
2412
+ from_ms?: number;
2413
+ /**
2414
+ * Frames a second. Default 30; with `video_id`, the video's own rate. `duration_ms` times `fps` is at most 300 frames.
2415
+ */
2416
+ fps?: 10 | 15 | 30 | 60;
2417
+ viewport?: InspectionViewport;
2418
+ /**
2419
+ * Emulated `prefers-color-scheme`; `auto` leaves the page default.
2420
+ * @default "auto"
2421
+ */
2422
+ theme?: "light" | "dark" | "auto";
2423
+ /**
2424
+ * Put the sheet's tiles at a fixed interval from the window's start instead of where pixels change. The window may hold at most 12 tiles at this interval.
2425
+ */
2426
+ interval_ms?: number;
2427
+ };
2428
+
2429
+ /** Browser viewport in CSS pixels. Default 1280x800. */
2430
+ export interface InspectionViewport {
2431
+ width: number;
2432
+ height: number;
2433
+ }
2434
+
2435
+ /**
2436
+ * An element to follow frame by frame: `selector` (CSS), or visible `text` (case-insensitive substring unless `exact`; the `nth` match when set). `role` and `name` are not accepted here: they cost too much to resolve on every frame.
2437
+ */
2438
+ export type InspectionWatchTarget = {
2439
+ selector?: string;
2440
+ text?: string;
2441
+ /** @default false */
2442
+ exact?: boolean;
2443
+ nth?: number;
2444
+ };
2445
+
2446
+ export interface Inspection {
2447
+ id: string;
2448
+ object: "inspection";
2449
+ /** An inspection answers once it has finished; a failure is an error response. */
2450
+ status: "succeeded";
2451
+ source: InspectionSource;
2452
+ window: InspectionWindow;
2453
+ /** When each step ran, in the window's clock. */
2454
+ steps: InspectionStep[];
2455
+ /**
2456
+ * Up to 8 plain lines in time order, the same events as `report` and `trace`, such as `0.333 s content below y 318 moved up 29 px (layout)`. When `layout_shifts` has a source on a shift's frame, that shift's line ends with the source's `label` in quotes (the largest labelled source when there are several): `0.333 s content below y 318 moved up 29 px (layout) "Step a1"`. A window where nothing changed has one line, `no change`.
2457
+ */
2458
+ summary: string[];
2459
+ report: InspectionReport;
2460
+ /** One entry per `watch` target, in request order; empty without `watch`. */
2461
+ trace: InspectionTrace[];
2462
+ /**
2463
+ * The browser's own layout-shift entries (the Layout Instability API), each naming the elements that moved. Left out when the browser reported none.
2464
+ */
2465
+ layout_shifts?: InspectionLayoutShift[];
2466
+ sheet: InspectionSheet;
2467
+ /**
2468
+ * Non-fatal problems, each starting with a code and a colon: `http_status` (the site answered an error status), `watch_not_found` (a `watch` target matched nothing on the first frame), `window_cut` (the window ran past the end of the video and was cut to it, or the default window of a video was more than 300 frames and was cut to 300).
2469
+ */
2470
+ warnings: string[];
2471
+ /**
2472
+ * Phases `queue` (waiting for a free inspection slot), `claim`, `navigate`, `settle`, `capture`, `analyze`, `sheet`, `persist` and `total`, also sent as `Server-Timing`. A video source has no `claim`, `navigate` or `settle`; its `capture` is reading the video.
2473
+ */
2474
+ timing: Timing;
2475
+ created_at: string;
2476
+ /** When the sheet is deleted, 24 hours after it was made. */
2477
+ expires_at: string;
2478
+ }
2479
+
2480
+ /** The page (`url`, `final_url`, `status_code`) or the video (`video_id`). */
2481
+ export interface InspectionSource {
2482
+ url?: string;
2483
+ /** The URL after redirects. */
2484
+ final_url?: string;
2485
+ /** The HTTP status the site answered for the page. */
2486
+ status_code?: number;
2487
+ video_id?: string;
2488
+ }
2489
+
2490
+ export interface InspectionSize {
2491
+ width: number;
2492
+ height: number;
2493
+ }
2494
+
2495
+ export interface InspectionWindow {
2496
+ /** The time of frame 0. Frame i is at `from_ms + round(i * 1000 / fps)`. */
2497
+ from_ms: number;
2498
+ duration_ms: number;
2499
+ fps: number;
2500
+ frames: number;
2501
+ /** The frame size in `units`, the viewport for a page and the video's size for a video. */
2502
+ viewport: InspectionSize;
2503
+ /** What every position and size in the answer is measured in. */
2504
+ units: "css_px" | "video_px";
2505
+ }
2506
+
2507
+ export interface InspectionStep {
2508
+ /** The step's path in the request, such as `steps/0`. */
2509
+ path: string;
2510
+ kind: string;
2511
+ /** When it started (a click's press). */
2512
+ t_ms: number;
2513
+ /** When it ended. */
2514
+ end_ms: number;
2515
+ }
2516
+
2517
+ /** A box in `window.units`. `name` is set on the two regions the sheet crops, `R1` and `R2`. */
2518
+ export interface InspectionRegion {
2519
+ x: number;
2520
+ y: number;
2521
+ w: number;
2522
+ h: number;
2523
+ name?: "R1" | "R2";
2524
+ }
2525
+
2526
+ export interface InspectionRect {
2527
+ x: number;
2528
+ y: number;
2529
+ w: number;
2530
+ h: number;
2531
+ }
2532
+
2533
+ /**
2534
+ * What changed from each frame to the next. A pixel changed when its luma moved by more than 24 levels; frames are read on a 2 px grid. Times are `t_ms` in the window's clock and frames are indexes from 0.
2535
+ */
2536
+ export interface InspectionReport {
2537
+ /**
2538
+ * `[frame, share]` for every frame where at least 0.1% of the picture changed against the frame before.
2539
+ */
2540
+ changed: [number, number, ...unknown[]][];
2541
+ /**
2542
+ * Runs of changed frames, joined across quiet gaps of up to 2 frames at 30 fps (about 67 ms), with their changed regions (16 px cells, at most 4 per event, largest first).
2543
+ */
2544
+ events: InspectionEvent[];
2545
+ /** Content that moved vertically by more than 2 px from one frame to the next. */
2546
+ shifts: InspectionShift[];
2547
+ /**
2548
+ * A region of at least 0.5% of the picture that changed and came back within 100 ms (A, then B, then A).
2549
+ */
2550
+ flashes: InspectionFlash[];
2551
+ /**
2552
+ * Frames where at least 40% of the picture was replaced while the frames either side changed by at most 5%.
2553
+ */
2554
+ cuts: InspectionCut[];
2555
+ /** Three or more frames without a move between two scroll shifts the same way. */
2556
+ stalls: InspectionStall[];
2557
+ /** `[y0, y1)` rows left out of the analysis: a video's caption rows. Left out when none. */
2558
+ masked?: number[][];
2559
+ network?: InspectionNetwork;
2560
+ }
2561
+
2562
+ export interface InspectionEvent {
2563
+ /** The first changed frame. */
2564
+ t0_ms: number;
2565
+ /** The settled frame, the first one after the last change (the last frame when it never settled). */
2566
+ t1_ms: number;
2567
+ /** The largest changed share in the run. */
2568
+ peak: number;
2569
+ peak_ms: number;
2570
+ /** Changed frames in the run. */
2571
+ frames: number;
2572
+ /** False when the window ended while it was still changing. */
2573
+ settled: boolean;
2574
+ /** The step that started at most 100 ms before the run, such as `steps/0`. */
2575
+ after_step?: string;
2576
+ regions: InspectionRegion[];
2577
+ }
2578
+
2579
+ export interface InspectionShift {
2580
+ t_ms: number;
2581
+ frame: number;
2582
+ /** How far it moved; positive is down. */
2583
+ dy: number;
2584
+ /** The row, in the frame before, where the moved content starts (0 when `whole`). */
2585
+ from_y: number;
2586
+ /** `scroll` when the page's scroll offset moved by the same amount, else `layout`. */
2587
+ kind: "scroll" | "layout";
2588
+ /** It moved 8 px or more. */
2589
+ large: boolean;
2590
+ /** Everything moved, the top of the picture included. */
2591
+ whole: boolean;
2592
+ }
2593
+
2594
+ export interface InspectionFlash {
2595
+ t_ms: number;
2596
+ frame: number;
2597
+ /** How long it showed. */
2598
+ ms: number;
2599
+ region: InspectionRegion;
2600
+ /** `lighter` or `darker` when the region's mean luma moved by 16 levels or more. */
2601
+ kind: "lighter" | "darker" | "other";
2602
+ }
2603
+
2604
+ export interface InspectionCut {
2605
+ t_ms: number;
2606
+ frame: number;
2607
+ /** The share of the picture that changed. */
2608
+ share: number;
2609
+ /** `camera_cut` is a cut the video's camera planned (video source only). */
2610
+ kind: "cut" | "camera_cut";
2611
+ }
2612
+
2613
+ export interface InspectionStall {
2614
+ /** The first frame without a move. */
2615
+ t0_ms: number;
2616
+ /** The frame where the scroll moved again. */
2617
+ t1_ms: number;
2618
+ frames: number;
2619
+ }
2620
+
2621
+ /**
2622
+ * How long the page's clock waited on the network (page source only). Network waits are not page time, so they never show in `t_ms`.
2623
+ */
2624
+ export interface InspectionNetwork {
2625
+ /** Wall-clock ms the page's clock was held while requests were in flight. */
2626
+ held_ms: number;
2627
+ /** How many times it was held. */
2628
+ waits: number;
2629
+ /** Page time run ahead of the window off camera (0 for an inspection, which never runs ahead). */
2630
+ ahead_ms: number;
2631
+ }
2632
+
2633
+ export interface InspectionTrace {
2634
+ target: InspectionWatchTarget;
2635
+ /** Whether the target matched an element on any frame. */
2636
+ found: boolean;
2637
+ /** The first 40 characters of the element's text or `aria-label`. */
2638
+ label?: string;
2639
+ /**
2640
+ * `[t_ms, x, y, w, h, visible]` in viewport CSS px (to 0.5 px), on the first frame and on every frame where a value changed by 1 px or more or visibility changed. `visible` is false when the element is hidden, has an empty box or lies outside the viewport.
2641
+ */
2642
+ boxes: [number, number, number, number, number, boolean, ...unknown[]][];
2643
+ /** Each change of the box against the entry before it. */
2644
+ moves: {
2645
+ t_ms: number;
2646
+ dx: number;
2647
+ dy: number;
2648
+ dw: number;
2649
+ dh: number;
2650
+ }[];
2651
+ }
2652
+
2653
+ export interface InspectionLayoutShift {
2654
+ /** The frame the shift showed on. */
2655
+ t_ms: number;
2656
+ sources: {
2657
+ /** A unique CSS selector for the element that moved. */
2658
+ selector: string;
2659
+ /** The first 40 characters of its text or `aria-label`. */
2660
+ label?: string;
2661
+ from: InspectionRect;
2662
+ to: InspectionRect;
2663
+ }[];
2664
+ }
2665
+
2666
+ /**
2667
+ * The contact sheet: up to 12 tiles in reading order, each under a black strip with its time, frame, changed share and word tags (`CLICK steps/0`, `SHIFT -29`, `FLASH 67 ms`, `CUT`), changed regions outlined in magenta, then before/after crops of `R1` and `R2`. Tiles go to the first and last frames, flashes, cuts, shifts, the start and end of each event and each step, then where most pixels changed. Positions here are sheet px.
2668
+ */
2669
+ export interface InspectionSheet {
2670
+ artifact: Artifact;
2671
+ width: number;
2672
+ height: number;
2673
+ /** ceil(width / 28) x ceil(height / 28), the image's cost for a model that reads 28 px patches. */
2674
+ tokens: number;
2675
+ tiles: InspectionTile[];
2676
+ crops: InspectionCrop[];
2677
+ }
2678
+
2679
+ export interface InspectionTile {
2680
+ frame: number;
2681
+ t_ms: number;
2682
+ x: number;
2683
+ y: number;
2684
+ w: number;
2685
+ h: number;
2686
+ tags: string[];
2687
+ }
2688
+
2689
+ /**
2690
+ * One region before and after its change, the region plus 16 px around it, scaled by `scale` (at most 2). Before is the frame just before the change; after is its settled frame (for a flash, the flash frame).
2691
+ */
2692
+ export interface InspectionCrop {
2693
+ region: "R1" | "R2";
2694
+ before_ms: number;
2695
+ after_ms: number;
2696
+ scale: number;
2697
+ /** The part of the frame shown, in `window.units`. */
2698
+ area: InspectionRegion;
2699
+ /** Where the before panel is on the sheet. */
2700
+ before: InspectionRect;
2701
+ /** Where the after panel is on the sheet. */
2702
+ after: InspectionRect;
2703
+ }
2704
+
2112
2705
  export interface Artifact {
2113
2706
  id: string;
2114
2707
  object: "artifact";
@@ -2264,9 +2857,21 @@ export interface VideoOutput {
2264
2857
 
2265
2858
  export type VideoFormat = "mp4" | "gif" | "poster";
2266
2859
 
2860
+ /**
2861
+ * Give exactly one of `beats` and `goal` (422 `script_invalid` at `/goal` otherwise). `goal` takes no `source.profile` (422 `script_invalid` at `/source/profile`): a goal is planned on public pages only.
2862
+ */
2267
2863
  export interface VideoCreateRequest {
2268
2864
  source: VideoSource;
2269
- beats: Beat[];
2865
+ /** The script, one beat per line of narration. Leave it out and give `goal` to have the node plan it. */
2866
+ beats?: Beat[];
2867
+ /**
2868
+ * What the video should show, in a sentence ("Show how to open billing and switch the plan to annual").
2869
+ * The node plans the beats from the start page (the operation's description says how) and the video
2870
+ * shows them in `goal`. Needs `vision:run` and `infer:run` besides `render:run`. Not with
2871
+ * `source.profile`: a goal is planned on public pages only.
2872
+ */
2873
+ goal?: string;
2874
+ alias?: VideoAliasName;
2270
2875
  /**
2271
2876
  * The narration voice. Leave it out and every beat with `say` is narrated in the node's default voice,
2272
2877
  * `kokoro-82m` `af_heart`, normalized to -16 LUFS. Narration is speech made as the caller, so it needs
@@ -2603,6 +3208,7 @@ export interface RecordingInfo {
2603
3208
  }
2604
3209
 
2605
3210
  export interface VideoRestyleRequest {
3211
+ alias?: VideoAliasName;
2606
3212
  style?: RenderStyle;
2607
3213
  captions?: CaptionOptions;
2608
3214
  output?: VideoOutput;
@@ -2616,23 +3222,144 @@ export interface VideoShareRequest {
2616
3222
  title?: string;
2617
3223
  }
2618
3224
 
3225
+ /**
3226
+ * A public share of a video or an alias. Its URLs are on `usercontent.b3os.org` and need no key:
3227
+ *
3228
+ * - `/s/<share id>`: the player page (HTML, Open Graph and JSON-LD for link previews, its own iframe embed).
3229
+ * Query parameters shape the player: `autoplay=1` (starts muted, as browsers require), `muted=1`, `loop=1`,
3230
+ * `controls=0` and `t=<seconds>` (0 to 86400, where it starts); others are ignored.
3231
+ * - `/s/<share id>/<file>`: the share's current file (`video.mp4`, `poster.jpg`, `video.gif`,
3232
+ * `captions.vtt`, `chapters.vtt`), the URLs in `media`. For an alias share they change bytes when the alias
3233
+ * moves (the `ETag` changes with them).
3234
+ * - `/s/<share id>/v/<video host id>/<file>`: a file of one video, which the page itself plays, so a player
3235
+ * keeps one video's bytes. For an alias, the video it left stays served for an hour after it moves.
3236
+ * - `/oembed?url=<share URL>` (`oembed_url`): the oEmbed answer (JSON, type `video`), an iframe of the page at
3237
+ * most 960 wide (`maxwidth` and `maxheight` make it smaller) plus a 32-pixel footer.
3238
+ *
3239
+ * A stopped, expired or taken-down share answers 404 on its files and oEmbed, and a short page on its own URL
3240
+ * (404, 410 for a video that expired, 451 when B3 took it down). Every answer may be cached for 60 seconds at
3241
+ * most, and each address may make 600 requests a minute (`render.share.address.rpm`).
3242
+ */
2619
3243
  export interface VideoShare {
2620
3244
  object: "video_share";
2621
- video_id: string;
2622
- /** The share page's artifact (kind `share`, `share.html`). */
2623
- artifact_id: string;
3245
+ /** The share ID. Unguessable (128 random bits); its host-safe form (`shr-…`) is in `url`. */
3246
+ id: string;
3247
+ /** The video it plays now (for an alias share, the one the alias points at; `null` when none). */
3248
+ video_id: string | null;
3249
+ /** The alias for an alias share, else `null`. */
3250
+ alias: string | null;
2624
3251
  title: string;
2625
- /** The share page, a signed `usercontent.b3os.org` URL valid until `expires_at`. */
3252
+ /** The share page, `https://usercontent.b3os.org/s/shr-…`. */
2626
3253
  url: string;
2627
- /** An `<iframe>` of the page, 960 wide at the video's aspect ratio, ready to paste. */
3254
+ /**
3255
+ * An `<iframe>` of the page, ready to paste: 960 pixels wide (less for a narrower video) at the video's aspect ratio plus the page's 32-pixel footer.
3256
+ */
2628
3257
  embed_html: string;
3258
+ /** The oEmbed answer for `url`. */
3259
+ oembed_url: string;
3260
+ media: VideoShareMedia;
2629
3261
  /** The video's width in pixels. */
2630
3262
  width: number;
2631
3263
  /** The video's height in pixels. */
2632
3264
  height: number;
2633
3265
  created_at: string;
2634
- /** When the page and its link end (the MP4's own expiry). */
2635
- expires_at: string;
3266
+ /**
3267
+ * When the share ends: the video's own expiry for a video share (`null` while an alias keeps the video, as the video's own `expires_at` is then); `null` for an alias share, which lasts as long as the alias.
3268
+ */
3269
+ expires_at: string | null;
3270
+ /**
3271
+ * `true` when B3 took the share down: its page answers 451 and its files and oEmbed 404, and sharing it again answers 403 `share_blocked` until B3 lifts the takedown. The reason is not shown; write to abuse@b3os.org to ask about it. The node learns of a takedown within about 10 minutes.
3272
+ */
3273
+ blocked: boolean;
3274
+ }
3275
+
3276
+ /** Stable URLs of the share's files, for a README image or a `<video>` written by hand. */
3277
+ export interface VideoShareMedia {
3278
+ mp4: string;
3279
+ poster?: string;
3280
+ gif?: string;
3281
+ /** WebVTT captions. */
3282
+ captions?: string;
3283
+ /** WebVTT chapters (beat titles). */
3284
+ chapters?: string;
3285
+ }
3286
+
3287
+ export interface VideoShareRef {
3288
+ id: string;
3289
+ url: string;
3290
+ /**
3291
+ * `true` when B3 took the share down (its page answers 451); the reason is not shown. See `VideoShare.blocked`.
3292
+ */
3293
+ blocked: boolean;
3294
+ }
3295
+
3296
+ /**
3297
+ * Tags the video with this alias of the project and makes the alias if it does not exist. When the video
3298
+ * succeeds, the alias points at it (unless it is pinned, or a newer tagged video already succeeded), and the
3299
+ * video is kept past the 7-day retention while it does. Its files count toward `render.kept.bytes`; a video
3300
+ * that would pass that limit still succeeds but is kept 7 days, leaves the alias where it was and warns
3301
+ * `alias_storage`. A new alias past `render.aliases.max` answers 422 `limit_exceeded`. Needs `render:write`
3302
+ * (a tag can change what a live share plays). A video recorded with `source.profile` never moves an alias that
3303
+ * has a share: it warns `alias_signed_in`, and `PUT` with `video_id` moves the alias to it.
3304
+ */
3305
+ export type VideoAliasName = string;
3306
+
3307
+ export interface VideoAliasPutRequest {
3308
+ /** Point the alias at this tagged, succeeded video and pin it there (`follow` becomes `false`). */
3309
+ video_id?: string;
3310
+ /**
3311
+ * `true`: move to the newest succeeded tagged video now and with every later one. `false`: stay where it is. With `video_id`, only `false` may be given.
3312
+ */
3313
+ follow?: boolean;
3314
+ }
3315
+
3316
+ export interface VideoAlias {
3317
+ object: "video_alias";
3318
+ id: string;
3319
+ name: VideoAliasName;
3320
+ /** The video the alias points at, kept while it does; `null` before one succeeded. */
3321
+ video_id: string | null;
3322
+ /** Whether a newly succeeded tagged video moves the alias (`false` after `PUT` with `video_id`). */
3323
+ follow: boolean;
3324
+ /** The newest 20 videos tagged with the alias, newest first, expired ones left out. */
3325
+ videos: {
3326
+ video_id: string;
3327
+ status: JobStatus;
3328
+ created_at: string;
3329
+ }[];
3330
+ /** The alias's share, if any; `blocked` says when B3 took it down. */
3331
+ share: VideoShare | null;
3332
+ created_at: string;
3333
+ updated_at: string;
3334
+ }
3335
+
3336
+ export type VideoAliasList = Omit<ListEnvelope, "data"> & {
3337
+ data: VideoAlias[];
3338
+ };
3339
+
3340
+ /**
3341
+ * A video made from a `goal`: what was asked and the beats the node planned. `state` is `drafting` while the
3342
+ * job's draft phase runs, `drafted` once the beats are planned (they are then the video's script), `failed`
3343
+ * when planning failed (the job's `error` is `goal_unplanned`).
3344
+ */
3345
+ export interface VideoGoal {
3346
+ /** The goal as given. */
3347
+ text: string;
3348
+ state: "drafting" | "drafted" | "failed";
3349
+ /** The planned beats; send them as `beats` to record the same steps again. */
3350
+ beats?: Beat[];
3351
+ /** Whether the planned steps ran once in a browser before recording. */
3352
+ checked?: boolean;
3353
+ /** Steps the model wrote that the page could not run, left out of `beats`. */
3354
+ dropped?: number;
3355
+ /** Buttons, links and fields the start page listed. */
3356
+ controls?: number;
3357
+ /** Controls the planned steps revealed that the start page did not show (a form, the next page). */
3358
+ more?: number;
3359
+ /** The chat model that planned the beats. */
3360
+ model?: string;
3361
+ /** How long planning took. */
3362
+ plan_ms?: number;
2636
3363
  }
2637
3364
 
2638
3365
  export interface VideoResult {
@@ -2651,7 +3378,7 @@ export interface VideoResult {
2651
3378
  recording?: RecordingInfo;
2652
3379
  narration?: NarrationInfo;
2653
3380
  /**
2654
- * Non-fatal problems, each starting with a code and a colon: `narration_scope` (the beats' `say` lines were not spoken because the key lacks `infer:run`, which narration needs; the video has no narration track); `page_requests` (requests for the page's code, styles or fonts, or for its own site's data, made while the video was captured, were not in the network recording made when it loaded, so they failed and the video can show a page that did not finish loading; up to three are named, without their query; trackers, beacons and prefetches that fail the same way are not counted); `zoom_soft` (the page drew differently between two parts of the capture and the video could not be captured again whole, so from the time it names on the video comes from a lower device scale and its zooms are softer than the page); `background_fallback` (the library image the `auto` background or `background_ref: "auto"` chose could not be loaded in time; the video was drawn on the studio pick, or the style's own background, and a restyle tries again); `scroll_round_trip` (the steps make the page scroll down and back up, or up and back down, within 4 s and no one scroll position shows every element they act on, so the video runs both scrolls; the timeline's `warnings` has the code too); `auto_background_pin` (the project's, organization's or node's `auto_background` pin does not clear the first frame's edges, so `auto` picked another image; it names both). A restyle repeats its source's, except `background_fallback`, which it decides again, and `auto_background_pin`, which it repeats only when it draws the source's image again (a restyle that picks the background again says its own, and one that draws another background says none). Absent when there is nothing to say.
3381
+ * Non-fatal problems, each starting with a code and a colon: `narration_scope` (the beats' `say` lines were not spoken because the key lacks `infer:run`, which narration needs; the video has no narration track); `page_requests` (requests for the page's code, styles or fonts, or for its own site's data, made while the video was captured, were not in the network recording made when it loaded, so they failed and the video can show a page that did not finish loading; up to three are named, without their query; trackers, beacons and prefetches that fail the same way are not counted); `zoom_soft` (the page drew differently between two parts of the capture and the video could not be captured again whole, so from the time it names on the video comes from a lower device scale and its zooms are softer than the page); `background_fallback` (the library image the `auto` background or `background_ref: "auto"` chose could not be loaded in time; the video was drawn on the studio pick, or the style's own background, and a restyle tries again); `scroll_round_trip` (the steps make the page scroll down and back up, or up and back down, within 4 s and no one scroll position shows every element they act on, so the video runs both scrolls; the timeline's `warnings` has the code too); `auto_background_pin` (the project's, organization's or node's `auto_background` pin does not clear the first frame's edges, so `auto` picked another image; it names both); `alias_storage` (the video is tagged with an alias but its files would pass the organization's `render.kept.bytes`, so it is kept 7 days like any video and the alias did not move to it); `alias_signed_in` (the video was recorded with `source.profile` and its alias has a share, so the alias did not move to it; `PUT /v1/render/aliases/{alias}` with `video_id` moves it); `alias_unshareable` (the video's MP4 is larger than the node uploads to storage, from which shares serve files, so the alias did not move to it); `goal_steps_dropped` (the goal's planned steps that the page could not run were left out; it says how many). A restyle repeats its source's, except `background_fallback`, which it decides again, and `auto_background_pin`, which it repeats only when it draws the source's image again (a restyle that picks the background again says its own, and one that draws another background says none). Absent when there is nothing to say.
2655
3382
  */
2656
3383
  warnings?: string[];
2657
3384
  auto_background?: AutoBackgroundChoice;
@@ -2670,7 +3397,11 @@ export interface NarrationInfo {
2670
3397
  reason?: string;
2671
3398
  }
2672
3399
 
2673
- /** A video job (`vid_…`). `progress` counts phases (voice, plan, capture, compose, encode, upload). */
3400
+ /**
3401
+ * A video job (`vid_…`). `progress` counts phases (voice, plan, capture, compose, encode, upload; a video made
3402
+ * from a `goal` starts with draft). While an alias points at the video (`kept_by_alias`), `expires_at` is
3403
+ * `null`: the video is kept until the alias moves on, then for 24 hours more.
3404
+ */
2674
3405
  export type Video = Omit<Job, "id" | "object" | "result"> & {
2675
3406
  id: string;
2676
3407
  object: "video";
@@ -2684,6 +3415,15 @@ export type Video = Omit<Job, "id" | "object" | "result"> & {
2684
3415
  */
2685
3416
  queue_position?: number;
2686
3417
  result?: VideoResult;
3418
+ /** The alias the video was created or restyled with, if any. */
3419
+ alias?: string | null;
3420
+ /** The alias that points at the video and keeps it past the retention, if any. */
3421
+ kept_by_alias?: string | null;
3422
+ /**
3423
+ * The video's own share, if any (`POST /v1/render/videos/{video_id}/share`); `blocked: true` when B3 took it down.
3424
+ */
3425
+ share?: VideoShareRef | null;
3426
+ goal?: VideoGoal;
2687
3427
  };
2688
3428
 
2689
3429
  export type VideoList = Omit<ListEnvelope, "data"> & {
@@ -2693,11 +3433,16 @@ export type VideoList = Omit<ListEnvelope, "data"> & {
2693
3433
  /**
2694
3434
  * An event of a video's stream. `job.queued` carries `queue_position` when the video waits for a slot (its
2695
3435
  * place when it was created; the video itself has the current one); `video.phase` carries `phase`;
3436
+ * `video.drafted` (a video made from a `goal`) carries the planned `beats`, `checked`, `dropped` and `model`;
2696
3437
  * `video.artifact` carries `artifact` (without a signed URL; fetch the artifact or the video for one).
2697
3438
  */
2698
3439
  export type VideoEvent = JobEvent & {
2699
3440
  queue_position?: number;
2700
- phase?: "voice" | "plan" | "capture" | "compose" | "encode" | "upload";
3441
+ phase?: "draft" | "voice" | "plan" | "capture" | "compose" | "encode" | "upload";
3442
+ beats?: Beat[];
3443
+ checked?: boolean;
3444
+ dropped?: number;
3445
+ model?: string;
2701
3446
  artifact?: Artifact;
2702
3447
  };
2703
3448
 
@@ -3476,9 +4221,9 @@ export type RenderBackgroundPackList = Omit<ListEnvelope, "data"> & {
3476
4221
  };
3477
4222
 
3478
4223
  /**
3479
- * `running` → `paused` ↔ `running` → `stopped`. `failed` means the microVM crashed; its usage is final.
4224
+ * `running` → `paused` ↔ `running` → `stopped`. `failed` means the microVM crashed; its usage is final. `hibernated` is an agent instance's microVM written to the node's disk with no process left (only agent instances, `/v1/agents`): its memory snapshot, which a message to its instance or a request to its port restores in place, or its disk alone (dormant), which a message to its instance boots. It is never listed.
3480
4225
  */
3481
- export type SandboxStatus = "running" | "paused" | "stopped" | "failed";
4226
+ export type SandboxStatus = "running" | "paused" | "stopped" | "failed" | "hibernated";
3482
4227
 
3483
4228
  /**
3484
4229
  * A value placed in the environment but never returned or logged; either the value itself or a field of a vault connection.
@@ -3496,6 +4241,11 @@ export type SecretValue =
3496
4241
  };
3497
4242
 
3498
4243
  export interface SandboxPort {
4244
+ /**
4245
+ * The port the app listens on inside the sandbox. Not 53, 1080, 3128, 7700 or 15001: the B3OS guest agent
4246
+ * listens on those in every sandbox (its API proxy, egress proxies and DNS), so they are never proxied and
4247
+ * a create that declares one is `400 invalid_request`.
4248
+ */
3499
4249
  port: number;
3500
4250
  /**
3501
4251
  * Reachable by anyone with the sandbox's long-lived port URL (`ports[].url` in the sandbox; its token lasts 7
@@ -3511,6 +4261,14 @@ export interface SandboxPort {
3511
4261
  * @default 65
3512
4262
  */
3513
4263
  first_byte_s?: number;
4264
+ /**
4265
+ * The port has an app address (`<label>.b3os.io`); `b3os apply` sets it on such a port and keeps the port
4266
+ * private (no long-lived URL). The sandbox then counts as reachable from the internet for as long as it
4267
+ * lives, as with a public port: code in another sandbox whose egress is not `public` cannot reach into it,
4268
+ * and code in such a sandbox cannot start one with an addressed port (`403 egress_escalation`).
4269
+ * @default false
4270
+ */
4271
+ addressed?: boolean;
3514
4272
  }
3515
4273
 
3516
4274
  /**
@@ -3530,12 +4288,34 @@ export interface SandboxApiGrant {
3530
4288
  spend_cap_usd?: number | null;
3531
4289
  /** Vault connections the sandbox's action calls may use. */
3532
4290
  connections?: string[];
4291
+ actions?: SandboxActionsRule;
3533
4292
  }
3534
4293
 
3535
4294
  /**
3536
- * Where sandbox traffic may go, enforced by the node's egress guard. `public` (default): any public internet
3537
- * address. `allowlist`: only hosts matching `allow` (exact hosts or `*.` wildcards). `deny`: no outbound
3538
- * network at all. Private, loopback, tailnet and metadata addresses are always refused. Without `egress`, a
4295
+ * Which pack actions code in the sandbox may call (`POST /v1/actions/call`) and which it gets as tools over MCP
4296
+ * (`POST /v1/actions/mcp`, at `B3OS_MCP_URL`, which the node sets when `allow` names an entry and the grant
4297
+ * holds `actions:read`). Without it (the default, or `null`), the creating principal's rule: none for an API
4298
+ * key, so any action your scopes allow; a sandbox's own rule for the sandboxes it creates, which may only
4299
+ * narrow it (`403 forbidden`, `reason: scope_escalation`). A call outside the rule is refused with
4300
+ * `403 action_not_allowed` before anything is read, bound or billed. `b3os apply` and the GitHub App write one
4301
+ * entry per pack a service declares in `uses`, at the version `actions.packs` gives, so a service calls the
4302
+ * tools it declared and no other pack. A routine run the sandbox starts runs as its publisher within the rule
4303
+ * (a step outside it fails with `action_not_allowed`), and the sandbox signals or sends events only to runs
4304
+ * within its rule. Read routes (describe, the pack and tools routes) are not bounded.
4305
+ */
4306
+ export type SandboxActionsRule = {
4307
+ /**
4308
+ * `<namespace>/<name>/<action>[@<version>]`: `<action>` an action key or `*` (every action of the pack),
4309
+ * `<version>` an exact version or a range (`1.0.1`, `1`, `1.2`, `^1.2`); without one, any version. A call
4310
+ * that names a range runs the newest allowed version it admits. Empty: no pack action at all.
4311
+ */
4312
+ allow: string[];
4313
+ } | null;
4314
+
4315
+ /**
4316
+ * Where sandbox traffic may go, enforced by the node's egress guard. `public` (default): any public internet
4317
+ * address. `allowlist`: only hosts matching `allow` (exact hosts or `*.` wildcards). `deny`: no outbound
4318
+ * network at all. Private, loopback, tailnet and metadata addresses are always refused. Without `egress`, a
3539
4319
  * sandbox created by code in another sandbox gets that sandbox's policy, and a policy within it is the most
3540
4320
  * such code can ask for (`403 forbidden`, `reason: egress_escalation`), and it gets no public port unless that
3541
4321
  * sandbox's egress is `public`. A sandbox has at most
@@ -3551,14 +4331,21 @@ export interface EgressPolicy {
3551
4331
 
3552
4332
  export interface SandboxCreateRequest {
3553
4333
  /**
3554
- * Template name or `tpl_` ID. Ignored when `snapshot` is set.
4334
+ * Template name or `tpl_` ID: a node template (`GET /v1/sandboxes/templates`) or one of your project's
4335
+ * image templates (an image's `template`). Ignored when `snapshot` is set.
3555
4336
  * @default "base"
3556
4337
  */
3557
4338
  template?: string;
3558
4339
  /** Restore this snapshot instead of starting from a template. */
3559
4340
  snapshot?: string;
4341
+ /**
4342
+ * Start from one of your project's imported images (`POST /v1/images`), once it is `ready`. Needs the
4343
+ * `images.import` flag on for your organization. Not with `template` or `snapshot` (`400 invalid_request`).
4344
+ */
4345
+ image?: string;
3560
4346
  /**
3561
4347
  * Virtual CPUs; defaults to the template's (`defaults.vcpu`), at most your plan's `sandboxes.vcpu_max`.
4348
+ * A sandbox from an image has the image's size: any other value answers `400 invalid_request`.
3562
4349
  * A microVM cannot change its vCPU count, so sandboxes come from pools per size: a create at one of the
3563
4350
  * template's `size_classes` claims a pre-warmed microVM, any other size is restored on demand (a pool
3564
4351
  * miss: tens of milliseconds, plus about two seconds the first time a node sees that size). A node
@@ -3630,9 +4417,119 @@ export interface SandboxCreateRequest {
3630
4417
  * `X-B3OS-Options` header.
3631
4418
  */
3632
4419
  clone_reset?: "full" | "none";
4420
+ /**
4421
+ * A volume to mount (`POST /v1/sandboxes/volumes`), held by this sandbox alone until it ends: at most one in
4422
+ * this beta (mount several of its folders with `subpath`). A volume another running or paused sandbox
4423
+ * holds is `409 volume_in_use`. The sandbox cannot be snapshotted or forked (`409 volume_attached`), and
4424
+ * `forkable: true` is refused. When the sandbox ends, its guest syncs and unmounts the volume first; the
4425
+ * volume is free for the next sandbox once the microVM has exited.
4426
+ */
4427
+ volumes?: VolumeAttach[];
4428
+ owner?: SandboxOwner;
4429
+ metadata?: Metadata;
4430
+ }
4431
+
4432
+ export interface VolumeAttach {
4433
+ /** The volume's `vol_` ID or name. */
4434
+ volume: string;
4435
+ mounts: VolumeMount[];
4436
+ /**
4437
+ * `uid` or `uid:gid` that owns the volume's root and each subpath folder when they are first made; default,
4438
+ * the account commands run as (`user`, uid 1000, or an image's `USER`). Later mounts change no owner.
4439
+ */
4440
+ owner?: string;
4441
+ }
4442
+
4443
+ export interface VolumeMount {
4444
+ /**
4445
+ * Where the folder appears in the sandbox: absolute, not `/`, not a system folder or under one (`/proc`,
4446
+ * `/sys`, `/dev`, `/run`, `/etc`, `/usr`, `/boot`, `/bin`, `/sbin`, `/lib*`, `/mnt`, `/var/run`); mount under
4447
+ * `/workspace`, `/data`, `/home`, `/srv`, `/opt` or `/var/lib`. Two mounts of a sandbox never overlap.
4448
+ */
4449
+ path: string;
4450
+ /** A folder of the volume (made on first use); empty or absent for the volume's root. */
4451
+ subpath?: string;
4452
+ /** @default false */
4453
+ read_only?: boolean;
4454
+ }
4455
+
4456
+ export interface SandboxVolume {
4457
+ volume_id: string;
4458
+ name: string;
4459
+ mounts: VolumeMount[];
4460
+ owner?: string | null;
4461
+ }
4462
+
4463
+ export interface Volume {
4464
+ id: string;
4465
+ object: "volume";
4466
+ name: string;
4467
+ size_gib: number;
4468
+ /**
4469
+ * `attached` from the create of the sandbox that holds it until that sandbox's microVM has exited; `deleted` until `purge_at`.
4470
+ */
4471
+ status: "available" | "attached" | "deleted";
4472
+ attached_to: null | {
4473
+ sandbox_id: string;
4474
+ since: string;
4475
+ };
4476
+ /** What the volume's file system held at its last mount or stats read; null before its first mount. */
4477
+ used_bytes: number | null;
4478
+ metadata: Metadata;
4479
+ created_at: string;
4480
+ deleted_at: string | null;
4481
+ /** When a deleted volume and its data are removed for good. */
4482
+ purge_at: string | null;
4483
+ }
4484
+
4485
+ export type VolumeList = Omit<ListEnvelope, "data"> & {
4486
+ data: Volume[];
4487
+ };
4488
+
4489
+ export interface VolumeCreateRequest {
4490
+ /** Unique among the project's volumes, deleted ones included until they are purged. */
4491
+ name: string;
4492
+ /** At most your plan's `sandboxes.volume_max`. */
4493
+ size_gib: number;
4494
+ metadata?: Metadata;
4495
+ }
4496
+
4497
+ export interface VolumeUpdateRequest {
4498
+ /** A larger size; a volume never shrinks. */
4499
+ size_gib?: number;
3633
4500
  metadata?: Metadata;
3634
4501
  }
3635
4502
 
4503
+ export interface VolumePurgeRequest {
4504
+ /** The volume's name. */
4505
+ confirm: string;
4506
+ }
4507
+
4508
+ /**
4509
+ * Who the sandbox belongs to, which decides what its key can do to it.
4510
+ *
4511
+ * - `key` (the default): the sandbox acts as the key that created it. It stops when that key is revoked or
4512
+ * expires (`stop_reason: revoked`), and its B3OS calls count toward the key's spend cap: an agent's sandbox
4513
+ * lives no longer than the credential that made it.
4514
+ * - `project`: a service of an application. It acts as its project, within its `api` grant (scopes and
4515
+ * connections), and holds no key: a key's expiry or revoke never stops it. The key that created it is kept as
4516
+ * `created_by_key`. Its spend cap: with `api.spend_cap_usd`, that cap, its own; without one, the creating
4517
+ * key's cap, shared with everything else that key runs: its usage counts toward that key's `spent_usd`, and
4518
+ * the key's cap stops it (`stop_reason: budget`), also after the key is revoked or expires. Both caps count
4519
+ * the whole billing period and survive restarts of the node. What else stops it: its organization suspended or
4520
+ * out of credits (`budget`), a delete or a take down (`deleted`), and B3. Needs `metadata."b3os.app"` (`400
4521
+ * invalid_request` otherwise), so it is listed under its application with a Take down, and an outside caller
4522
+ * (an API key, a CLI token, the console): a sandbox's own credential gets `403 forbidden` with `reason:
4523
+ * sandbox`, a routine run `reason: routine`. `b3os apply` (CLI 0.2.2) and the GitHub App create services this
4524
+ * way. A fork of it belongs to the key that forks it.
4525
+ *
4526
+ * What a service's own code starts (a create or a fork with the service's credential) is the service's:
4527
+ * `owner: project`, `parent` its creator and `root` the service. It holds no key either, and it ends when
4528
+ * the service ends (`stop_reason: revoked`), however long its own timeout or lease, so a take down reaches
4529
+ * everything a service started.
4530
+ */
4531
+ export type SandboxOwner = "key" | "project";
4532
+
3636
4533
  /**
3637
4534
  * When the sandbox counts as ready: a TCP port inside it accepting connections (`port`), or a command that
3638
4535
  * exits 0 (`cmd`, run as `user` with a 5 s limit per try). Set exactly one. The node tries it every
@@ -3713,6 +4610,8 @@ export interface Sandbox {
3713
4610
  ports: {
3714
4611
  port: number;
3715
4612
  public: boolean;
4613
+ /** The port has an app address (the create set `addressed`); always sent by this node. */
4614
+ addressed?: boolean;
3716
4615
  /**
3717
4616
  * Public ports: the long-lived preview URL, token included. Private ports: `null`; mint a URL with
3718
4617
  * `POST /v1/sandboxes/{sandbox_id}/ports/{port}/url`. Also `null` when code in another sandbox reads
@@ -3729,6 +4628,14 @@ export interface Sandbox {
3729
4628
  /** The grant's own cap, or `null` when the creating principal's cap applies. */
3730
4629
  spend_cap_usd: number | null;
3731
4630
  connections: string[];
4631
+ /**
4632
+ * The actions rule the sandbox holds (the grant's, or the one it inherited from the sandbox that created
4633
+ * it), or `null` when it holds none; a node before release 1118 leaves the member out. Its packs are the
4634
+ * sandbox's tools at `B3OS_MCP_URL`.
4635
+ */
4636
+ actions?: {
4637
+ allow: string[];
4638
+ } | null;
3732
4639
  };
3733
4640
  egress: {
3734
4641
  mode: "public" | "allowlist" | "deny";
@@ -3743,7 +4650,9 @@ export interface Sandbox {
3743
4650
  * Why the sandbox stopped: `deleted`, `timeout` (it reached `expires_at`), `failed` (the microVM crashed),
3744
4651
  * `budget` (while it ran, its organization was suspended or ran out of credits, or the creating key or
3745
4652
  * the sandbox's own `api.spend_cap_usd` reached its cap; the node checks every 10 s) or `revoked` (the key
3746
- * that created it was revoked).
4653
+ * that created it was revoked or expired, or, for a sandbox a service started, the service at its `root`
4654
+ * ended). A project's service never stops for its key's revoke or expiry; for the key's spend cap only when
4655
+ * its grant sets no cap of its own.
3747
4656
  */
3748
4657
  stop_reason: "deleted" | "timeout" | "failed" | "budget" | "revoked" | null;
3749
4658
  usage: {
@@ -3758,7 +4667,33 @@ export interface Sandbox {
3758
4667
  };
3759
4668
  /** The readiness probe and what it found; `null` when the sandbox has none. */
3760
4669
  readiness?: null | Readiness;
4670
+ /**
4671
+ * The sandbox's lease (`PUT /v1/sandboxes/{sandbox_id}/lease`): while `held`, the node keeps the sandbox
4672
+ * running and renews its `expires_at` itself. `null` when it never held one. Always sent by this node.
4673
+ */
4674
+ lease?: null | SandboxLease;
4675
+ /**
4676
+ * The processes the node supervises (an exec with `background: true` and `restart`), oldest first; empty
4677
+ * when there are none. Always sent by this node.
4678
+ */
4679
+ supervised?: SupervisedProcess[];
4680
+ /** The volume the sandbox holds and where it is mounted; empty when none. Always sent by this node. */
4681
+ volumes?: SandboxVolume[];
3761
4682
  options: SandboxOptions;
4683
+ owner?: SandboxOwner;
4684
+ /**
4685
+ * The key that created the sandbox, whoever owns it; `null` when the creator held none: the GitHub App, or
4686
+ * a service's own credential (then `root` names the service).
4687
+ */
4688
+ created_by_key?: string | null;
4689
+ /** The sandbox whose own credential created this one; `null` when an outside caller did. */
4690
+ parent?: string | null;
4691
+ /**
4692
+ * The project's service this sandbox was started from, directly or through other sandboxes it started
4693
+ * (`owner: project`). This sandbox ends when that service ends. `null` for a service and for a sandbox no
4694
+ * service started.
4695
+ */
4696
+ root?: string | null;
3762
4697
  timing?: Timing;
3763
4698
  metadata: Metadata;
3764
4699
  }
@@ -3779,6 +4714,68 @@ export type SandboxList = Omit<ListEnvelope, "data"> & {
3779
4714
  data: Sandbox[];
3780
4715
  };
3781
4716
 
4717
+ export interface LeaseRequest {
4718
+ /**
4719
+ * The lease's name, 1 to 128 of `A-Z a-z 0-9 . _ : / -`. One live sandbox of the project holds it at a time:
4720
+ * holding it here takes it from the sandbox that held it.
4721
+ */
4722
+ key: string;
4723
+ /**
4724
+ * A precondition: the sandbox you read holding `key` (its ID), or `null` when you read none holding it. The
4725
+ * key is taken only while that is still so; otherwise `409 lease_holder_changed` names the sandbox that holds
4726
+ * it now (`holder`) and nothing changes. Left out, the key is taken from whichever sandbox holds it. A sandbox
4727
+ * that already holds `key` answers 200 whatever this says.
4728
+ */
4729
+ expect_holder?: string | null;
4730
+ }
4731
+
4732
+ /** A sandbox's lease, held or ended. */
4733
+ export interface SandboxLease {
4734
+ key: string;
4735
+ state: "held" | "ended";
4736
+ /** When the sandbox took the lease. */
4737
+ since: string;
4738
+ /** When the node last moved `expires_at` for it; `null` before the first renewal. */
4739
+ renewed_at: string | null;
4740
+ ended_at: string | null;
4741
+ /**
4742
+ * Why it ended: `released` (`DELETE …/lease`), `replaced` (another sandbox of the project took its key; this
4743
+ * one then stops within `sandboxes.lease_term`), or the sandbox's `stop_reason`.
4744
+ */
4745
+ end_reason: "released" | "replaced" | "deleted" | "timeout" | "failed" | "budget" | "revoked" | null;
4746
+ }
4747
+
4748
+ /** A background process the node starts again when it exits (an exec with `restart`). */
4749
+ export interface SupervisedProcess {
4750
+ /** The process running now, or the last one while it waits to start again; `null` if none started. */
4751
+ pid: number | null;
4752
+ /** The command as started (argv arrays are joined with spaces). */
4753
+ cmd: string;
4754
+ restart: "on-failure" | "always";
4755
+ /**
4756
+ * `starting`: started again, and the sandbox's readiness probe has not passed since. `running`: it runs
4757
+ * (and is ready, when the sandbox has a probe). `backoff`: it exited and starts again at `next_start_at`.
4758
+ * `crash_loop`: 5 exits within 300 s; restarts go on, at most 60 s apart, and it reads `crash_loop`, running
4759
+ * or waiting, until one run lasts 60 s. `exited`: it exited and
4760
+ * its policy keeps it down (`on-failure` after exit code 0). `stopped`: stopped through
4761
+ * `POST …/processes/{pid}/kill`, or the sandbox stopped.
4762
+ */
4763
+ state: "starting" | "running" | "backoff" | "crash_loop" | "exited" | "stopped";
4764
+ /** How many times the node started it again. */
4765
+ restarts: number;
4766
+ /** When the current process started. */
4767
+ started_at: string | null;
4768
+ /** How the last process ended; `null` before any exit. */
4769
+ last_exit: null | {
4770
+ pid: number | null;
4771
+ exit_code: number | null;
4772
+ signal: string | null;
4773
+ at: string;
4774
+ };
4775
+ /** When it starts again, in `backoff` and `crash_loop`; `null` otherwise. */
4776
+ next_start_at: string | null;
4777
+ }
4778
+
3782
4779
  export interface TimeoutRequest {
3783
4780
  timeout_s: number;
3784
4781
  }
@@ -3832,6 +4829,13 @@ export interface ExecRequest {
3832
4829
  background?: boolean;
3833
4830
  /** @default "user" */
3834
4831
  user?: "user" | "root";
4832
+ /**
4833
+ * With `background: true` only: the node starts the command again in this sandbox when it exits.
4834
+ * `on-failure` after a non-zero exit code or a signal, `always` after any exit. Waits between restarts in
4835
+ * a row: 0, 1, 2, 4, 8, 16, 32, then 60 s; a run of 60 s resets them. 5 exits within 300 s report
4836
+ * `crash_loop`. At most 8 per sandbox. Left out, the process is not supervised.
4837
+ */
4838
+ restart?: "on-failure" | "always";
3835
4839
  }
3836
4840
 
3837
4841
  export interface ExecResult {
@@ -3872,6 +4876,13 @@ export interface SandboxProcess {
3872
4876
  signal?: string | null;
3873
4877
  started_at: string;
3874
4878
  exited_at: string | null;
4879
+ /**
4880
+ * The node supervises this process now (it is the current process of an entry in the sandbox's
4881
+ * `supervised`). Always sent by this node.
4882
+ */
4883
+ supervised?: boolean;
4884
+ /** The process this one replaced when the node started the command again; `null` otherwise. */
4885
+ restart_of?: number | null;
3875
4886
  }
3876
4887
 
3877
4888
  /** What a running sandbox uses now (`GET /v1/sandboxes/{sandbox_id}/stats`). */
@@ -3911,6 +4922,14 @@ export interface SandboxStats {
3911
4922
  */
3912
4923
  total: number | null;
3913
4924
  };
4925
+ /**
4926
+ * The mounted volume's size and use (its guest name is its host ID); present only when the sandbox holds one.
4927
+ */
4928
+ volumes?: {
4929
+ name: string;
4930
+ used_bytes: number;
4931
+ total_bytes: number;
4932
+ }[];
3914
4933
  }
3915
4934
 
3916
4935
  export type SandboxProcessList = Omit<ListEnvelope, "data"> & {
@@ -3920,6 +4939,15 @@ export type SandboxProcessList = Omit<ListEnvelope, "data"> & {
3920
4939
  export interface KillRequest {
3921
4940
  /** @default "TERM" */
3922
4941
  signal?: "TERM" | "KILL" | "INT" | "HUP";
4942
+ /**
4943
+ * On a supervised process: keep the supervision, so the node starts the command again once the signal
4944
+ * ends it (counted as a restart). Without it the supervision ends first and the process stays down.
4945
+ * Ignored on a process the node does not supervise. A process still running 10 s after the signal ignored
4946
+ * it: the request lapses (the node logs it), and the process's next exit counts as a crash. Send `KILL` to
4947
+ * restart one that ignores `TERM`.
4948
+ * @default false
4949
+ */
4950
+ restart?: boolean;
3923
4951
  }
3924
4952
 
3925
4953
  /**
@@ -4086,7 +5114,21 @@ export interface Template {
4086
5114
  vcpu: number;
4087
5115
  memory_mib: number;
4088
5116
  }[];
5117
+ /**
5118
+ * `node`: one of the node's templates, the same for everyone. `project`: an imported image's template,
5119
+ * which only its project sees and can start sandboxes from. An image template's `name` is its `tpl_` ID and
5120
+ * it has one size (`size_classes` holds only the image's).
5121
+ */
5122
+ owner: "node" | "project";
5123
+ /** The image this template was imported from (`owner: project`); `null` for node templates. */
5124
+ image: string | null;
4089
5125
  created_at: string;
5126
+ /**
5127
+ * The sha256 of the guest agent in the template's image. A node's agent update changes it while
5128
+ * `created_at` stays, so a deployment's build key takes it: each application builds again once at its first
5129
+ * deploy after an agent update. Absent from a template whose image records no agent.
5130
+ */
5131
+ agent_sha256?: string;
4090
5132
  }
4091
5133
 
4092
5134
  export type TemplateList = Omit<ListEnvelope, "data"> & {
@@ -4094,291 +5136,890 @@ export type TemplateList = Omit<ListEnvelope, "data"> & {
4094
5136
  };
4095
5137
 
4096
5138
  /**
4097
- * A routine as sent to PUT /v1/routines/{id} (ARCHITECTURE 5.4). GitHub-Actions-shaped: triggers, defaults and an ordered list of steps; expressions are CEL inside ${{ }}. Steps run in array order unless a step lists needs. Contexts, status functions, template rules and the divergences from GitHub Actions are in packages/spec/schemas/README.md. Compile-time rules JSON Schema cannot express (unique ids, needs pointing at earlier steps, references only to ancestors, retry forbidden on irreversible steps) are listed there under 'Routine publish checks'. Owner after freeze: routines.
5139
+ * One child's command. In `defaults`, every field is optional; a child's own fields replace the defaults' (`env` is merged, the child's keys winning).
4098
5140
  */
4099
- export interface RoutineDefinition {
4100
- /** Optional pointer to this schema for editors. */
4101
- $schema?: string;
5141
+ export interface SwarmChildSpec {
5142
+ /** A shell command line (run with `/bin/sh -c`) or an argv array, as for exec. */
5143
+ cmd?: string | string[];
4102
5144
  /**
4103
- * Routine slug, unique within the project. Used by the CLI (b3os routine deploy); an MCP server that lists routines as tools names the tool routine_<name> with - mapped to _. runs, hooks, waits, events, validate and import are reserved: they are API paths under /v1/routines.
5145
+ * Extra environment variables for this child's command, on top of the checkpoint's. Kept with the swarm's record; never put secrets here.
4104
5146
  */
4105
- name: string;
4106
- /** What the routine does; an MCP server that lists routines as tools uses it as the tool description. */
4107
- description?: string;
5147
+ env?: Record<string, string>;
5148
+ /** @default "/workspace" */
5149
+ cwd?: string;
5150
+ /** Written to the command's standard input, which is then closed. */
5151
+ stdin?: string;
5152
+ /** @default "user" */
5153
+ user?: "user" | "root";
4108
5154
  /**
4109
- * JSON Schema 2020-12 for the run input, available as inputs. Defaults declared here are applied before the run starts. Absent: the run takes no input ({}).
5155
+ * Kill the command after this long; the child then ends `timed_out`.
5156
+ * @default 300000
4110
5157
  */
4111
- inputs?: RoutineDefinitionJsonSchemaObject;
5158
+ timeout_ms?: number;
5159
+ metadata?: Metadata;
5160
+ }
5161
+
5162
+ /** The checkpoint every child starts from. Exactly one of `sandbox` and `snapshot`. */
5163
+ export interface SwarmSource {
5164
+ /** A forkable sandbox, running or paused. A paused one is resumed for the fork and paused again. */
5165
+ sandbox?: string;
5166
+ /** A snapshot of this project; every child is restored from it. */
5167
+ snapshot?: string;
5168
+ }
5169
+
5170
+ /**
5171
+ * Give either `children` or `count` (with `defaults`), not both. Every child needs a `cmd`, its own or the defaults'.
5172
+ */
5173
+ export interface SwarmCreateRequest {
5174
+ from: SwarmSource;
5175
+ /** The children, in index order (`sandboxes.swarm_children_max`). */
5176
+ children?: SwarmChildSpec[];
5177
+ /** This many children, each running `defaults`. */
5178
+ count?: number;
5179
+ defaults?: SwarmChildSpec;
4112
5180
  /**
4113
- * The run's result, evaluated once after every step has finished and the run succeeded. Absent: the result is {}. Context: inputs, vars, env, trigger, run, steps (all).
5181
+ * `first_success`: once a child exits 0, kill the other children's commands and end the swarm.
5182
+ * @default "all"
4114
5183
  */
4115
- output?: RoutineDefinitionTemplateValue;
5184
+ stop_when?: "all" | "first_success";
4116
5185
  /**
4117
- * Non-secret strings evaluated once at run start (context: inputs, vars, trigger, run) and exposed as env.<NAME>. Not passed to sandboxes implicitly; put what a step needs in its with.
5186
+ * Which children stay running after their command ends; the rest are deleted.
5187
+ * @default "none"
4118
5188
  */
4119
- env?: Record<string, RoutineDefinitionTemplateString>;
5189
+ keep?: "none" | "succeeded" | "all";
4120
5190
  /**
4121
- * Read-only JSON constants exposed as vars.<name>. Values are literals; strings in them are not evaluated as templates.
5191
+ * Add `child.stdout` and `child.stderr` events to the swarm's stream (each stream up to `output_max_bytes`).
5192
+ * @default false
4122
5193
  */
4123
- vars?: Record<string, unknown>;
5194
+ stream_output?: boolean;
4124
5195
  /**
4125
- * How runs start besides POST /v1/routines/{id}/runs. Triggers switch atomically when a new version is published. Action triggers are trigger subscriptions (tsub_): publishing a version creates or updates them, and a rollback or delete removes them (README, 'Pack triggers').
5196
+ * How many bytes of each child's stdout and of its stderr are kept; the rest is dropped and `stdout_truncated` or `stderr_truncated` is set.
5197
+ * @default 65536
4126
5198
  */
4127
- triggers?: RoutineDefinitionTrigger[];
4128
- defaults?: {
4129
- /**
4130
- * ephemeral: nothing journaled while it runs (the agent tool-call fast path; a crash loses the run), and once it ends only its summary is stored (status, timing, input, result, error; no step history). standard: group-commit journal, effects durable before dependents run. strict: intent and result commits for every effect step (ARCHITECTURE 4.9, 5.4). A run may request a different tier at start.
4131
- * @default "standard"
4132
- */
4133
- durability?: "ephemeral" | "standard" | "strict";
4134
- /**
4135
- * Default timeout for uses and map steps that do not set timeout_ms. Wait and sleep steps are not affected. A job step (a product callable of kind job, such as render/video@1) that sets neither gets its operation's timeout instead (one hour for every job callable today).
4136
- * @default 30000
4137
- */
4138
- timeout_ms?: number;
4139
- /**
4140
- * Default retry policy, applied only to steps whose effect class is pure or read. A write step retries only when it sets retry itself; an irreversible step never retries.
4141
- */
4142
- retry?: RoutineDefinitionRetry;
4143
- /**
4144
- * Admission for runs of this routine, shaped like GitHub's concurrency. At most limit runs are active per group; on_limit decides what a new run does when the group is full.
4145
- */
4146
- concurrency?: {
4147
- limit: number;
4148
- /**
4149
- * Group key evaluated at run start (context: inputs, vars, trigger). Default: one group for the routine.
4150
- */
4151
- group?: RoutineDefinitionTemplateString;
4152
- /**
4153
- * queue: wait (FIFO) for a free slot. skip: the new run ends canceled with reason concurrency_skipped. cancel_running: cancel the oldest active run in the group, then start.
4154
- * @default "queue"
4155
- */
4156
- on_limit?: "queue" | "skip" | "cancel_running";
4157
- };
4158
- /**
4159
- * Pause the existing sandboxes a run execs in (sandboxes/exec@1 with sandbox) while it waits long (a wait or sleep of at least the node's pause_sandboxes_after_ms, 30 s by default, or a signal wait without a deadline) and nothing else of it runs: a paused sandbox bills no CPU. The run's next exec there resumes it first, and the end of the run resumes it. A sandbox another active run on the node execs in is not paused, and another run's exec resumes it first; anything else using the sandbox (your own processes or agents in it, other clients) is frozen while it is paused, so set this only for sandboxes the routine's runs have to themselves. Needs sandboxes:write on the publishing key.
4160
- * @default false
4161
- */
4162
- pause_sandboxes?: boolean;
5199
+ output_max_bytes?: number;
5200
+ /** As for a fork (`ForkRequest.clone_reset`), for every child. */
5201
+ clone_reset?: "full" | "none";
5202
+ webhook?: WebhookConfig;
5203
+ metadata?: Metadata;
5204
+ }
5205
+
5206
+ /** One child of a swarm and what its command did. */
5207
+ export interface SwarmChild {
5208
+ /** The child's position in `children` (or 0 to `count` - 1); also its `B3OS_SWARM_INDEX`. */
5209
+ index: number;
5210
+ /** The child's sandbox; `null` until the fork made it. */
5211
+ sandbox_id: string | null;
5212
+ /**
5213
+ * `queued` until its sandbox exists, `running` while its command runs, then `exited` (any exit code),
5214
+ * `timed_out` (killed at `timeout_ms`), `failed` (the command could not start or the sandbox was lost;
5215
+ * see `error`) or `canceled` (the swarm stopped it).
5216
+ */
5217
+ status: "queued" | "running" | "exited" | "timed_out" | "failed" | "canceled";
5218
+ /** The command's exit status; `null` until it exits, or when a signal ended it. */
5219
+ exit_code: number | null;
5220
+ /** The signal that ended the command, such as `KILL` after a timeout or a cancel. */
5221
+ signal: string | null;
5222
+ stdout: string;
5223
+ stderr: string;
5224
+ stdout_truncated: boolean;
5225
+ stderr_truncated: boolean;
5226
+ /** The child's sandbox was left running (`keep`); delete it when you are done with it. */
5227
+ kept: boolean;
5228
+ error?: Problem;
5229
+ metadata?: Metadata;
5230
+ /**
5231
+ * `start_ms`: from the swarm's start to the command's start. `run_ms`: the command's own run. `total_ms`: from the swarm's start to the command's end (or to now while it runs).
5232
+ */
5233
+ timing: {
5234
+ start_ms?: number;
5235
+ run_ms?: number;
5236
+ total_ms: number;
4163
5237
  };
4164
- steps: RoutineDefinitionStep[];
4165
5238
  }
4166
5239
 
4167
- /**
4168
- * A CEL identifier (so steps.<id>.outputs parses): lowercase letters, digits and _, not a CEL reserved word.
4169
- */
4170
- export type RoutineDefinitionIdent = string;
5240
+ /** A swarm (`swm_…`), one checkpoint forked into children that each ran a command. */
5241
+ export type Swarm = Omit<Job, "id" | "object" | "result" | "timing"> & {
5242
+ id: string;
5243
+ object: "swarm";
5244
+ from: SwarmSource;
5245
+ stop_when: "all" | "first_success";
5246
+ keep: "none" | "succeeded" | "all";
5247
+ /** Every child, by index. Left out of lists. */
5248
+ children?: SwarmChild[];
5249
+ /** How the children ended. Present once the swarm ended, and on a canceled swarm. */
5250
+ result?: {
5251
+ exit_zero: number;
5252
+ exit_nonzero: number;
5253
+ timed_out: number;
5254
+ failed: number;
5255
+ canceled: number;
5256
+ /** With `stop_when: first_success`, the index of the child that exited 0 first; else `null`. */
5257
+ winner: number | null;
5258
+ };
5259
+ /**
5260
+ * `fork_ms`: the fork or the restores that made the children. `first_exit_ms` and `last_exit_ms`: from the swarm's start to the first and the last command's end. `total_ms`: the whole swarm.
5261
+ */
5262
+ timing?: {
5263
+ fork_ms?: number;
5264
+ first_exit_ms?: number;
5265
+ last_exit_ms?: number;
5266
+ total_ms: number;
5267
+ };
5268
+ };
4171
5269
 
4172
- export type RoutineDefinitionJsonSchemaObject = JsonSchemaDocument & {
4173
- type: "object";
5270
+ export type SwarmList = Omit<ListEnvelope, "data"> & {
5271
+ data: Swarm[];
4174
5272
  };
4175
5273
 
4176
- /** Exactly one CEL expression wrapped as the whole string: ${{ <cel> }}. Keeps its CEL type. */
4177
- export type RoutineDefinitionCelExpression = string;
5274
+ export type SwarmChildList = Omit<ListEnvelope, "data"> & {
5275
+ data: SwarmChild[];
5276
+ };
4178
5277
 
4179
5278
  /**
4180
- * A CEL bool expression, bare or wrapped in one ${{ }} (both forms are accepted, as in GitHub's if). Without a call to success(), failure() or always(), the condition is implicitly success() && (<expression>).
5279
+ * An event of a swarm's stream. `swarm.forked` carries `children` (each `index` and `sandbox_id`) and the
5280
+ * fork's `timing`; `child.started`, `child.exited` and `child.failed` carry `index` and `sandbox_id`, and
5281
+ * `child.exited` also `exit_code`, `signal` and `timed_out`, `child.failed` an `error`; `child.stdout` and
5282
+ * `child.stderr` carry `index` and `data`.
4181
5283
  */
4182
- export type RoutineDefinitionCondition = string;
4183
-
4184
- /** A string that may contain ${{ <cel> }} expressions (README, 'Templates'). */
4185
- export type RoutineDefinitionTemplateString = string;
5284
+ export type SwarmEvent = JobEvent & {
5285
+ index?: number;
5286
+ sandbox_id?: string;
5287
+ data?: string;
5288
+ exit_code?: number | null;
5289
+ signal?: string | null;
5290
+ timed_out?: boolean;
5291
+ error?: Problem;
5292
+ children?: {
5293
+ index: number;
5294
+ sandbox_id: string;
5295
+ }[];
5296
+ };
4186
5297
 
4187
- /** Any JSON value; strings inside it at any depth are template strings, object keys are literal. */
4188
- export type RoutineDefinitionTemplateValue = unknown;
5298
+ /**
5299
+ * `queued` (accepted, waiting for the queue), `pulling` (layers streaming into the unpacking microVM),
5300
+ * `flattening` (the last byte sent; waiting for the unpacker and the store), `warming` (the first boot, the
5301
+ * warm-up and the warm snapshot), `ready`. `rebuilding`: a node release changed the guest agent, kernel or
5302
+ * hypervisor, and the warm snapshot is being taken again (creates answer `409 image_not_ready` until it is
5303
+ * `ready`). `failed`: see `error`. `evicted`: the node's image cache was full and this image, unused, was
5304
+ * removed; import it again with the same request.
5305
+ */
5306
+ export type ImageStatus =
5307
+ | "queued"
5308
+ | "pulling"
5309
+ | "flattening"
5310
+ | "warming"
5311
+ | "ready"
5312
+ | "rebuilding"
5313
+ | "failed"
5314
+ | "evicted";
4189
5315
 
4190
- /** An object of template values. */
4191
- export type RoutineDefinitionTemplateObject = Record<string, unknown>;
5316
+ export interface ImageWarmup {
5317
+ /**
5318
+ * Commands run once, in order, in the image's first boot before its warm snapshot is taken: each an
5319
+ * argument list, as root, in `WORKDIR` (else `/`), with the image's `ENV`, with no network, all of them
5320
+ * within 300 seconds. A command that exits non-zero fails the import (stage `golden`).
5321
+ */
5322
+ commands: string[][];
5323
+ }
4192
5324
 
4193
- /** Milliseconds: a literal integer or one CEL expression that evaluates to an int. */
4194
- export type RoutineDefinitionDurationMs = number | RoutineDefinitionCelExpression;
5325
+ export interface ImageImportRequest {
5326
+ /**
5327
+ * An image reference: `[registry/]repository[:tag|@sha256:digest]`. Without a registry it is Docker Hub
5328
+ * (`python:3.11-slim` is `registry-1.docker.io/library/python:3.11-slim`); without a tag or digest it is
5329
+ * `latest`. A tag is resolved to its digest once, when the import is accepted; the image keeps that digest.
5330
+ * Public images only (no credentials).
5331
+ */
5332
+ ref: string;
5333
+ warmup?: ImageWarmup;
5334
+ /** The size every sandbox from the image has. Default 1, at most your plan's `sandboxes.vcpu_max`. */
5335
+ vcpu?: number;
5336
+ /**
5337
+ * The memory every sandbox from the image has. Default 1024, at most your plan's `sandboxes.memory_max`.
5338
+ */
5339
+ memory_mib?: number;
5340
+ }
4195
5341
 
4196
5342
  /**
4197
- * <ref>@<ver>. First-party: vision/<name>@<major>, render/<name>@<major>, sandboxes/<name>@<major>, infer/<name>@<major>, core/http@1, core/transform@1, core/log@1 (core/map, core/wait and core/sleep are written as the map, wait and sleep_ms step fields). Sub-routine: routine/<rtn_id>@<ver_id>. Pack action: <namespace>/<pack>/<action>@<semver>, or @<major> which is resolved to the newest matching release when the version is published and pinned in it. The compiler checks that the callable exists and validates with against its input schema.
5343
+ * What the image's own configuration says, read when it was imported. `user`, `env` and `workdir` apply to every
5344
+ * command a sandbox from the image runs (`user` as in Docker: a name from the image's `/etc/passwd`, or
5345
+ * `uid[:gid]`; root when unset). `entrypoint`, `cmd`, `exposed_ports`, `volumes` and `healthcheck` are reported,
5346
+ * not run: a sandbox starts with no process of the image's own. Labels are shown, never acted on.
4198
5347
  */
4199
- export type RoutineDefinitionCallable = string;
5348
+ export interface ImageConfig {
5349
+ entrypoint: string[] | null;
5350
+ cmd: string[] | null;
5351
+ env: Record<string, string>;
5352
+ workdir: string | null;
5353
+ user: string | null;
5354
+ exposed_ports: string[];
5355
+ volumes: string[];
5356
+ labels: Record<string, string>;
5357
+ /** Docker's `HEALTHCHECK`, when the image has one (a Docker extension, not part of OCI). */
5358
+ healthcheck: {
5359
+ test: string[];
5360
+ interval_ms: number | null;
5361
+ timeout_ms: number | null;
5362
+ start_period_ms: number | null;
5363
+ retries: number | null;
5364
+ } | null;
5365
+ }
4200
5366
 
4201
- /**
4202
- * A pack trigger: <namespace>/<pack>/<trigger>@<semver>, or @<major>, which is resolved to the newest matching release when the version is published and pinned in it (and in the trigger subscription).
4203
- */
4204
- export type RoutineDefinitionTriggerRef = string;
5367
+ export interface ImagePackage {
5368
+ name: string;
5369
+ version: string;
5370
+ }
4205
5371
 
4206
5372
  /**
4207
- * Attempt n (n >= 2) starts after min(max_ms, initial_ms * factor^(n-2)) ms; with jitter the delay is drawn uniformly from [delay/2, delay] using a PRNG seeded by (run id, step id, item index, attempt), so replay is deterministic. Only failures the callee marks retryable (and timeouts of pure or read steps) are retried. Every attempt of a step carries the same idempotency key.
5373
+ * Milliseconds each finished stage took (`null` until it finishes): `resolve` (the reference to a digest,
5374
+ * before the answer), `queue` (waiting for a slot), `pull_flatten` (pulling and unpacking, which overlap),
5375
+ * `adopt` (checking and storing the file system), `golden` (the first boot, warm-up and warm snapshot), and
5376
+ * `total`.
4208
5377
  */
4209
- export interface RoutineDefinitionRetry {
4210
- /** Total attempts including the first. */
4211
- max_attempts: number;
4212
- /** @default 200 */
4213
- initial_ms?: number;
4214
- /** @default 2 */
4215
- factor?: number;
4216
- /** @default 30000 */
4217
- max_ms?: number;
4218
- /** @default true */
4219
- jitter?: boolean;
5378
+ export interface ImageStagesMs {
5379
+ resolve: number | null;
5380
+ queue: number | null;
5381
+ pull_flatten: number | null;
5382
+ adopt: number | null;
5383
+ golden: number | null;
5384
+ total: number | null;
4220
5385
  }
4221
5386
 
4222
- /** A vault connection id, or one CEL expression that evaluates to one (for example from vars). */
4223
- export type RoutineDefinitionConnectionRef = string;
5387
+ export interface ImageError {
5388
+ /** `import_failed`. */
5389
+ code: string;
5390
+ stage: "resolve" | "pull" | "flatten" | "adopt" | "golden" | "rebuild" | "interrupted";
5391
+ detail: string;
5392
+ /** The last 4 KiB of the unpacker's or the warm-up's output, when there was any. */
5393
+ output: string | null;
5394
+ }
5395
+
5396
+ export interface Image {
5397
+ id: string;
5398
+ object: "image";
5399
+ /** The reference as given. */
5400
+ ref: string;
5401
+ /** The `linux/amd64` image manifest's digest. */
5402
+ digest: string;
5403
+ /** The index (multi-platform list) the manifest was picked from, when the reference named one. */
5404
+ index_digest: string | null;
5405
+ platform: "linux/amd64";
5406
+ status: ImageStatus;
5407
+ /**
5408
+ * The template sandboxes start from (`POST /v1/sandboxes {"template": "tpl_…"}`), set once the image has been ready.
5409
+ */
5410
+ template: string | null;
5411
+ config: ImageConfig;
5412
+ /** The flattened read-only root file system, once stored. */
5413
+ rootfs: {
5414
+ sha256: string;
5415
+ bytes: number;
5416
+ } | null;
5417
+ warmup: ImageWarmup;
5418
+ size: {
5419
+ vcpu: number;
5420
+ memory_mib: number;
5421
+ };
5422
+ /** The import key (sha256); an import with the same key in this project returns this image. */
5423
+ key: string;
5424
+ stages_ms: ImageStagesMs;
5425
+ /** Compressed layer bytes pulled from the registry. */
5426
+ bytes_pulled: number;
5427
+ /**
5428
+ * Packages the unpacker found, best effort, at most 2,000 of each kind: Debian packages (`dpkg`), Python
5429
+ * distributions under `site-packages` (`pip`) and global `node_modules` (`npm`). `null` until the image is
5430
+ * flattened.
5431
+ */
5432
+ packages: {
5433
+ dpkg: ImagePackage[];
5434
+ pip: ImagePackage[];
5435
+ npm: ImagePackage[];
5436
+ } | null;
5437
+ error: null | ImageError;
5438
+ created_at: string;
5439
+ ready_at: string | null;
5440
+ }
5441
+
5442
+ export type ImageList = Omit<ListEnvelope, "data"> & {
5443
+ data: Image[];
5444
+ };
5445
+
5446
+ /** An instance's key, stored and shown as written, so never a credential or a personal detail. */
5447
+ export type AgentInstanceKey = string;
5448
+
5449
+ /** Lowercase letters, digits and `-`, starting with a letter. `sessions` is reserved. */
5450
+ export type AgentName = string;
4224
5451
 
4225
5452
  /**
4226
- * Exactly one of uses (call), map (fan-out), wait (signal or time) or sleep_ms (delay). Without needs a step depends on the step before it in the same list (the first step has no dependency); needs: [] makes it a root that starts immediately. Ids are unique across the whole routine, including map bodies.
5453
+ * What each instance starts from: a template (node templates, or one of your project's image templates) at a
5454
+ * size, or one of your project's snapshots. The size is fixed per agent, within `sandboxes.vcpu_max` and
5455
+ * `sandboxes.memory_max`.
4227
5456
  */
4228
- export type RoutineDefinitionStep = {
4229
- id: RoutineDefinitionIdent;
4230
- /** Display label. */
4231
- name?: string;
4232
- uses?: RoutineDefinitionCallable;
5457
+ export interface AgentSource {
5458
+ /** @default "agent" */
5459
+ template?: string;
5460
+ /** Restore this snapshot instead of starting from a template. */
5461
+ snapshot?: string;
5462
+ vcpu?: number;
5463
+ memory_mib?: number;
5464
+ disk_gib?: number;
5465
+ }
5466
+
5467
+ /**
5468
+ * The harness. `command` runs in each instance when it is made, and again after a cold boot from its disk. The
5469
+ * node delivers each message as a `POST` to `port` and `path`. The instance counts as made once `readiness`
5470
+ * passes (by default, once `port` accepts connections). A harness that exits is started again in place, at most
5471
+ * `max_restarts` times in a row; past that the instance is `failed`.
5472
+ */
5473
+ export interface AgentEntry {
5474
+ command: string[];
5475
+ /** Not 53, 1080, 3128, 7700 or 15001, which the guest agent listens on. */
5476
+ port: number;
5477
+ /** @default "/" */
5478
+ path?: string;
5479
+ readiness?: ReadinessProbe;
5480
+ /** @default 5 */
5481
+ max_restarts?: number;
5482
+ }
5483
+
5484
+ /**
5485
+ * When an idle instance moves to each sleep tier. Quiet means no turn, no queued message, no open connection
5486
+ * through its ports, no exec, file or terminal call and no sandbox it started still running; its own outbound
5487
+ * traffic does not count. Every default was chosen for the beta, not measured.
5488
+ */
5489
+ export interface AgentSleep {
4233
5490
  /**
4234
- * Input for the callable. Context: inputs, vars, env, trigger, run, steps (ancestors only), item and index inside a map body.
5491
+ * Quiet this long, it pauses in memory.
5492
+ * @default 30
4235
5493
  */
4236
- with?: RoutineDefinitionTemplateObject;
5494
+ ram_after_s?: number;
4237
5495
  /**
4238
- * Pack action steps only: binds the pack's connection keys to vault connections. A key left out is resolved when the step runs with SecretStore::find_connection (the most recently created connection for that pack the run's principal may use); when there is none the step fails with connection_required. Bind explicitly when a project holds several.
5496
+ * Paused this long, its memory goes to a snapshot on the node's disk and its memory is freed.
5497
+ * @default 600
4239
5498
  */
4240
- connections?: Record<string, RoutineDefinitionConnectionRef>;
5499
+ snapshot_after_s?: number;
4241
5500
  /**
4242
- * Pack action steps only: the end user the call is made for (ARCHITECTURE 5.5), a literal or a ${{ }} template such as ${{ inputs.user_id }}. Connection keys the step does not bind resolve to that subject's most recent connection for the pack and key, never to another subject's or to one without a subject; a subject with no connection fails the step with connection_required. The evaluated subject is 1 to 256 characters. Without subject, an end user's connection is used only when bound in connections.
5501
+ * How long a memory snapshot is kept. After it, the instance is `dormant`: only its disk is kept, and the
5502
+ * next message cold boots it from that disk and runs `entry.command` again.
5503
+ * @default 604800
4243
5504
  */
4244
- subject?: string;
5505
+ snapshot_keep_s?: number;
5506
+ }
5507
+
5508
+ /** How messages become turns. One turn runs at a time per instance. */
5509
+ export interface AgentTurns {
4245
5510
  /**
4246
- * Runs steps once per element of over. Inside the body, item is the element and index its position; steps.<id> of a body step refers to the current item. outputs of the map step: {items: [the last body step's outputs per element, null for failed or skipped items], outcomes: [outcome per element]}, both in input order. An item fails when a body step fails without continue_on_error; the first failed item cancels in-flight items and fails the map.
5511
+ * Messages that may wait for the current turn, at most `agents.queue_max`.
5512
+ * @default 16
4247
5513
  */
4248
- map?: {
4249
- /** Must evaluate to a list (at most 10,000 elements). */
4250
- over: RoutineDefinitionCelExpression;
4251
- /** @default 8 */
4252
- concurrency?: number;
4253
- steps: RoutineDefinitionStep[];
4254
- };
5514
+ queue_max?: number;
4255
5515
  /**
4256
- * Blocks the step without holding resources. {signal}: wait for POST /v1/routines/runs/{run_id}/signal with that name (signals sent before the step starts are buffered, at most 16 per signal name per run, and consumed in order). {signal, ms} or {signal, until}: give up at the deadline. {until}: wait for a time. {token: true}: a person answers through a signed link, run.wait_urls.<step id>, with no key or login (the signal is the step id unless signal names another). {event, match}: wait for an event sent with POST /v1/routines/events, from anywhere and without the run's ID, whose data holds the match values (not buffered: an event sent before the step waits does not count). outputs for signal waits: {signal, payload, received_at, timed_out}; a deadline is not a failure: timed_out is true and signal, payload and received_at are null. A link answer's payload is {decision: approve or reject, comment, via: link}. outputs for event waits: {event, data, id, received_at, timed_out}. outputs for {until}: {fired_at}.
5516
+ * How long a turn may take from its message's acceptance, queue time included.
5517
+ * @default 300
4257
5518
  */
4258
- wait?: {
4259
- signal?: string;
4260
- /** RFC 3339 timestamp, literal or produced by an expression. */
4261
- until?: RoutineDefinitionTemplateString;
4262
- /** Signal, token and event waits only: maximum wait. */
4263
- ms?: RoutineDefinitionDurationMs;
4264
- /**
4265
- * Wait for an event of this name (POST /v1/routines/events) in the run's project whose data holds every match value. Takes ms for a deadline; not with signal, until or token.
4266
- */
4267
- event?: string;
4268
- /**
4269
- * Event waits only: values the event's data must hold, by dot path into data (customer.id), compared as JSON. Templates are evaluated when the step starts waiting. Without match, any event of the name answers.
4270
- */
4271
- match?: Record<string, RoutineDefinitionTemplateValue>;
4272
- /**
4273
- * Give the wait a signed link a person can answer without a key: run.wait_urls.<step id> in any step's with (send it by Slack, email or a pack action). GET on the link shows a page with the prompt and Approve and Reject; the answer completes the step. The link is bound to this run and step, works once, stops working when the step stops waiting or the run ends, and expires 7 days after the step started waiting. Top-level steps only, and no other wait of the routine may use the same signal name.
4274
- */
4275
- token?: boolean;
4276
- /**
4277
- * What the person is asked, shown on the link's page and the run page while the step waits. Evaluated when the step starts waiting (context as for with). title at most 200 characters, body at most 4,000 (plain text, line breaks kept), image an https URL or an object with one (a render artifact such as steps.shot.outputs.artifacts[0]), link an https URL.
4278
- */
4279
- prompt?: {
4280
- title?: RoutineDefinitionTemplateString;
4281
- body?: RoutineDefinitionTemplateString;
4282
- image?: RoutineDefinitionTemplateValue;
4283
- link?: RoutineDefinitionTemplateString;
4284
- };
4285
- };
4286
- /** Durable delay; outputs {}. */
4287
- sleep_ms?: RoutineDefinitionDurationMs;
4288
- /** Ids of earlier steps in the same list that must finish first. */
4289
- needs?: RoutineDefinitionIdent[];
4290
- if?: RoutineDefinitionCondition;
4291
- retry?: RoutineDefinitionRetry;
5519
+ timeout_s?: number;
4292
5520
  /**
4293
- * uses steps: per attempt; a job step's attempt is its job's create and the wait for its end, and a job still running when it runs out is canceled. map steps: the whole map.
5521
+ * Deliver a message again after the node restarted while the harness had it. Only for a harness that
5522
+ * ignores a session ID it has seen (`x-b3os-session`).
5523
+ * @default false
4294
5524
  */
4295
- timeout_ms?: number;
5525
+ redeliver?: boolean;
5526
+ }
5527
+
5528
+ export interface AgentCreateRequest {
5529
+ name: AgentName;
5530
+ source?: AgentSource;
5531
+ entry: AgentEntry;
5532
+ /** Environment variables of the harness. Returned as given; put credentials in `secrets`. */
5533
+ env?: Record<string, string>;
4296
5534
  /**
4297
- * When the step fails, its outcome is failure but its conclusion is success, so dependents run and the run can still succeed.
4298
- * @default false
5535
+ * Environment variables never returned or logged, as a sandbox's `secrets`: code in the instance can read
5536
+ * them. A memory snapshot holds them, so the node keeps an instance's snapshots to itself: they are never
5537
+ * listed or restorable through the API.
4299
5538
  */
4300
- continue_on_error?: boolean;
5539
+ secrets?: Record<string, SecretValue>;
5540
+ api?: SandboxApiGrant;
5541
+ egress?: EgressPolicy;
5542
+ sleep?: AgentSleep;
5543
+ turns?: AgentTurns;
5544
+ metadata?: Metadata;
5545
+ }
5546
+
5547
+ export interface AgentUpdateRequest {
5548
+ source?: AgentSource;
5549
+ entry?: AgentEntry;
5550
+ env?: Record<string, string>;
5551
+ secrets?: Record<string, SecretValue>;
5552
+ api?: SandboxApiGrant;
5553
+ egress?: EgressPolicy;
5554
+ sleep?: AgentSleep;
5555
+ turns?: AgentTurns;
5556
+ /**
5557
+ * What happens to instances of earlier revisions: `new_instances` leaves them as they are; `on_wake` makes a
5558
+ * sleeping one again from this revision at its next wake, which ends its memory and disk.
5559
+ * @default "new_instances"
5560
+ */
5561
+ upgrade?: "new_instances" | "on_wake";
5562
+ metadata?: Metadata;
5563
+ }
5564
+
5565
+ export interface Agent {
5566
+ id: string;
5567
+ object: "agent";
5568
+ name: AgentName;
5569
+ /** Grows by one with each update. Each instance keeps the revision it was made from. */
5570
+ revision: number;
5571
+ source: AgentSource;
5572
+ entry: AgentEntry;
5573
+ env: Record<string, string>;
5574
+ secret_names: string[];
5575
+ api: SandboxApiGrant;
5576
+ egress: EgressPolicy;
5577
+ sleep: AgentSleep;
5578
+ turns: AgentTurns;
5579
+ upgrade: "new_instances" | "on_wake";
5580
+ /** How many instances the agent has, in any state. */
5581
+ instances: number;
5582
+ created_at: string;
5583
+ updated_at: string;
5584
+ metadata: Metadata;
5585
+ }
5586
+
5587
+ export type AgentList = Omit<ListEnvelope, "data"> & {
5588
+ data: Agent[];
4301
5589
  };
4302
5590
 
4303
5591
  /**
4304
- * core/http@1: one HTTP request through the egress guard, with no credentials (bind credentials through a pack action instead). Effect class read for GET and HEAD, write otherwise. outputs: {status: int, headers: map of lowercase name to string, body: parsed JSON when the response is JSON, else string}. A status >= 400 fails the step with upstream_error (retryable for 429 and 5xx) unless fail_on_error_status is false.
5592
+ * `creating` (its microVM starting and its harness passing readiness), `running`, `paused` (asleep in memory),
5593
+ * `hibernated` (asleep as a memory snapshot on disk), `dormant` (only its disk kept), `waking` (on its way back
5594
+ * to `running`) or `failed` (it recovers at its next message).
4305
5595
  */
4306
- export interface RoutineDefinitionCoreHttpWith {
4307
- /** @default "GET" */
4308
- method?: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE";
4309
- url: RoutineDefinitionTemplateString;
4310
- headers?: Record<string, RoutineDefinitionTemplateString>;
4311
- query?: Record<string, RoutineDefinitionTemplateValue>;
4312
- body?: RoutineDefinitionTemplateValue;
4313
- /** @default "json" */
4314
- body_encoding?: "json" | "form" | "text";
4315
- /** @default "auto" */
4316
- response?: "auto" | "json" | "text";
4317
- /** @default true */
4318
- fail_on_error_status?: boolean;
5596
+ export type AgentInstanceStatus = "creating" | "running" | "paused" | "hibernated" | "dormant" | "waking" | "failed";
5597
+
5598
+ export interface AgentInstancePutRequest {
5599
+ /**
5600
+ * Wake an existing sleeping instance too.
5601
+ * @default false
5602
+ */
5603
+ wake?: boolean;
5604
+ /**
5605
+ * Delete an existing instance (memory, snapshot and disk) and make it again from the current revision.
5606
+ * @default false
5607
+ */
5608
+ replace?: boolean;
5609
+ metadata?: Metadata;
4319
5610
  }
4320
5611
 
4321
- /** core/transform@1: evaluates value; outputs {value}. Effect class pure. */
4322
- export interface RoutineDefinitionCoreTransformWith {
4323
- value: RoutineDefinitionTemplateValue;
5612
+ export interface AgentInstanceSleepRequest {
5613
+ /** @default "ram" */
5614
+ tier?: "ram" | "snapshot";
4324
5615
  }
4325
5616
 
4326
- /** core/log@1: writes a log event to the run's event stream; outputs {}. Effect class pure. */
4327
- export interface RoutineDefinitionCoreLogWith {
4328
- message: RoutineDefinitionTemplateString;
4329
- /** @default "info" */
4330
- level?: "debug" | "info" | "warn" | "error";
4331
- data?: RoutineDefinitionTemplateValue;
5617
+ export interface AgentInstance {
5618
+ id: string;
5619
+ object: "agent_instance";
5620
+ agent_id: string;
5621
+ key: AgentInstanceKey;
5622
+ revision: number;
5623
+ status: AgentInstanceStatus;
5624
+ /** The instance's microVM, the same through every sleep tier; `null` before it was first made. */
5625
+ sandbox_id: string | null;
5626
+ /** Host memory the instance holds now (0 when hibernated or dormant). */
5627
+ resident_mib: number;
5628
+ /**
5629
+ * Bytes its checkpoint holds on the node beside its running microVM, which is its memory snapshot (memory, device state and a copy of its disk) or, when dormant, its disk alone. Kept while it sleeps and after it wakes, until the next one replaces it. 0 before its first.
5630
+ */
5631
+ storage_bytes: number;
5632
+ /** Messages waiting for the current turn. */
5633
+ queued: number;
5634
+ last_message_at: string | null;
5635
+ /** When it last went to sleep; `null` while it runs. */
5636
+ slept_at: string | null;
5637
+ /** When its kept memory snapshot was written, if it has one. */
5638
+ snapshot_at: string | null;
5639
+ created_at: string;
5640
+ metadata: Metadata;
4332
5641
  }
4333
5642
 
5643
+ export type AgentInstanceList = Omit<ListEnvelope, "data"> & {
5644
+ data: AgentInstance[];
5645
+ };
5646
+
4334
5647
  /**
4335
- * Occurrences missed while the node was down or the routine was paused: skip runs none, latest runs only the newest one, all runs each one in order. Only occurrences inside catch_up_window_s count. Required on every schedule (ARCHITECTURE 8).
5648
+ * How the instance was brought to the turn: `none` (it was running), `ram` (resumed from memory), `snapshot`
5649
+ * (restored from its memory snapshot), `disk` (cold booted from its disk, memory lost), `new` (made from the
5650
+ * agent). `null` until the session is delivered.
4336
5651
  */
4337
- export type RoutineDefinitionCatchUp = "skip" | "latest" | "all";
5652
+ export type AgentWokeFrom = "none" | "ram" | "snapshot" | "disk" | "new" | null;
5653
+
5654
+ export interface AgentInstanceEvent {
5655
+ object: "agent_instance_event";
5656
+ type:
5657
+ | "instance.created"
5658
+ | "instance.paused"
5659
+ | "instance.hibernated"
5660
+ | "instance.dormant"
5661
+ | "instance.woke"
5662
+ | "instance.failed"
5663
+ | "instance.recovered"
5664
+ | "instance.upgraded";
5665
+ ts: string;
5666
+ woke_from?: AgentWokeFrom;
5667
+ session_id?: string;
5668
+ detail?: string;
5669
+ }
5670
+
5671
+ export type AgentInstanceEventList = Omit<ListEnvelope, "data"> & {
5672
+ data: AgentInstanceEvent[];
5673
+ };
4338
5674
 
4339
5675
  /**
4340
- * When an occurrence fires while a run started by this trigger is still active: skip drops it, buffer_one keeps at most one pending occurrence (a newer one replaces it), allow starts it anyway, cancel_running cancels the active run first. defaults.concurrency still applies on top.
5676
+ * Your message. Every member but the reserved ones (`type`, `conversation`, `subject`, `metadata`, `create`,
5677
+ * `webhook`) is yours, and reaches the harness as `message`, with `type`.
4341
5678
  */
4342
- export type RoutineDefinitionOverlap = "skip" | "buffer_one" | "allow" | "cancel_running";
5679
+ export interface AgentMessageRequest {
5680
+ /**
5681
+ * What kind of message this is (a listener's actor sink sends `listener.event`).
5682
+ * @default "message"
5683
+ */
5684
+ type?: string;
5685
+ /** Your conversation or thread ID. Default, the `b3os.conversation` baggage. */
5686
+ conversation?: string;
5687
+ /** The end user the turn is for, an opaque ID, never an email. Default, the `b3os.subject` baggage. */
5688
+ subject?: string;
5689
+ metadata?: Metadata;
5690
+ /**
5691
+ * Make the instance if it does not exist. `false` answers `404 instance_not_found` instead.
5692
+ * @default true
5693
+ */
5694
+ create?: boolean;
5695
+ webhook?: WebhookConfig;
5696
+ [key: string]: unknown;
5697
+ }
5698
+
5699
+ /** Who sent the message, from its credential. */
5700
+ export interface AgentSessionInitiator {
5701
+ kind: "key" | "user" | "sandbox" | "instance" | "routine_run" | "listener";
5702
+ id: string;
5703
+ }
5704
+
5705
+ /** One turn (`ses_…`); `result` is the harness's answer. */
5706
+ export type AgentSession = Omit<Job, "id" | "object"> & {
5707
+ id: string;
5708
+ object: "agent_session";
5709
+ /** Where the turn is; `status` says how it ended. */
5710
+ phase: "queued" | "waking" | "delivered" | "ended";
5711
+ agent_id: string;
5712
+ instance_id: string;
5713
+ key: AgentInstanceKey;
5714
+ revision: number;
5715
+ type: string;
5716
+ conversation: string | null;
5717
+ subject: string | null;
5718
+ initiator: AgentSessionInitiator;
5719
+ woke_from: AgentWokeFrom;
5720
+ /** The instance had failed and recovered for this turn; `woke_from` says how. */
5721
+ recovered: boolean;
5722
+ trace_id: string;
5723
+ };
5724
+
5725
+ export type AgentSessionList = Omit<ListEnvelope, "data"> & {
5726
+ data: AgentSession[];
5727
+ };
4343
5728
 
4344
5729
  /**
4345
- * trigger context by type. cron and interval: {type, id, occurrence_id, scheduled_at, fired_at}. webhook: {type, id, hook_id, delivery_id, received_at, method, headers (lowercase map), query (map), body (parsed JSON when the request is JSON, else string)}. action: {type, id, subscription_id, event_id, event_type, source, time, data (the pack trigger's event data, valid against its eventSchema)}. Runs started through the API: {type: api}; sub-routine runs: {type: routine, parent_run_id, parent_step_id}.
5730
+ * `session.waking` carries `woke_from`; `session.output` carries `data`, one event the harness streamed, as text.
4346
5731
  */
4347
- export type RoutineDefinitionTrigger = {
4348
- type: "cron" | "interval" | "webhook" | "action";
4349
- id: RoutineDefinitionIdent;
4350
- /** action only: the pack trigger to subscribe to. */
4351
- uses?: RoutineDefinitionTriggerRef;
5732
+ export type AgentSessionEvent = JobEvent & {
5733
+ woke_from?: AgentWokeFrom;
5734
+ data?: string;
5735
+ };
5736
+
5737
+ /**
5738
+ * A routine as sent to PUT /v1/routines/{id} (ARCHITECTURE 5.4). GitHub-Actions-shaped: triggers, defaults and an ordered list of steps; expressions are CEL inside ${{ }}. Steps run in array order unless a step lists needs. Contexts, status functions, template rules and the divergences from GitHub Actions are in packages/spec/schemas/README.md. Compile-time rules JSON Schema cannot express (unique ids, needs pointing at earlier steps, references only to ancestors, retry forbidden on irreversible steps) are listed there under 'Routine publish checks'. Owner after freeze: routines.
5739
+ */
5740
+ export interface RoutineDefinition {
5741
+ /** Optional pointer to this schema for editors. */
5742
+ $schema?: string;
4352
5743
  /**
4353
- * cron, interval, webhook: the run input built from the event (context: trigger, vars), validated against inputs; absent: {} plus input defaults. action: the pack trigger's configuration, validated against its configSchema and evaluated once when the version is published (context: vars only); action runs start with {} plus input defaults and read the event from trigger.data.
5744
+ * Routine slug, unique within the project. Used by the CLI (b3os routine deploy); an MCP server that lists routines as tools names the tool routine_<name> with - mapped to _. runs, hooks, waits, events, validate and import are reserved: they are API paths under /v1/routines.
4354
5745
  */
4355
- with?: RoutineDefinitionTemplateObject;
5746
+ name: string;
5747
+ /** What the routine does; an MCP server that lists routines as tools uses it as the tool description. */
5748
+ description?: string;
4356
5749
  /**
4357
- * action only: binds the pack trigger's connection keys (its requires.connections) to vault connections. A key left out is resolved when the version is published (the most recently created connection for that pack the publishing key may use) and pinned in the subscription; when there is none the publish fails with routine_invalid.
5750
+ * JSON Schema 2020-12 for the run input, available as inputs. Defaults declared here are applied before the run starts. Absent: the run takes no input ({}).
4358
5751
  */
4359
- connections?: Record<string, RoutineDefinitionConnectionRef>;
5752
+ inputs?: RoutineDefinitionJsonSchemaObject;
4360
5753
  /**
4361
- * Start a run only when true (context: trigger, vars). A webhook delivery that does not match is acknowledged with 202 and starts nothing; an action event that does not match is dropped. Status functions are not available here.
5754
+ * The run's result, evaluated once after every step has finished and the run succeeded. Absent: the result is {}. Context: inputs, vars, env, trigger, run, steps (all).
4362
5755
  */
4363
- if?: RoutineDefinitionCondition;
5756
+ output?: RoutineDefinitionTemplateValue;
4364
5757
  /**
4365
- * Six fields with seconds: second minute hour day-of-month month day-of-week, single spaces. Numbers, names (JAN, MON), *, a-b, a,b, *\/n and ? are accepted; L, W and # in the day fields.
5758
+ * Non-secret strings evaluated once at run start (context: inputs, vars, trigger, run) and exposed as env.<NAME>. Not passed to sandboxes implicitly; put what a step needs in its with.
4366
5759
  */
4367
- cron?: string;
5760
+ env?: Record<string, RoutineDefinitionTemplateString>;
4368
5761
  /**
4369
- * IANA zone for cron, default UTC. A local time skipped by a DST change fires at the first instant after the gap; a local time that occurs twice fires once, at its first occurrence.
5762
+ * Read-only JSON constants exposed as vars.<name>. Values are literals; strings in them are not evaluated as templates.
4370
5763
  */
4371
- tz?: string;
4372
- /** Interval period. Plans may raise the floor (GET /v1/limits). */
4373
- every_ms?: number;
5764
+ vars?: Record<string, unknown>;
4374
5765
  /**
4375
- * interval: epoch fires at Unix-epoch multiples of every_ms (clock aligned); publish fires every_ms after the version became active, then every every_ms.
4376
- * @default "epoch"
5766
+ * How runs start besides POST /v1/routines/{id}/runs. Triggers switch atomically when a new version is published. Action triggers are trigger subscriptions (tsub_): publishing a version creates or updates them, and a rollback or delete removes them (README, 'Pack triggers').
4377
5767
  */
4378
- anchor?: "epoch" | "publish";
4379
- catch_up?: RoutineDefinitionCatchUp;
4380
- /** @default 86400 */
4381
- catch_up_window_s?: number;
5768
+ triggers?: RoutineDefinitionTrigger[];
5769
+ defaults?: {
5770
+ /**
5771
+ * ephemeral: nothing journaled while it runs (the agent tool-call fast path; a crash loses the run), and once it ends only its summary is stored (status, timing, input, result, error; no step history). standard: group-commit journal, effects durable before dependents run. strict: intent and result commits for every effect step (ARCHITECTURE 4.9, 5.4). A run may request a different tier at start.
5772
+ * @default "standard"
5773
+ */
5774
+ durability?: "ephemeral" | "standard" | "strict";
5775
+ /**
5776
+ * Default timeout for uses and map steps that do not set timeout_ms. Wait and sleep steps are not affected. A product step (vision/*, render/*, sandboxes/*, infer/*) that sets neither waits as long as its operation allows instead: its operation's timeout (65 seconds for vision/search@1 and vision/scrape@1, 600 seconds for infer/chat@1, one hour for every job callable today), and 65 seconds for sandboxes/exec@1, whose one hour is a streamed exec's. A map step that sets neither waits what one item's steps may take in a row (each step's own timeout, added along the steps it needs) once per round of concurrency items, and at least 30 seconds.
5777
+ * @default 30000
5778
+ */
5779
+ timeout_ms?: number;
5780
+ /**
5781
+ * Default retry policy, applied only to steps whose effect class is pure or read. A write step retries only when it sets retry itself; an irreversible step never retries.
5782
+ */
5783
+ retry?: RoutineDefinitionRetry;
5784
+ /**
5785
+ * Admission for runs of this routine, shaped like GitHub's concurrency. At most limit runs are active per group; on_limit decides what a new run does when the group is full.
5786
+ */
5787
+ concurrency?: {
5788
+ limit: number;
5789
+ /**
5790
+ * Group key evaluated at run start (context: inputs, vars, trigger). Default: one group for the routine.
5791
+ */
5792
+ group?: RoutineDefinitionTemplateString;
5793
+ /**
5794
+ * queue: wait (FIFO) for a free slot. skip: the new run ends canceled with reason concurrency_skipped. cancel_running: cancel the oldest active run in the group, then start.
5795
+ * @default "queue"
5796
+ */
5797
+ on_limit?: "queue" | "skip" | "cancel_running";
5798
+ };
5799
+ /**
5800
+ * Pause the existing sandboxes a run execs in (sandboxes/exec@1 with sandbox) while it waits long (a wait or sleep of at least the node's pause_sandboxes_after_ms, 30 s by default, or a signal wait without a deadline) and nothing else of it runs: a paused sandbox bills no CPU. The run's next exec there resumes it first, and the end of the run resumes it. A sandbox another active run on the node execs in is not paused, and another run's exec resumes it first; anything else using the sandbox (your own processes or agents in it, other clients) is frozen while it is paused, so set this only for sandboxes the routine's runs have to themselves. Needs sandboxes:write on the publishing key.
5801
+ * @default false
5802
+ */
5803
+ pause_sandboxes?: boolean;
5804
+ };
5805
+ steps: RoutineDefinitionStep[];
5806
+ }
5807
+
5808
+ /**
5809
+ * A CEL identifier (so steps.<id>.outputs parses): lowercase letters, digits and _, not a CEL reserved word.
5810
+ */
5811
+ export type RoutineDefinitionIdent = string;
5812
+
5813
+ export type RoutineDefinitionJsonSchemaObject = JsonSchemaDocument & {
5814
+ type: "object";
5815
+ };
5816
+
5817
+ /** Exactly one CEL expression wrapped as the whole string: ${{ <cel> }}. Keeps its CEL type. */
5818
+ export type RoutineDefinitionCelExpression = string;
5819
+
5820
+ /**
5821
+ * A CEL bool expression, bare or wrapped in one ${{ }} (both forms are accepted, as in GitHub's if). Without a call to success(), failure() or always(), the condition is implicitly success() && (<expression>).
5822
+ */
5823
+ export type RoutineDefinitionCondition = string;
5824
+
5825
+ /** A string that may contain ${{ <cel> }} expressions (README, 'Templates'). */
5826
+ export type RoutineDefinitionTemplateString = string;
5827
+
5828
+ /** Any JSON value; strings inside it at any depth are template strings, object keys are literal. */
5829
+ export type RoutineDefinitionTemplateValue = unknown;
5830
+
5831
+ /** An object of template values. */
5832
+ export type RoutineDefinitionTemplateObject = Record<string, unknown>;
5833
+
5834
+ /** Milliseconds: a literal integer or one CEL expression that evaluates to an int. */
5835
+ export type RoutineDefinitionDurationMs = number | RoutineDefinitionCelExpression;
5836
+
5837
+ /**
5838
+ * <ref>@<ver>. First-party: vision/<name>@<major>, render/<name>@<major>, sandboxes/<name>@<major>, infer/<name>@<major>, core/http@1, core/transform@1, core/log@1 (core/map, core/wait and core/sleep are written as the map, wait and sleep_ms step fields). Sub-routine: routine/<rtn_id>@<ver_id>. Pack action: <namespace>/<pack>/<action>@<semver>, or @<major> which is resolved to the newest matching release when the version is published and pinned in it. The compiler checks that the callable exists and validates with against its input schema.
5839
+ */
5840
+ export type RoutineDefinitionCallable = string;
5841
+
5842
+ /**
5843
+ * A pack trigger: <namespace>/<pack>/<trigger>@<semver>, or @<major>, which is resolved to the newest matching release when the version is published and pinned in it (and in the trigger subscription).
5844
+ */
5845
+ export type RoutineDefinitionTriggerRef = string;
5846
+
5847
+ /**
5848
+ * Attempt n (n >= 2) starts after min(max_ms, initial_ms * factor^(n-2)) ms; with jitter the delay is drawn uniformly from [delay/2, delay] using a PRNG seeded by (run id, step id, item index, attempt), so replay is deterministic. Only failures the callee marks retryable (and timeouts of pure or read steps) are retried. Every attempt of a step carries the same idempotency key.
5849
+ */
5850
+ export interface RoutineDefinitionRetry {
5851
+ /** Total attempts including the first. */
5852
+ max_attempts: number;
5853
+ /** @default 200 */
5854
+ initial_ms?: number;
5855
+ /** @default 2 */
5856
+ factor?: number;
5857
+ /** @default 30000 */
5858
+ max_ms?: number;
5859
+ /** @default true */
5860
+ jitter?: boolean;
5861
+ }
5862
+
5863
+ /** A vault connection id, or one CEL expression that evaluates to one (for example from vars). */
5864
+ export type RoutineDefinitionConnectionRef = string;
5865
+
5866
+ /**
5867
+ * Exactly one of uses (call), map (fan-out), wait (signal or time) or sleep_ms (delay). Without needs a step depends on the step before it in the same list (the first step has no dependency); needs: [] makes it a root that starts immediately. Ids are unique across the whole routine, including map bodies.
5868
+ */
5869
+ export type RoutineDefinitionStep = {
5870
+ id: RoutineDefinitionIdent;
5871
+ /** Display label. */
5872
+ name?: string;
5873
+ uses?: RoutineDefinitionCallable;
5874
+ /**
5875
+ * Input for the callable. Context: inputs, vars, env, trigger, run, steps (ancestors only), item and index inside a map body.
5876
+ */
5877
+ with?: RoutineDefinitionTemplateObject;
5878
+ /**
5879
+ * Pack action steps only: binds the pack's connection keys to vault connections. A key left out is resolved when the step runs with SecretStore::find_connection (the most recently created connection for that pack the run's principal may use); when there is none the step fails with connection_required. Bind explicitly when a project holds several.
5880
+ */
5881
+ connections?: Record<string, RoutineDefinitionConnectionRef>;
5882
+ /**
5883
+ * Pack action steps only: the end user the call is made for (ARCHITECTURE 5.5), a literal or a ${{ }} template such as ${{ inputs.user_id }}. Connection keys the step does not bind resolve to that subject's most recent connection for the pack and key, never to another subject's or to one without a subject; a subject with no connection fails the step with connection_required. The evaluated subject is 1 to 256 characters. Without subject, an end user's connection is used only when bound in connections.
5884
+ */
5885
+ subject?: string;
5886
+ /**
5887
+ * Runs steps once per element of over. Inside the body, item is the element and index its position; steps.<id> of a body step refers to the current item. outputs of the map step: {items: [the last body step's outputs per element, null for failed or skipped items], outcomes: [outcome per element]}, both in input order. An item fails when a body step fails without continue_on_error; the first failed item cancels in-flight items and fails the map.
5888
+ */
5889
+ map?: {
5890
+ /** Must evaluate to a list (at most 10,000 elements). */
5891
+ over: RoutineDefinitionCelExpression;
5892
+ /** @default 8 */
5893
+ concurrency?: number;
5894
+ steps: RoutineDefinitionStep[];
5895
+ };
5896
+ /**
5897
+ * Blocks the step without holding resources. {signal}: wait for POST /v1/routines/runs/{run_id}/signal with that name (signals sent before the step starts are buffered, at most 16 per signal name per run, and consumed in order). {signal, ms} or {signal, until}: give up at the deadline. {until}: wait for a time. {token: true}: a person answers through a signed link, run.wait_urls.<step id>, with no key or login (the signal is the step id unless signal names another). {event, match}: wait for an event sent with POST /v1/routines/events, from anywhere and without the run's ID, whose data holds the match values (not buffered: an event sent before the step waits does not count). outputs for signal waits: {signal, payload, received_at, timed_out}; a deadline is not a failure: timed_out is true and signal, payload and received_at are null. A link answer's payload is {decision: approve or reject, comment, via: link}. outputs for event waits: {event, data, id, received_at, timed_out}. outputs for {until}: {fired_at}.
5898
+ */
5899
+ wait?: {
5900
+ signal?: string;
5901
+ /** RFC 3339 timestamp, literal or produced by an expression. */
5902
+ until?: RoutineDefinitionTemplateString;
5903
+ /** Signal, token and event waits only: maximum wait. */
5904
+ ms?: RoutineDefinitionDurationMs;
5905
+ /**
5906
+ * Wait for an event of this name (POST /v1/routines/events) in the run's project whose data holds every match value. Takes ms for a deadline; not with signal, until or token.
5907
+ */
5908
+ event?: string;
5909
+ /**
5910
+ * Event waits only: values the event's data must hold, by dot path into data (customer.id), compared as JSON. Templates are evaluated when the step starts waiting. Without match, any event of the name answers.
5911
+ */
5912
+ match?: Record<string, RoutineDefinitionTemplateValue>;
5913
+ /**
5914
+ * Give the wait a signed link a person can answer without a key: run.wait_urls.<step id> in any step's with (send it by Slack, email or a pack action). GET on the link shows a page with the prompt and Approve and Reject; the answer completes the step. The link is bound to this run and step, works once, stops working when the step stops waiting or the run ends, and expires 7 days after the step started waiting. Top-level steps only, and no other wait of the routine may use the same signal name.
5915
+ */
5916
+ token?: boolean;
5917
+ /**
5918
+ * What the person is asked, shown on the link's page and the run page while the step waits. Evaluated when the step starts waiting (context as for with). title at most 200 characters, body at most 4,000 (plain text, line breaks kept), image an https URL or an object with one (a render artifact such as steps.shot.outputs.artifacts[0]), link an https URL.
5919
+ */
5920
+ prompt?: {
5921
+ title?: RoutineDefinitionTemplateString;
5922
+ body?: RoutineDefinitionTemplateString;
5923
+ image?: RoutineDefinitionTemplateValue;
5924
+ link?: RoutineDefinitionTemplateString;
5925
+ };
5926
+ };
5927
+ /** Durable delay; outputs {}. */
5928
+ sleep_ms?: RoutineDefinitionDurationMs;
5929
+ /** Ids of earlier steps in the same list that must finish first. */
5930
+ needs?: RoutineDefinitionIdent[];
5931
+ if?: RoutineDefinitionCondition;
5932
+ retry?: RoutineDefinitionRetry;
5933
+ /**
5934
+ * uses steps: per attempt; a job step's attempt is its job's create and the wait for its end, and a job still running when it runs out is canceled. map steps: the whole map.
5935
+ */
5936
+ timeout_ms?: number;
5937
+ /**
5938
+ * When the step fails, its outcome is failure but its conclusion is success, so dependents run and the run can still succeed.
5939
+ * @default false
5940
+ */
5941
+ continue_on_error?: boolean;
5942
+ };
5943
+
5944
+ /**
5945
+ * core/http@1: one HTTP request through the egress guard, with no credentials (bind credentials through a pack action instead). Effect class read for GET and HEAD, write otherwise. outputs: {status: int, headers: map of lowercase name to string, body: parsed JSON when the response is JSON, else string}. A status >= 400 fails the step with upstream_error (retryable for 429 and 5xx) unless fail_on_error_status is false.
5946
+ */
5947
+ export interface RoutineDefinitionCoreHttpWith {
5948
+ /** @default "GET" */
5949
+ method?: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE";
5950
+ url: RoutineDefinitionTemplateString;
5951
+ headers?: Record<string, RoutineDefinitionTemplateString>;
5952
+ query?: Record<string, RoutineDefinitionTemplateValue>;
5953
+ body?: RoutineDefinitionTemplateValue;
5954
+ /** @default "json" */
5955
+ body_encoding?: "json" | "form" | "text";
5956
+ /** @default "auto" */
5957
+ response?: "auto" | "json" | "text";
5958
+ /** @default true */
5959
+ fail_on_error_status?: boolean;
5960
+ }
5961
+
5962
+ /** core/transform@1: evaluates value; outputs {value}. Effect class pure. */
5963
+ export interface RoutineDefinitionCoreTransformWith {
5964
+ value: RoutineDefinitionTemplateValue;
5965
+ }
5966
+
5967
+ /** core/log@1: writes a log event to the run's event stream; outputs {}. Effect class pure. */
5968
+ export interface RoutineDefinitionCoreLogWith {
5969
+ message: RoutineDefinitionTemplateString;
5970
+ /** @default "info" */
5971
+ level?: "debug" | "info" | "warn" | "error";
5972
+ data?: RoutineDefinitionTemplateValue;
5973
+ }
5974
+
5975
+ /**
5976
+ * Occurrences missed while the node was down or the routine was paused: skip runs none, latest runs only the newest one, all runs each one in order. Only occurrences inside catch_up_window_s count. Required on every schedule (ARCHITECTURE 8).
5977
+ */
5978
+ export type RoutineDefinitionCatchUp = "skip" | "latest" | "all";
5979
+
5980
+ /**
5981
+ * When an occurrence fires while a run started by this trigger is still active: skip drops it, buffer_one keeps at most one pending occurrence (a newer one replaces it), allow starts it anyway, cancel_running cancels the active run first. defaults.concurrency still applies on top.
5982
+ */
5983
+ export type RoutineDefinitionOverlap = "skip" | "buffer_one" | "allow" | "cancel_running";
5984
+
5985
+ /**
5986
+ * trigger context by type. cron and interval: {type, id, occurrence_id, scheduled_at, fired_at}. webhook: {type, id, hook_id, delivery_id, received_at, method, headers (lowercase map), query (map), body (parsed JSON when the request is JSON, else string)}. action: {type, id, subscription_id, event_id, event_type, source, time, data (the pack trigger's event data, valid against its eventSchema)}. Runs started through the API: {type: api}; sub-routine runs: {type: routine, parent_run_id, parent_step_id}.
5987
+ */
5988
+ export type RoutineDefinitionTrigger = {
5989
+ type: "cron" | "interval" | "webhook" | "action";
5990
+ id: RoutineDefinitionIdent;
5991
+ /** action only: the pack trigger to subscribe to. */
5992
+ uses?: RoutineDefinitionTriggerRef;
5993
+ /**
5994
+ * cron, interval, webhook: the run input built from the event (context: trigger, vars), validated against inputs; absent: {} plus input defaults. action: the pack trigger's configuration, validated against its configSchema and evaluated once when the version is published (context: vars only); action runs start with {} plus input defaults and read the event from trigger.data.
5995
+ */
5996
+ with?: RoutineDefinitionTemplateObject;
5997
+ /**
5998
+ * action only: binds the pack trigger's connection keys (its requires.connections) to vault connections. A key left out is resolved when the version is published (the most recently created connection for that pack the publishing key may use) and pinned in the subscription; when there is none the publish fails with routine_invalid.
5999
+ */
6000
+ connections?: Record<string, RoutineDefinitionConnectionRef>;
6001
+ /**
6002
+ * Start a run only when true (context: trigger, vars). A webhook delivery that does not match is acknowledged with 202 and starts nothing; an action event that does not match is dropped. Status functions are not available here.
6003
+ */
6004
+ if?: RoutineDefinitionCondition;
6005
+ /**
6006
+ * Six fields with seconds: second minute hour day-of-month month day-of-week, single spaces. Numbers, names (JAN, MON), *, a-b, a,b, *\/n and ? are accepted; L, W and # in the day fields.
6007
+ */
6008
+ cron?: string;
6009
+ /**
6010
+ * IANA zone for cron, default UTC. A local time skipped by a DST change fires at the first instant after the gap; a local time that occurs twice fires once, at its first occurrence.
6011
+ */
6012
+ tz?: string;
6013
+ /** Interval period. Plans may raise the floor (GET /v1/limits). */
6014
+ every_ms?: number;
6015
+ /**
6016
+ * interval: epoch fires at Unix-epoch multiples of every_ms (clock aligned); publish fires every_ms after the version became active, then every every_ms.
6017
+ * @default "epoch"
6018
+ */
6019
+ anchor?: "epoch" | "publish";
6020
+ catch_up?: RoutineDefinitionCatchUp;
6021
+ /** @default 86400 */
6022
+ catch_up_window_s?: number;
4382
6023
  overlap?: RoutineDefinitionOverlap;
4383
6024
  verify?: RoutineDefinitionWebhookVerify;
4384
6025
  challenge?: RoutineDefinitionWebhookChallenge;
@@ -4399,417 +6040,966 @@ export interface RoutineDefinitionWebhookChallenge {
4399
6040
  /**
4400
6041
  * An api_key vault connection whose api_key field holds the verify token you gave the provider (store it without pack and without hosts, like verify.secret). The token is read from the vault and never appears in the definition. Naming one needs vault:run on top of routines:write.
4401
6042
  */
4402
- token_connection?: string;
6043
+ token_connection?: string;
6044
+ }
6045
+
6046
+ /**
6047
+ * Mandatory verification for POST /v1/routines/hooks/{hk_id} (ARCHITECTURE 4.3); the hk_ id is created when the version is published. b3os: B3OS-Signature 't=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<body>")>' with a per-hook secret B3OS generates (shown once by the API). github, stripe, slack, standard_webhooks: the provider's scheme as in b3pack verify. hmac_sha256: generic, and always timestamped: the signature covers '<value of timestamp_header>.<body>', and a delivery whose timestamp header is missing or not a Unix time is refused. Timestamped schemes reject deliveries more than tolerance_s (at most 300 s) from the node clock. Secrets never appear in the URL.
6048
+ */
6049
+ export type RoutineDefinitionWebhookVerify = {
6050
+ scheme: "b3os" | "github" | "stripe" | "slack" | "standard_webhooks" | "hmac_sha256";
6051
+ /**
6052
+ * An api_key vault connection whose api_key field holds the provider's signing secret (vault.yaml field names). Store it as a verification-only connection, without pack and without hosts: B3OS reads it to check signatures, and a connection with no hosts is never injected into any request. Naming one needs vault:run on top of routines:write. Not used with b3os.
6053
+ */
6054
+ secret?: string;
6055
+ header?: string;
6056
+ encoding?: "hex" | "base64";
6057
+ prefix?: string;
6058
+ /** hmac_sha256 only, and required there: header carrying the delivery's Unix timestamp. */
6059
+ timestamp_header?: string;
6060
+ /** @default 300 */
6061
+ tolerance_s?: number;
6062
+ };
6063
+
6064
+ export interface RoutineVersionRef {
6065
+ id: string;
6066
+ number: number;
6067
+ created_at: string;
6068
+ }
6069
+
6070
+ export interface RoutineHook {
6071
+ id: string;
6072
+ /** Give this URL to the provider. */
6073
+ url: string;
6074
+ verify: "b3os" | "github" | "stripe" | "slack" | "standard_webhooks" | "hmac_sha256";
6075
+ /**
6076
+ * The `b3os` scheme's signing secret. Present only in the response of the publish that created the hook (and of a rotation).
6077
+ */
6078
+ secret?: string;
6079
+ }
6080
+
6081
+ export interface RoutineTrigger {
6082
+ /** The trigger's `id` in the definition. */
6083
+ id: string;
6084
+ type: "cron" | "interval" | "webhook" | "action";
6085
+ status: "active" | "paused";
6086
+ /** Next scheduled fire (cron and interval), or `null`. */
6087
+ next_fire_at: string | null;
6088
+ /** The inbound URL of a webhook trigger, or `null`. */
6089
+ hook: null | RoutineHook;
6090
+ /**
6091
+ * The trigger subscription of an action trigger (`GET /v1/actions/subscriptions/{subscription_id}`), or `null`.
6092
+ */
6093
+ subscription_id: string | null;
6094
+ }
6095
+
6096
+ export interface Routine {
6097
+ id: string;
6098
+ object: "routine";
6099
+ name: string;
6100
+ description: string | null;
6101
+ /** `paused` when triggers are stopped; API runs still work unless `paused_reason` is `run_as_revoked`. */
6102
+ status: "active" | "paused";
6103
+ paused_reason: "manual" | "run_as_revoked" | null;
6104
+ version: RoutineVersionRef;
6105
+ triggers: RoutineTrigger[];
6106
+ /**
6107
+ * The identity runs execute as (the key that published the active version, with its scopes at publish time).
6108
+ */
6109
+ run_as: {
6110
+ /** The API key ID; `null` when a dashboard user published. */
6111
+ key: string | null;
6112
+ scopes: string[];
6113
+ };
6114
+ created_at: string;
6115
+ updated_at: string;
6116
+ metadata: Metadata;
6117
+ /**
6118
+ * Present only when something about the active version needs attention. Today: a `product_unavailable` warning at `/triggers/<i>` for each action trigger whose subscription the actions product does not hold yet (it was not running, or answered 5xx or 429, when the version was published). The publish stands, the trigger starts no runs until it is subscribed, and routines retries the subscription every 10 seconds until the actions product takes it; the warning then goes away. A 4xx from the actions product fails the publish with `routine_invalid` instead.
6119
+ */
6120
+ warnings?: Diagnostic[];
6121
+ }
6122
+
6123
+ export type RoutineList = Omit<ListEnvelope, "data"> & {
6124
+ data: Routine[];
6125
+ };
6126
+
6127
+ export interface RoutineUpdateRequest {
6128
+ paused?: boolean;
6129
+ metadata?: Metadata;
6130
+ }
6131
+
6132
+ export interface RollbackRequest {
6133
+ /** A `ver_` ID or a version number. */
6134
+ version: string | number;
6135
+ }
6136
+
6137
+ export interface RoutineVersion {
6138
+ id: string;
6139
+ object: "routine_version";
6140
+ routine_id: string;
6141
+ number: number;
6142
+ active: boolean;
6143
+ /** The key ID that published this version. */
6144
+ published_by: string | null;
6145
+ /** The publisher's scopes, snapshotted; runs of this version get at most these. */
6146
+ scopes: string[];
6147
+ created_at: string;
6148
+ definition?: RoutineDefinition;
6149
+ }
6150
+
6151
+ export type RoutineVersionList = Omit<ListEnvelope, "data"> & {
6152
+ data: RoutineVersion[];
6153
+ };
6154
+
6155
+ export interface Diagnostic {
6156
+ severity: "error" | "warning";
6157
+ /** An error code from the catalog, such as `routine_invalid` or `connection_required`. */
6158
+ code: string;
6159
+ /** JSON pointer into the definition. */
6160
+ pointer: string;
6161
+ detail: string;
6162
+ }
6163
+
6164
+ export interface RoutineValidation {
6165
+ object: "routine_validation";
6166
+ valid: boolean;
6167
+ diagnostics: Diagnostic[];
6168
+ /** Number of steps in the compiled plan, map bodies included. */
6169
+ steps?: number;
6170
+ }
6171
+
6172
+ export interface RoutineImportRequest {
6173
+ format: "b3os-workflow-v1";
6174
+ /** The workflow JSON exported from the original B3OS app. */
6175
+ workflow: Record<string, unknown>;
6176
+ }
6177
+
6178
+ export interface RoutineImport {
6179
+ object: "routine_import";
6180
+ definition: RoutineDefinition;
6181
+ diagnostics: Diagnostic[];
6182
+ }
6183
+
6184
+ export interface HookTestRequest {
6185
+ /** The JSON body to deliver; `trigger.body` of the run it starts. */
6186
+ body?: Record<string, unknown>;
6187
+ }
6188
+
6189
+ /** One request to a known hook, as its delivery log keeps it. */
6190
+ export interface HookDeliveryEntry {
6191
+ object: "hook_delivery_entry";
6192
+ hook_id: string;
6193
+ received_at: string;
6194
+ method: "POST" | "GET";
6195
+ /** `edge_replay`: replayed from the edge's queue after the node was down; `test`: `POST …/test`. */
6196
+ source: "provider" | "edge_replay" | "test";
6197
+ /** The HTTP status the hook answered. */
6198
+ status: number;
6199
+ /**
6200
+ * `not_started`: accepted without a run (`if` was false, or the routine is paused); `rejected`: a 4xx; `unavailable`: a 5xx (the edge retries).
6201
+ */
6202
+ outcome: "started" | "deduplicated" | "not_started" | "handshake" | "rejected" | "unavailable";
6203
+ /** The error code of a 4xx or 5xx. */
6204
+ code: string | null;
6205
+ /** The `reason` of a `webhook_signature_invalid` (`signature` or `timestamp`). */
6206
+ reason: string | null;
6207
+ /** The error's detail (at most 500 characters). */
6208
+ detail: string | null;
6209
+ run_id: string | null;
6210
+ delivery_id: string | null;
6211
+ deduplicated: boolean;
6212
+ handshake: "slack_url_verification" | "slack_ssl_check" | "github_ping" | "get_challenge" | null;
6213
+ /** Body bytes (the body itself is not kept). */
6214
+ size: number;
6215
+ /** The allowlisted request headers it had (values up to 256 characters). */
6216
+ headers: Record<string, string>;
6217
+ }
6218
+
6219
+ export type HookDeliveryEntryList = Omit<ListEnvelope, "data"> & {
6220
+ data: HookDeliveryEntry[];
6221
+ };
6222
+
6223
+ export interface HookRotateRequest {
6224
+ /** @default 86400 */
6225
+ grace_s?: number;
6226
+ }
6227
+
6228
+ export interface HookSecret {
6229
+ object: "hook_secret";
6230
+ hook_id: string;
6231
+ secret: string;
6232
+ previous_valid_until: string | null;
6233
+ }
6234
+
6235
+ /** How the run started (the `trigger` context of its expressions). */
6236
+ export interface RunTrigger {
6237
+ type: "api" | "cron" | "interval" | "webhook" | "action" | "routine" | "replay";
6238
+ /** The trigger ID (cron, interval, webhook, action). */
6239
+ id?: string;
6240
+ /** Cron and interval occurrence, used to deduplicate fires. */
6241
+ occurrence_id?: string;
6242
+ scheduled_at?: string;
6243
+ hook_id?: string;
6244
+ delivery_id?: string;
6245
+ /** The trigger subscription that delivered the event (action triggers). */
6246
+ subscription_id?: string;
6247
+ /** The pack trigger event's ID (action triggers). */
6248
+ event_id?: string;
6249
+ /** For sub-routine runs, the calling run; for replays, the source run. */
6250
+ parent_run_id?: string;
6251
+ parent_step_id?: string;
6252
+ /** For replays started with `from_step`, that step. */
6253
+ from_step?: string;
6254
+ }
6255
+
6256
+ export interface StepRun {
6257
+ /** The step ID from the definition. */
6258
+ id: string;
6259
+ uses?: string;
6260
+ /** Position in the map's list, for steps inside a map body. */
6261
+ item_index?: number;
6262
+ status: "pending" | "running" | "waiting" | "retrying" | "succeeded" | "failed" | "skipped" | "canceled";
6263
+ /**
6264
+ * The attempt this execution is. Retries add one; so does a node restart while the step ran (the earlier attempt's result, should it arrive, is discarded).
6265
+ */
6266
+ attempt: number;
6267
+ started_at?: string;
6268
+ finished_at?: string;
6269
+ duration_ms?: number;
6270
+ /** The step's outputs, once it succeeded. */
6271
+ outputs?: unknown;
6272
+ error?: Problem;
6273
+ /** Item counts for a map step. */
6274
+ map?: {
6275
+ total?: number;
6276
+ succeeded?: number;
6277
+ failed?: number;
6278
+ running?: number;
6279
+ };
6280
+ /**
6281
+ * What a waiting step waits for. `token` and `prompt` show in the run's current state (`GET /v1/routines/runs/{run_id}`), not in event snapshots.
6282
+ */
6283
+ waiting_for?: {
6284
+ signal?: string;
6285
+ until?: string;
6286
+ /** The step has a wait link (`token: true`); the link itself is only in `run.wait_urls`. */
6287
+ token?: true;
6288
+ prompt?: WaitPrompt;
6289
+ /** An event wait's event name (`POST /v1/routines/events`). */
6290
+ event?: string;
6291
+ /** An event wait's evaluated match values, by dot path into the event's data. */
6292
+ match?: Record<string, unknown>;
6293
+ };
6294
+ /** A replay copied this step's outputs from its source run; the step did not run. Absent otherwise. */
6295
+ replayed?: true;
6296
+ }
6297
+
6298
+ export type StepRunList = Omit<ListEnvelope, "data"> & {
6299
+ data: StepRun[];
6300
+ };
6301
+
6302
+ export interface RunCreateRequest {
6303
+ /** Validated against the routine's `inputs`; defaults from it are applied. */
6304
+ input?: Record<string, unknown>;
6305
+ /** Run this version instead of the active one (`ver_` ID or number). */
6306
+ version?: string | number;
6307
+ /** Override the routine's default durability for this run. */
6308
+ durability?: "ephemeral" | "standard" | "strict";
6309
+ webhook?: WebhookConfig;
6310
+ metadata?: Metadata;
6311
+ }
6312
+
6313
+ export interface RunReplayRequest {
6314
+ /**
6315
+ * Run this top-level step and every step downstream of it again. Absent: only the steps that did not succeed, and those downstream of them, run again.
6316
+ */
6317
+ from_step?: string;
6318
+ /**
6319
+ * The new run's input instead of the source run's; validated against the version's `inputs`. When it differs from the source's, the steps that read it (directly or through `env`) and the steps that wait for a signal run again, with every step downstream of them.
6320
+ */
6321
+ input?: Record<string, unknown>;
6322
+ /**
6323
+ * Replay with this version instead of the source run's (`ver_` ID or number). The steps it adds or changes and the steps that wait for a signal run again, with every step downstream of them.
6324
+ */
6325
+ version?: string | number;
6326
+ /** Override the version's default durability for the new run. */
6327
+ durability?: "ephemeral" | "standard" | "strict";
6328
+ webhook?: WebhookConfig;
6329
+ metadata?: Metadata;
6330
+ }
6331
+
6332
+ /** A routine run (`run_…`); `result` is the routine's `output`. */
6333
+ export type RoutineRun = Omit<Job, "id" | "object"> & {
6334
+ id: string;
6335
+ object: "routine_run";
6336
+ routine_id: string;
6337
+ version_id: string;
6338
+ version_number: number;
6339
+ durability: "ephemeral" | "standard" | "strict";
6340
+ trigger: RunTrigger;
6341
+ input: Record<string, unknown>;
6342
+ /**
6343
+ * The run's outcome line: when the routine's `output` is an object with a non-empty `summary` string,
6344
+ * that string on one line, cut to 140 characters (an ellipsis marks the cut). Absent otherwise. Run
6345
+ * lists, the run's terminal event and its webhook carry it, so a list of runs says what each one did.
6346
+ */
6347
+ summary?: string;
6348
+ /** Top-level steps in definition order (empty when `steps_kept` is `false`). */
6349
+ steps: StepRun[];
6350
+ /**
6351
+ * `false` on an `ephemeral` run read after it ended: only its summary was kept (status, timing,
6352
+ * `input`, `result`, `error` and its IDs), so `steps` is empty, `…/steps` and a replay answer 410
6353
+ * `run_steps_not_kept`, and `…/events` sends its terminal event alone. The `?wait=` answer, the event
6354
+ * stream and the webhook carried its steps as it ended. Absent on every other run.
6355
+ */
6356
+ steps_kept?: false;
6357
+ };
6358
+
6359
+ export type RoutineRunList = Omit<ListEnvelope, "data"> & {
6360
+ data: RoutineRun[];
6361
+ };
6362
+
6363
+ /** `step.*` events carry `step` (a `StepRun`); `run.log` carries `step_id`, `level` and `message`. */
6364
+ export type RunEvent = JobEvent & {
6365
+ step?: StepRun;
6366
+ step_id?: string;
6367
+ level?: "debug" | "info" | "warn" | "error";
6368
+ message?: string;
6369
+ };
6370
+
6371
+ export interface RoutineEventRequest {
6372
+ /** The event name `wait.event` names. */
6373
+ name: string;
6374
+ /** What `wait.match` is checked against, and the step's `data` output. */
6375
+ data?: unknown;
6376
+ /** Your ID for the event, passed to the step's `id` output. */
6377
+ id?: string;
6378
+ }
6379
+
6380
+ export interface RoutineEvent {
6381
+ object: "routine_event";
6382
+ name: string;
6383
+ id?: string | null;
6384
+ /** How many waiting steps the event resumed. */
6385
+ delivered: number;
6386
+ /** The runs and steps it resumed (the first 100). */
6387
+ runs: {
6388
+ run_id: string;
6389
+ step_id: string;
6390
+ }[];
6391
+ }
6392
+
6393
+ /**
6394
+ * A wait's `prompt` as evaluated when the step started waiting. `dropped` names fields left out because they were not https URLs.
6395
+ */
6396
+ export interface WaitPrompt {
6397
+ title?: string;
6398
+ body?: string;
6399
+ image?: string;
6400
+ /**
6401
+ * The render artifact the image came from, when `image` was one (`steps.shot.outputs.artifacts[0]`). Its URL is signed for a day; the link's page signs a fresh one, as the run's principal, each time it is served.
6402
+ */
6403
+ image_artifact?: string;
6404
+ link?: string;
6405
+ dropped?: Array<"image" | "link">;
6406
+ }
6407
+
6408
+ /** A wait link's step. */
6409
+ export interface RoutineWait {
6410
+ object: "routine_wait";
6411
+ /**
6412
+ * waiting: it takes an answer. pending: the step has not started waiting. answered: through a link or a signal. timed_out: its deadline passed. expired: 7 days after it started waiting. ended: the run ended, or the step was skipped or canceled, before an answer.
6413
+ */
6414
+ status: "waiting" | "pending" | "answered" | "timed_out" | "expired" | "ended";
6415
+ run_id: string;
6416
+ run_status: "queued" | "running" | "succeeded" | "failed" | "canceled";
6417
+ routine_id: string;
6418
+ routine_name?: string | null;
6419
+ step_id: string;
6420
+ step_name?: string | null;
6421
+ /**
6422
+ * The step's evaluated prompt while it waits, and after an answer while the node still holds the run (null once the run is only in the run store).
6423
+ */
6424
+ prompt: WaitPrompt | null;
6425
+ waiting_since?: string | null;
6426
+ /**
6427
+ * While the step waits, when the link stops taking an answer: 7 days after the step started waiting, or the step's own deadline (`wait.ms`, `wait.until`) when that is sooner.
6428
+ */
6429
+ expires_at?: string | null;
6430
+ /** Once answered. `decision` is null for a signal sent through the API without one. */
6431
+ answer: {
6432
+ decision?: "approve" | "reject" | null;
6433
+ approved?: boolean | null;
6434
+ comment?: string | null;
6435
+ via?: "link" | "signal";
6436
+ answered_at?: string | null;
6437
+ } | null;
6438
+ }
6439
+
6440
+ export interface SignalRequest {
6441
+ /** The `wait.signal` name the run waits for (routine.schema.json). */
6442
+ name: string;
6443
+ /** Becomes the waiting step's outputs. */
6444
+ payload?: unknown;
6445
+ }
6446
+
6447
+ /**
6448
+ * A CEL expression (the routines dialect, without `${{ }}`), compiled at create and run under a cost meter.
6449
+ * It sees `event` (`payload`, `headers`, `source`, `received_at`), `listener` (`id`, `name`, `metadata`) and
6450
+ * `now`; a source's `items` and `cursor` expressions see `response` (`status`, `headers`, `body`) and
6451
+ * `cursor` instead.
6452
+ */
6453
+ export type CelExpression = string;
6454
+
6455
+ /**
6456
+ * A vault connection in this project, injected by its type (`bearer`, `api_key`, `basic`, `oauth2`) into each
6457
+ * https request to the source when the URL's host is one of the connection's `hosts`. Resolved again at each
6458
+ * connect, so a rotated secret or a refreshed OAuth token applies from the next one. Needs `vault:run`.
6459
+ */
6460
+ export type ConnectionId = string;
6461
+
6462
+ /** Extra request headers. `Authorization`, `Cookie` and `Host` are refused here; use `connection`. */
6463
+ export type SourceHeaders = Record<string, string>;
6464
+
6465
+ export interface HttpPollSource {
6466
+ type: "http_poll";
6467
+ /**
6468
+ * http or https. May hold `${{ cursor }}`, replaced (URL-encoded) by the current cursor, or by an empty string before the first one.
6469
+ */
6470
+ url: string;
6471
+ /** @default "GET" */
6472
+ method?: "GET" | "POST";
6473
+ headers?: SourceHeaders;
6474
+ /** A JSON body for `POST`; string values may hold `${{ cursor }}`. */
6475
+ body?: unknown;
6476
+ connection?: ConnectionId;
6477
+ /**
6478
+ * Time between polls, from the end of one to the start of the next. 429 and 5xx answers back off up to 10 times this.
6479
+ * @default 60000
6480
+ */
6481
+ interval_ms?: number;
6482
+ /**
6483
+ * The list of events in a response. Default `response.body` when it is a list, else `[response.body]`.
6484
+ */
6485
+ items?: CelExpression;
6486
+ /**
6487
+ * The next cursor, from the response. It is stored only after every event of the response is in the log. `null` keeps the current one.
6488
+ */
6489
+ cursor?: CelExpression;
6490
+ /**
6491
+ * `skip`: the first poll records what is there and emits nothing; `emit`: it emits every item.
6492
+ * @default "skip"
6493
+ */
6494
+ initial?: "skip" | "emit";
6495
+ }
6496
+
6497
+ export interface SseSource {
6498
+ type: "sse";
6499
+ /** http or https. */
6500
+ url: string;
6501
+ headers?: SourceHeaders;
6502
+ connection?: ConnectionId;
6503
+ /**
6504
+ * Keep only frames whose `event:` is one of these (`message` for frames without one). `null` keeps every frame.
6505
+ */
6506
+ event_types?: string[] | null;
6507
+ /**
6508
+ * Reconnect when nothing (frames or comments) arrives for this long.
6509
+ * @default 90000
6510
+ */
6511
+ idle_timeout_ms?: number;
6512
+ }
6513
+
6514
+ /**
6515
+ * A WebSocket held by the node's socket holder (`b3os-listend`), a unit of its own, so a node release that
6516
+ * restarts the API server keeps the socket open: each frame is written to disk before anything reads it, and
6517
+ * the server reads what arrived while it was down. After a network drop or a restart of the holder itself the
6518
+ * source reconnects on HookBuffer's ladder (1, 2, 5, 10, 30, 60 s). The reconnect resumes when a cursor is
6519
+ * stored and the frames it sends (`resume`, else `subscribe`) hold `${{ cursor }}`; otherwise the time the
6520
+ * socket was down is a `gap` record in the history.
6521
+ *
6522
+ * A text frame that is JSON becomes the event's `payload` as JSON, any other text frame as a string, and a
6523
+ * binary frame as its base64 text with `headers.binary` true. A frame over `listeners.event_bytes_max` is
6524
+ * counted as failed and not kept.
6525
+ */
6526
+ export interface WebsocketSource {
6527
+ type: "websocket";
6528
+ /** ws or wss. A `connection` is sent only in a wss handshake. */
6529
+ url: string;
6530
+ headers?: SourceHeaders;
6531
+ connection?: ConnectionId;
6532
+ /**
6533
+ * Frames sent after each connect, in order. An object or array is sent as its JSON text, a string as it is; string values may hold `${{ cursor }}`, replaced by the stored cursor (an empty string before the first).
6534
+ */
6535
+ subscribe?: unknown[];
6536
+ /**
6537
+ * Frames sent instead of `subscribe` after a reconnect when a cursor is stored; string values may hold `${{ cursor }}`.
6538
+ */
6539
+ resume?: unknown[];
6540
+ /**
6541
+ * The cursor after an event, from `event` (`payload`, `headers`). It is stored once the event is in the log; `null` keeps the current one.
6542
+ */
6543
+ cursor?: CelExpression;
6544
+ /**
6545
+ * The events in one frame, from `frame` (its parsed JSON, or its text). By default a frame is one event. A frame whose `split` is not a list is counted as failed.
6546
+ */
6547
+ split?: CelExpression;
6548
+ /**
6549
+ * A ping is sent this often; a socket that sends nothing (no pong, no frame) for twice this long is reconnected.
6550
+ * @default 30000
6551
+ */
6552
+ ping_ms?: number;
4403
6553
  }
4404
6554
 
4405
6555
  /**
4406
- * Mandatory verification for POST /v1/routines/hooks/{hk_id} (ARCHITECTURE 4.3); the hk_ id is created when the version is published. b3os: B3OS-Signature 't=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<body>")>' with a per-hook secret B3OS generates (shown once by the API). github, stripe, slack, standard_webhooks: the provider's scheme as in b3pack verify. hmac_sha256: generic, and always timestamped: the signature covers '<value of timestamp_header>.<body>', and a delivery whose timestamp header is missing or not a Unix time is refused. Timestamped schemes reject deliveries more than tolerance_s (at most 300 s) from the node clock. Secrets never appear in the URL.
6556
+ * How a `webhook` source checks each delivery, as a routine's webhook trigger does. `b3os`: `B3OS-Signature:
6557
+ * t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<body>")>` with a per-hook secret B3OS makes, shown once in the
6558
+ * create answer (`source.secret`). `github`, `stripe`, `slack`, `standard_webhooks`: the provider's own
6559
+ * scheme, with its signing secret in `secret`. `hmac_sha256`: a generic HMAC over `<value of
6560
+ * timestamp_header>.<body>` in `header` (`header` and `timestamp_header` are required, and `dedupe.key` must
6561
+ * be set). Timestamped schemes refuse a delivery more than `tolerance_s` from the node clock. Secrets never
6562
+ * appear in the URL.
4407
6563
  */
4408
- export type RoutineDefinitionWebhookVerify = {
6564
+ export interface ListenerWebhookVerify {
4409
6565
  scheme: "b3os" | "github" | "stripe" | "slack" | "standard_webhooks" | "hmac_sha256";
4410
6566
  /**
4411
- * An api_key vault connection whose api_key field holds the provider's signing secret (vault.yaml field names). Store it as a verification-only connection, without pack and without hosts: B3OS reads it to check signatures, and a connection with no hosts is never injected into any request. Naming one needs vault:run on top of routines:write. Not used with b3os.
6567
+ * An `api_key` vault connection whose `api_key` holds the provider's signing secret. Keep it verification-only, with no pack and no hosts, so it is never injected into a request. Needs `vault:run`. Required for every scheme but `b3os`, and refused with it.
4412
6568
  */
4413
6569
  secret?: string;
6570
+ /** `hmac_sha256` only: the header holding the signature. */
4414
6571
  header?: string;
6572
+ /** `hmac_sha256` only: how the signature is written. Default `hex`. */
4415
6573
  encoding?: "hex" | "base64";
6574
+ /** `hmac_sha256` only: text before the signature in `header`, such as `sha256=`. */
4416
6575
  prefix?: string;
4417
- /** hmac_sha256 only, and required there: header carrying the delivery's Unix timestamp. */
6576
+ /** `hmac_sha256` only: the header holding the delivery's Unix timestamp. */
4418
6577
  timestamp_header?: string;
4419
6578
  /** @default 300 */
4420
6579
  tolerance_s?: number;
4421
- };
4422
-
4423
- export interface RoutineVersionRef {
4424
- id: string;
4425
- number: number;
4426
- created_at: string;
4427
6580
  }
4428
6581
 
4429
- export interface RoutineHook {
4430
- id: string;
6582
+ /**
6583
+ * Deliveries a provider sends to `hook_url` (`POST /v1/listeners/hooks/{hook_id}`), through the edge, which
6584
+ * queues them for 72 hours while the node is down. `hook_id`, `hook_url` and `secret` are set by B3OS and
6585
+ * refused in a request.
6586
+ */
6587
+ export interface WebhookSource {
6588
+ type: "webhook";
6589
+ verify: ListenerWebhookVerify;
6590
+ hook_id?: string;
4431
6591
  /** Give this URL to the provider. */
4432
- url: string;
4433
- verify: "b3os" | "github" | "stripe" | "slack" | "standard_webhooks" | "hmac_sha256";
4434
- /**
4435
- * The `b3os` scheme's signing secret. Present only in the response of the publish that created the hook (and of a rotation).
4436
- */
6592
+ hook_url?: string;
6593
+ /** The `b3os` scheme's signing secret, in the create answer only. */
4437
6594
  secret?: string;
4438
6595
  }
4439
6596
 
4440
- export interface RoutineTrigger {
4441
- /** The trigger's `id` in the definition. */
4442
- id: string;
4443
- type: "cron" | "interval" | "webhook" | "action";
4444
- status: "active" | "paused";
4445
- /** Next scheduled fire (cron and interval), or `null`. */
4446
- next_fire_at: string | null;
4447
- /** The inbound URL of a webhook trigger, or `null`. */
4448
- hook: null | RoutineHook;
6597
+ /**
6598
+ * A pack's trigger, as a routine's `type: action` trigger takes it: the actions trigger manager subscribes
6599
+ * (registering a provider webhook, or polling, or a schedule) and hands each event to the listener, keyed by
6600
+ * the trigger's own event ID. The event's `payload` is the trigger's `data`; its `headers` carry
6601
+ * `event_type`, `source`, `time` and `subscription_id`.
6602
+ */
6603
+ export interface PackSource {
6604
+ type: "pack";
6605
+ /** `<namespace>/<pack>/<trigger>@<version or major>`, such as `io.b3os/github/push@1`. */
6606
+ uses: string;
6607
+ /** The trigger's configuration, valid against its `configSchema`. */
6608
+ with?: unknown;
4449
6609
  /**
4450
- * The trigger subscription of an action trigger (`GET /v1/actions/subscriptions/{subscription_id}`), or `null`.
6610
+ * Connection key to `conn_` ID; an unbound required key takes the project's most recent connection for it.
4451
6611
  */
4452
- subscription_id: string | null;
6612
+ connections?: Record<string, ConnectionId>;
4453
6613
  }
4454
6614
 
4455
- export interface Routine {
4456
- id: string;
4457
- object: "routine";
4458
- name: string;
4459
- description: string | null;
4460
- /** `paused` when triggers are stopped; API runs still work unless `paused_reason` is `run_as_revoked`. */
4461
- status: "active" | "paused";
4462
- paused_reason: "manual" | "run_as_revoked" | null;
4463
- version: RoutineVersionRef;
4464
- triggers: RoutineTrigger[];
6615
+ /** Events arrive through `POST /v1/listeners/{listener_id}/events`. */
6616
+ export interface PushSource {
6617
+ type: "push";
6618
+ }
6619
+
6620
+ export type ListenerSource = HttpPollSource | SseSource | WebsocketSource | WebhookSource | PackSource | PushSource;
6621
+
6622
+ export interface ListenerDedupe {
4465
6623
  /**
4466
- * The identity runs execute as (the key that published the active version, with its scopes at publish time).
6624
+ * The event's identity, turned into text. Defaults: the SSE frame's `id` when it has one, a push event's
6625
+ * `dedupe_key`, otherwise the SHA-256 of the payload's canonical JSON.
4467
6626
  */
4468
- run_as: {
4469
- /** The API key ID; `null` when a dashboard user published. */
4470
- key: string | null;
4471
- scopes: string[];
4472
- };
4473
- created_at: string;
4474
- updated_at: string;
4475
- metadata: Metadata;
6627
+ key?: CelExpression;
4476
6628
  /**
4477
- * Present only when something about the active version needs attention. Today: a `product_unavailable` warning at `/triggers/<i>` for each action trigger whose subscription the actions product does not hold yet (it was not running, or answered 5xx or 429, when the version was published). The publish stands, the trigger starts no runs until it is subscribed, and routines retries the subscription every 10 seconds until the actions product takes it; the warning then goes away. A 4xx from the actions product fails the publish with `routine_invalid` instead.
6629
+ * How long a key is remembered; a repeat within it is dropped before the filter.
6630
+ * @default 86400
4478
6631
  */
4479
- warnings?: Diagnostic[];
4480
- }
4481
-
4482
- export type RoutineList = Omit<ListEnvelope, "data"> & {
4483
- data: Routine[];
4484
- };
4485
-
4486
- export interface RoutineUpdateRequest {
4487
- paused?: boolean;
4488
- metadata?: Metadata;
6632
+ window_s?: number;
4489
6633
  }
4490
6634
 
4491
- export interface RollbackRequest {
4492
- /** A `ver_` ID or a version number. */
4493
- version: string | number;
6635
+ export interface ListenerFilter {
6636
+ /**
6637
+ * Keep the event when this is `true`. An evaluation error drops the event as `filtered`, with the error in its record.
6638
+ */
6639
+ cel?: CelExpression;
6640
+ model?: ListenerModelFilter;
4494
6641
  }
4495
6642
 
4496
- export interface RoutineVersion {
4497
- id: string;
4498
- object: "routine_version";
4499
- routine_id: string;
4500
- number: number;
4501
- active: boolean;
4502
- /** The key ID that published this version. */
4503
- published_by: string | null;
4504
- /** The publisher's scopes, snapshotted; runs of this version get at most these. */
4505
- scopes: string[];
4506
- created_at: string;
4507
- definition?: RoutineDefinition;
6643
+ /**
6644
+ * One question to the small model (`b3os/qwen3.5-9b`) about each event CEL kept, asked after the event is in the
6645
+ * log and before the sink. The answer is `{match, reason}` plus `fields`; `match: false` ends the event
6646
+ * `filtered`. Calls run as the listener's owner (`infer:run`) and bill infer tokens, at most
6647
+ * `listeners.model_filter.rpm` a minute per listener, in order.
6648
+ */
6649
+ export interface ListenerModelFilter {
6650
+ /** The question, such as "Does this mail ask for something that must happen today?". */
6651
+ prompt: string;
6652
+ /**
6653
+ * The event's payload is cut to about this many tokens (four bytes of JSON each).
6654
+ * @default 2048
6655
+ */
6656
+ max_input_tokens?: number;
6657
+ /**
6658
+ * A JSON-schema object (`type: object`, at most 16 `properties`, none named `match` or `reason`) of extra values the model returns beside them; they are recorded in the event's `filter.model.fields`.
6659
+ */
6660
+ fields?: Record<string, unknown>;
6661
+ /**
6662
+ * What happens to an event the model could not judge (an error, a timeout, output that does not parse, the token budget spent).
6663
+ * @default "drop"
6664
+ */
6665
+ on_error?: "drop" | "pass";
4508
6666
  }
4509
6667
 
4510
- export type RoutineVersionList = Omit<ListEnvelope, "data"> & {
4511
- data: RoutineVersion[];
4512
- };
4513
-
4514
- export interface Diagnostic {
4515
- severity: "error" | "warning";
4516
- /** An error code from the catalog, such as `routine_invalid` or `connection_required`. */
4517
- code: string;
4518
- /** JSON pointer into the definition. */
4519
- pointer: string;
4520
- detail: string;
6668
+ /**
6669
+ * Hand kept events to the sink together: once `max_events` are waiting, or once the oldest has waited
6670
+ * `max_wait_ms`. One delivery is `{type: listener.batch, id, dedupe_key, count, first_seq, last_seq, events}`:
6671
+ * `events` in the order the listener kept them, each with its own `dedupe_key`, and the batch's `dedupe_key`
6672
+ * a digest of theirs, so a receiver that sees the same batch twice can drop it. A routine sink starts one run
6673
+ * per batch with the batch as its `trigger`. Needs `concurrency: 1`, and for a routine sink `mode: run`.
6674
+ */
6675
+ export interface ListenerBatch {
6676
+ max_events: number;
6677
+ /** @default 1000 */
6678
+ max_wait_ms?: number;
4521
6679
  }
4522
6680
 
4523
- export interface RoutineValidation {
4524
- object: "routine_validation";
4525
- valid: boolean;
4526
- diagnostics: Diagnostic[];
4527
- /** Number of steps in the compiled plan, map bodies included. */
4528
- steps?: number;
6681
+ export interface RoutineSink {
6682
+ type: "routine";
6683
+ /** The routine's ID (`rtn_…`) or name in this project. Needs `routines:run`. */
6684
+ routine: string;
6685
+ /**
6686
+ * `run` starts a run of the routine's active version per event, with `trigger = {type: listener, id,
6687
+ * event_id, seq, dedupe_key, received_at, payload}`; a redelivery of the same `dedupe_key` starts no
6688
+ * second run. `event` sends the event to the routine's runs waiting with `wait: {event: <event>}`
6689
+ * (`routinesSendEvent`), with `data` = the payload.
6690
+ * @default "run"
6691
+ */
6692
+ mode?: "run" | "event";
6693
+ /** The event name, for `mode: event` (required there). */
6694
+ event?: string | null;
6695
+ /**
6696
+ * Deliveries in flight at once. With 1, events arrive in the order the listener kept them.
6697
+ * @default 1
6698
+ */
6699
+ concurrency?: number;
6700
+ /**
6701
+ * How long a retryable failure (5xx, 429, 503) is retried, with backoff, before the event is `failed`.
6702
+ * @default 86400
6703
+ */
6704
+ retry_for_s?: number;
6705
+ batch?: ListenerBatch;
4529
6706
  }
4530
6707
 
4531
- export interface RoutineImportRequest {
4532
- format: "b3os-workflow-v1";
4533
- /** The workflow JSON exported from the original B3OS app. */
4534
- workflow: Record<string, unknown>;
6708
+ export interface WebhookSink {
6709
+ type: "webhook";
6710
+ /**
6711
+ * https. Each kept event is POSTed as a `WebhookEvent` (`type: listener.event`, `job_id` = the listener)
6712
+ * signed with `B3OS-Signature` under the endpoint's secret (`POST /v1/webhooks/secret`), through the
6713
+ * egress guard and retried for 24 hours. Its `data` is `{type: listener, id, event_id, seq, dedupe_key,
6714
+ * received_at, payload}`; `data.dedupe_key` (32 hex characters, a digest of the listener and the event's
6715
+ * key) is the same on every delivery of one event, so a receiver can drop a repeat. With `batch`, the
6716
+ * event type is `listener.batch` and `data` is the batch (`ListenerBatch`).
6717
+ */
6718
+ url: string;
6719
+ /** @default 1 */
6720
+ concurrency?: number;
6721
+ /** @default 86400 */
6722
+ retry_for_s?: number;
6723
+ batch?: ListenerBatch;
4535
6724
  }
4536
6725
 
4537
- export interface RoutineImport {
4538
- object: "routine_import";
4539
- definition: RoutineDefinition;
4540
- diagnostics: Diagnostic[];
4541
- }
6726
+ export type ListenerSink = RoutineSink | WebhookSink;
4542
6727
 
4543
- export interface HookTestRequest {
4544
- /** The JSON body to deliver; `trigger.body` of the run it starts. */
4545
- body?: Record<string, unknown>;
4546
- }
6728
+ /**
6729
+ * JSON pointers into the payload (`/customer/email`). Their values are replaced by `"[redacted]"` before the
6730
+ * event is written anywhere: the log, the history and the sink's copy. A pointer that does not exist in an
6731
+ * event changes nothing. The filter sees the redacted event too.
6732
+ */
6733
+ export type ListenerRedact = string[];
4547
6734
 
4548
- /** One request to a known hook, as its delivery log keeps it. */
4549
- export interface HookDeliveryEntry {
4550
- object: "hook_delivery_entry";
4551
- hook_id: string;
4552
- received_at: string;
4553
- method: "POST" | "GET";
4554
- /** `edge_replay`: replayed from the edge's queue after the node was down; `test`: `POST …/test`. */
4555
- source: "provider" | "edge_replay" | "test";
4556
- /** The HTTP status the hook answered. */
4557
- status: number;
6735
+ export interface ListenerBudgetRequest {
4558
6736
  /**
4559
- * `not_started`: accepted without a run (`if` was false, or the routine is paused); `rejected`: a 4xx; `unavailable`: a 5xx (the edge retries).
6737
+ * Events the filter may keep per UTC day. At the limit, delivery pauses (`status_reason: budget`) and further events are kept as `skipped` until the day ends. At most the organization's `listeners.events.daily`.
4560
6738
  */
4561
- outcome: "started" | "deduplicated" | "not_started" | "handshake" | "rejected" | "unavailable";
4562
- /** The error code of a 4xx or 5xx. */
4563
- code: string | null;
4564
- /** The `reason` of a `webhook_signature_invalid` (`signature` or `timestamp`). */
4565
- reason: string | null;
4566
- /** The error's detail (at most 500 characters). */
4567
- detail: string | null;
4568
- run_id: string | null;
4569
- delivery_id: string | null;
4570
- deduplicated: boolean;
4571
- handshake: "slack_url_verification" | "slack_ssl_check" | "github_ping" | "get_challenge" | null;
4572
- /** Body bytes (the body itself is not kept). */
4573
- size: number;
4574
- /** The allowlisted request headers it had (values up to 256 characters). */
4575
- headers: Record<string, string>;
6739
+ events_per_day?: number;
6740
+ /**
6741
+ * Infer tokens the model filter may spend per UTC day; past it, events go by `filter.model.on_error`. Default and at most ten times the organization's `listeners.model_tokens.default`.
6742
+ */
6743
+ model_tokens_per_day?: number;
4576
6744
  }
4577
6745
 
4578
- export type HookDeliveryEntryList = Omit<ListEnvelope, "data"> & {
4579
- data: HookDeliveryEntry[];
4580
- };
4581
-
4582
- export interface HookRotateRequest {
4583
- /** @default 86400 */
4584
- grace_s?: number;
6746
+ export interface ListenerCreateRequest {
6747
+ /** A label; not unique. */
6748
+ name?: string | null;
6749
+ source: ListenerSource;
6750
+ dedupe?: ListenerDedupe;
6751
+ filter?: ListenerFilter;
6752
+ sink: ListenerSink;
6753
+ redact?: ListenerRedact;
6754
+ /** Seconds from now until the listener ends `expired`. Not with `expires_at`. */
6755
+ ttl_s?: number;
6756
+ /** When the listener ends `expired`. Not with `ttl_s`. */
6757
+ expires_at?: string;
6758
+ budget?: ListenerBudgetRequest;
6759
+ metadata?: Metadata;
4585
6760
  }
4586
6761
 
4587
- export interface HookSecret {
4588
- object: "hook_secret";
4589
- hook_id: string;
4590
- secret: string;
4591
- previous_valid_until: string | null;
6762
+ export interface ListenerUpdateRequest {
6763
+ paused?: boolean;
6764
+ /** Seconds from now until the listener ends `expired`. Not with `expires_at`. */
6765
+ ttl_s?: number;
6766
+ /** When the listener ends `expired`; `null` lets it live until deleted. */
6767
+ expires_at?: string | null;
6768
+ filter?: ListenerFilter;
6769
+ sink?: ListenerSink;
6770
+ redact?: ListenerRedact;
6771
+ budget?: ListenerBudgetRequest;
6772
+ metadata?: Metadata;
4592
6773
  }
4593
6774
 
4594
- /** How the run started (the `trigger` context of its expressions). */
4595
- export interface RunTrigger {
4596
- type: "api" | "cron" | "interval" | "webhook" | "action" | "routine" | "replay";
4597
- /** The trigger ID (cron, interval, webhook, action). */
4598
- id?: string;
4599
- /** Cron and interval occurrence, used to deduplicate fires. */
4600
- occurrence_id?: string;
4601
- scheduled_at?: string;
4602
- hook_id?: string;
4603
- delivery_id?: string;
4604
- /** The trigger subscription that delivered the event (action triggers). */
4605
- subscription_id?: string;
4606
- /** The pack trigger event's ID (action triggers). */
4607
- event_id?: string;
4608
- /** For sub-routine runs, the calling run; for replays, the source run. */
4609
- parent_run_id?: string;
4610
- parent_step_id?: string;
4611
- /** For replays started with `from_step`, that step. */
4612
- from_step?: string;
4613
- }
6775
+ /**
6776
+ * `starting` until the first connect or poll succeeds; `active`; `reconnecting` while the source is down and
6777
+ * being retried; `paused` (`status_reason` `user` or `budget`); then the ends: `failed` (`error` says why),
6778
+ * `expired` (its lifetime passed) and `revoked` (its owner key was revoked or expired, or its sandbox ended).
6779
+ */
6780
+ export type ListenerStatus = "starting" | "active" | "reconnecting" | "paused" | "failed" | "expired" | "revoked";
4614
6781
 
4615
- export interface StepRun {
4616
- /** The step ID from the definition. */
6782
+ export interface Listener {
4617
6783
  id: string;
4618
- uses?: string;
4619
- /** Position in the map's list, for steps inside a map body. */
4620
- item_index?: number;
4621
- status: "pending" | "running" | "waiting" | "retrying" | "succeeded" | "failed" | "skipped" | "canceled";
4622
- /**
4623
- * The attempt this execution is. Retries add one; so does a node restart while the step ran (the earlier attempt's result, should it arrive, is discarded).
4624
- */
4625
- attempt: number;
4626
- started_at?: string;
4627
- finished_at?: string;
4628
- duration_ms?: number;
4629
- /** The step's outputs, once it succeeded. */
4630
- outputs?: unknown;
4631
- error?: Problem;
4632
- /** Item counts for a map step. */
4633
- map?: {
4634
- total?: number;
4635
- succeeded?: number;
4636
- failed?: number;
4637
- running?: number;
6784
+ object: "listener";
6785
+ name: string | null;
6786
+ status: ListenerStatus;
6787
+ status_reason:
6788
+ | "user"
6789
+ | "budget"
6790
+ | "auth"
6791
+ | "egress_denied"
6792
+ | "source_errors"
6793
+ | "owner_revoked"
6794
+ | "sandbox_ended"
6795
+ | null;
6796
+ /** Why the source last failed, or why the listener ended `failed`. */
6797
+ error: {
6798
+ code: string;
6799
+ detail: string;
6800
+ at: string;
6801
+ } | null;
6802
+ source: ListenerSource;
6803
+ source_state: {
6804
+ /** The stored cursor (`http_poll`, `websocket`) or last event ID (`sse`); `null` before the first. */
6805
+ cursor: unknown;
6806
+ connected_since: string | null;
6807
+ /** The next poll, or the next reconnect attempt while `reconnecting`. */
6808
+ next_attempt_at: string | null;
4638
6809
  };
4639
- /**
4640
- * What a waiting step waits for. `token` and `prompt` show in the run's current state (`GET /v1/routines/runs/{run_id}`), not in event snapshots.
4641
- */
4642
- waiting_for?: {
4643
- signal?: string;
4644
- until?: string;
4645
- /** The step has a wait link (`token: true`); the link itself is only in `run.wait_urls`. */
4646
- token?: true;
4647
- prompt?: WaitPrompt;
4648
- /** An event wait's event name (`POST /v1/routines/events`). */
4649
- event?: string;
4650
- /** An event wait's evaluated match values, by dot path into the event's data. */
4651
- match?: Record<string, unknown>;
6810
+ dedupe: ListenerDedupe;
6811
+ filter: ListenerFilter;
6812
+ sink: ListenerSink;
6813
+ redact: ListenerRedact;
6814
+ expires_at: string | null;
6815
+ budget: {
6816
+ events_per_day: number;
6817
+ model_tokens_per_day: number;
6818
+ used: {
6819
+ events: number;
6820
+ model_tokens: number;
6821
+ window_start: string;
6822
+ };
6823
+ };
6824
+ owner: {
6825
+ kind: "key" | "project";
6826
+ /** The owning key (`key_…`) or project (`prj_…`). */
6827
+ id: string;
6828
+ /** The sandbox that created it, when one did; the listener ends with that sandbox's root. */
6829
+ sandbox: string | null;
6830
+ };
6831
+ stats: {
6832
+ received: number;
6833
+ delivered: number;
6834
+ filtered: number;
6835
+ duplicates: number;
6836
+ failed: number;
6837
+ skipped: number;
6838
+ reconnects: number;
6839
+ last_event_at: string | null;
4652
6840
  };
4653
- /** A replay copied this step's outputs from its source run; the step did not run. Absent otherwise. */
4654
- replayed?: true;
6841
+ created_at: string;
6842
+ updated_at: string;
6843
+ metadata: Metadata;
4655
6844
  }
4656
6845
 
4657
- export type StepRunList = Omit<ListEnvelope, "data"> & {
4658
- data: StepRun[];
6846
+ export type ListenerList = Omit<ListEnvelope, "data"> & {
6847
+ data: Listener[];
4659
6848
  };
4660
6849
 
4661
- export interface RunCreateRequest {
4662
- /** Validated against the routine's `inputs`; defaults from it are applied. */
4663
- input?: Record<string, unknown>;
4664
- /** Run this version instead of the active one (`ver_` ID or number). */
4665
- version?: string | number;
4666
- /** Override the routine's default durability for this run. */
4667
- durability?: "ephemeral" | "standard" | "strict";
4668
- webhook?: WebhookConfig;
4669
- metadata?: Metadata;
4670
- }
4671
-
4672
- export interface RunReplayRequest {
4673
- /**
4674
- * Run this top-level step and every step downstream of it again. Absent: only the steps that did not succeed, and those downstream of them, run again.
4675
- */
4676
- from_step?: string;
4677
- /**
4678
- * The new run's input instead of the source run's; validated against the version's `inputs`. When it differs from the source's, the steps that read it (directly or through `env`) and the steps that wait for a signal run again, with every step downstream of them.
4679
- */
4680
- input?: Record<string, unknown>;
4681
- /**
4682
- * Replay with this version instead of the source run's (`ver_` ID or number). The steps it adds or changes and the steps that wait for a signal run again, with every step downstream of them.
4683
- */
4684
- version?: string | number;
4685
- /** Override the version's default durability for the new run. */
4686
- durability?: "ephemeral" | "standard" | "strict";
4687
- webhook?: WebhookConfig;
4688
- metadata?: Metadata;
4689
- }
6850
+ /**
6851
+ * `pending` (in the log, being delivered or retried), `delivered`, `filtered` (the filter dropped it or could
6852
+ * not evaluate), `failed` (the sink refused it, or kept failing for `retry_for_s`), `skipped` (the budget was
6853
+ * spent).
6854
+ */
6855
+ export type ListenerEventStatus = "pending" | "delivered" | "filtered" | "failed" | "skipped";
4690
6856
 
4691
- /** A routine run (`run_…`); `result` is the routine's `output`. */
4692
- export type RoutineRun = Omit<Job, "id" | "object"> & {
6857
+ export interface ListenerEvent {
4693
6858
  id: string;
4694
- object: "routine_run";
4695
- routine_id: string;
4696
- version_id: string;
4697
- version_number: number;
4698
- durability: "ephemeral" | "standard" | "strict";
4699
- trigger: RunTrigger;
4700
- input: Record<string, unknown>;
4701
- /**
4702
- * The run's outcome line: when the routine's `output` is an object with a non-empty `summary` string,
4703
- * that string on one line, cut to 140 characters (an ellipsis marks the cut). Absent otherwise. Run
4704
- * lists, the run's terminal event and its webhook carry it, so a list of runs says what each one did.
4705
- */
4706
- summary?: string;
4707
- /** Top-level steps in definition order (empty when `steps_kept` is `false`). */
4708
- steps: StepRun[];
6859
+ object: "listener_event";
6860
+ listener: string;
6861
+ /** The listener's own sequence number, from 1, gap records included. */
6862
+ seq: number;
6863
+ kind: "event" | "gap";
6864
+ received_at: string;
6865
+ dedupe_key: string | null;
6866
+ /** The event as the source sent it (JSON, or a string for text), after `redact`. `null` for a gap. */
6867
+ payload: unknown;
6868
+ payload_truncated: boolean;
6869
+ filter: {
6870
+ cel?: boolean | null;
6871
+ error?: string | null;
6872
+ /**
6873
+ * The model filter's verdict, `{match, reason, fields, tokens}`, or when it could not judge `{match: null, error: {code, detail}, on_error, tokens}`.
6874
+ */
6875
+ model?: {
6876
+ match?: boolean | null;
6877
+ reason?: string;
6878
+ fields?: Record<string, unknown>;
6879
+ tokens?: number;
6880
+ error?: {
6881
+ code?: string;
6882
+ detail?: string;
6883
+ };
6884
+ on_error?: "drop" | "pass";
6885
+ } | null;
6886
+ } | null;
6887
+ status: ListenerEventStatus | null;
6888
+ delivery: {
6889
+ attempts: number;
6890
+ /** The run (`run_…`) or webhook delivery the sink made. */
6891
+ sink_ref: string | null;
6892
+ delivered_at: string | null;
6893
+ last_error: {
6894
+ code?: string;
6895
+ detail?: string;
6896
+ } | null;
6897
+ } | null;
6898
+ /** For `kind: gap`, the time the source was down. */
6899
+ gap: {
6900
+ from: string;
6901
+ to: string;
6902
+ reason: "disconnected" | "node_restart" | "backlog_full";
6903
+ } | null;
4709
6904
  /**
4710
- * `false` on an `ephemeral` run read after it ended: only its summary was kept (status, timing,
4711
- * `input`, `result`, `error` and its IDs), so `steps` is empty, `…/steps` and a replay answer 410
4712
- * `run_steps_not_kept`, and `…/events` sends its terminal event alone. The `?wait=` answer, the event
4713
- * stream and the webhook carried its steps as it ended. Absent on every other run.
6905
+ * Where the node spent the time between receiving the event and its sink accepting it, measured on the node
6906
+ * in milliseconds with microsecond resolution (the platform's `Timing`). `append_ms`: from receipt (the frame
6907
+ * read, the poll's response or the request in hand) to the event durable in the listener's log; dedupe and
6908
+ * the CEL filter run inside it. `filter_ms`: the model filter's question, only when it was asked.
6909
+ * `sink_ms`: from the log, or the model filter's verdict, to the sink accepting the event (a run created, a
6910
+ * webhook delivery queued, a batch handed over), the wait for the delivery task, every retry and a batch's
6911
+ * wait included. `total_ms`: from receipt to the last phase the event reached. A phase the event did not
6912
+ * go through is left out: an event the filter dropped has no `sink_ms`. Absent on a gap record, on an
6913
+ * event still on its way to the sink, and on events whose receipt the node did not see (kept before a
6914
+ * restart of b3osd, or before the node recorded timing).
4714
6915
  */
4715
- steps_kept?: false;
4716
- };
6916
+ timing?: Timing | null;
6917
+ }
4717
6918
 
4718
- export type RoutineRunList = Omit<ListEnvelope, "data"> & {
4719
- data: RoutineRun[];
6919
+ export type ListenerEventList = Omit<ListEnvelope, "data"> & {
6920
+ data: ListenerEvent[];
4720
6921
  };
4721
6922
 
4722
- /** `step.*` events carry `step` (a `StepRun`); `run.log` carries `step_id`, `level` and `message`. */
4723
- export type RunEvent = JobEvent & {
4724
- step?: StepRun;
4725
- step_id?: string;
4726
- level?: "debug" | "info" | "warn" | "error";
4727
- message?: string;
4728
- };
6923
+ export interface ListenerStreamFrame {
6924
+ type: "listener.event" | "listener.gap" | "listener.status";
6925
+ ts: string;
6926
+ seq: number;
6927
+ event?: ListenerEvent | null;
6928
+ status?: ListenerStatus | null;
6929
+ }
4729
6930
 
4730
- export interface RoutineEventRequest {
4731
- /** The event name `wait.event` names. */
4732
- name: string;
4733
- /** What `wait.match` is checked against, and the step's `data` output. */
4734
- data?: unknown;
4735
- /** Your ID for the event, passed to the step's `id` output. */
4736
- id?: string;
6931
+ export interface ListenerIngestRequest {
6932
+ events: {
6933
+ /** Any JSON value, at most `listeners.event_bytes_max` when serialized. */
6934
+ payload: unknown;
6935
+ dedupe_key?: string;
6936
+ }[];
4737
6937
  }
4738
6938
 
4739
- export interface RoutineEvent {
4740
- object: "routine_event";
4741
- name: string;
4742
- id?: string | null;
4743
- /** How many waiting steps the event resumed. */
4744
- delivered: number;
4745
- /** The runs and steps it resumed (the first 100). */
4746
- runs: {
4747
- run_id: string;
4748
- step_id: string;
6939
+ export interface ListenerIngestResult {
6940
+ object: "listener_ingest";
6941
+ accepted: number;
6942
+ duplicates: number;
6943
+ events: {
6944
+ /** The event's ID; `null` for a duplicate. */
6945
+ id: string | null;
6946
+ seq: number | null;
6947
+ status: "pending" | "duplicate";
4749
6948
  }[];
4750
6949
  }
4751
6950
 
4752
- /**
4753
- * A wait's `prompt` as evaluated when the step started waiting. `dropped` names fields left out because they were not https URLs.
4754
- */
4755
- export interface WaitPrompt {
4756
- title?: string;
4757
- body?: string;
4758
- image?: string;
4759
- /**
4760
- * The render artifact the image came from, when `image` was one (`steps.shot.outputs.artifacts[0]`). Its URL is signed for a day; the link's page signs a fresh one, as the run's principal, each time it is served.
4761
- */
4762
- image_artifact?: string;
4763
- link?: string;
4764
- dropped?: Array<"image" | "link">;
6951
+ export interface ListenerTestRequest {
6952
+ /** A sample event payload. */
6953
+ payload: unknown;
6954
+ /** @default false */
6955
+ deliver?: boolean;
4765
6956
  }
4766
6957
 
4767
- /** A wait link's step. */
4768
- export interface RoutineWait {
4769
- object: "routine_wait";
4770
- /**
4771
- * waiting: it takes an answer. pending: the step has not started waiting. answered: through a link or a signal. timed_out: its deadline passed. expired: 7 days after it started waiting. ended: the run ended, or the step was skipped or canceled, before an answer.
4772
- */
4773
- status: "waiting" | "pending" | "answered" | "timed_out" | "expired" | "ended";
4774
- run_id: string;
4775
- run_status: "queued" | "running" | "succeeded" | "failed" | "canceled";
4776
- routine_id: string;
4777
- routine_name?: string | null;
4778
- step_id: string;
4779
- step_name?: string | null;
4780
- /**
4781
- * The step's evaluated prompt while it waits, and after an answer while the node still holds the run (null once the run is only in the run store).
4782
- */
4783
- prompt: WaitPrompt | null;
4784
- waiting_since?: string | null;
4785
- /**
4786
- * While the step waits, when the link stops taking an answer: 7 days after the step started waiting, or the step's own deadline (`wait.ms`, `wait.until`) when that is sooner.
4787
- */
4788
- expires_at?: string | null;
4789
- /** Once answered. `decision` is null for a signal sent through the API without one. */
4790
- answer: {
4791
- decision?: "approve" | "reject" | null;
4792
- approved?: boolean | null;
4793
- comment?: string | null;
4794
- via?: "link" | "signal";
4795
- answered_at?: string | null;
4796
- } | null;
6958
+ export interface ListenerTestResult {
6959
+ object: "listener_test";
6960
+ dedupe_key: string | null;
6961
+ /** Whether the key is in the dedupe window now. */
6962
+ duplicate: boolean;
6963
+ filter: {
6964
+ cel?: boolean | null;
6965
+ error?: string | null;
6966
+ };
6967
+ /** Whether the listener would keep the event (not a duplicate, and the filter passed). */
6968
+ kept: boolean;
6969
+ /** With `deliver: true` and a kept event, the event as written to the log. */
6970
+ event: ListenerEvent | null;
4797
6971
  }
4798
6972
 
4799
- export interface SignalRequest {
4800
- /** The `wait.signal` name the run waits for (routine.schema.json). */
4801
- name: string;
4802
- /** Becomes the waiting step's outputs. */
4803
- payload?: unknown;
6973
+ /**
6974
+ * One JSON-RPC 2.0 message of the Model Context Protocol (https://modelcontextprotocol.io): a request
6975
+ * (`method` and `id`), a notification (`method`, no `id`) or a response (`result` or `error`). Methods served:
6976
+ * `initialize`, `server/discover`, `ping`, `tools/list`, `tools/call`, the empty `resources/list`,
6977
+ * `resources/templates/list` and `prompts/list`, and every `notifications/*`.
6978
+ */
6979
+ export interface McpMessage {
6980
+ jsonrpc: "2.0";
6981
+ /** A string, an integer or `null` (a response to a message whose id could not be read). */
6982
+ id?: unknown;
6983
+ method?: string;
6984
+ params?: Record<string, unknown>;
6985
+ result?: Record<string, unknown>;
6986
+ error?: {
6987
+ code: number;
6988
+ message: string;
6989
+ data?: unknown;
6990
+ };
4804
6991
  }
4805
6992
 
4806
6993
  /**
4807
- * One manifest per pack: connections, egress, actions (T0 declarative HTTP or T1 first-party JS), triggers (webhook, poll, schedule), fixtures, pricing and the publisher signature. Field names follow research/b3os-actions.md section 12.3 (camelCase, like MCP). Every string that contains ${{ }} is a CEL template; the template rules and CEL contexts are in packages/spec/schemas/README.md. Rules JSON Schema cannot express (unique action keys, egress subset, connection references, effect consistency) are listed in the README under 'b3pack publish checks' and are enforced by the actions registry and by examples/validate.mjs. Owner after freeze: actions.
6994
+ * One manifest per pack: connections, egress, actions (T0 declarative HTTP, T1 first-party JS, or vm: a hosted tool's command run in a fresh microVM), triggers (webhook, poll, schedule), fixtures, pricing and the publisher signature. A pack whose actions are vm is a hosted tool and has a tool block. Field names follow research/b3os-actions.md section 12.3 (camelCase, like MCP). Every string that contains ${{ }} is a CEL template; the template rules and CEL contexts are in packages/spec/schemas/README.md. Rules JSON Schema cannot express (unique action keys, egress subset, connection references, effect consistency, what a hosted tool may declare in this version) are listed in the README under 'b3pack publish checks' and are enforced by the actions registry and by examples/validate.mjs. Owner after freeze: actions.
4808
6995
  */
4809
6996
  export interface B3Pack {
4810
6997
  /** Optional pointer to this schema for editors. Ignored by the runtime. */
4811
6998
  $schema?: string;
4812
6999
  pack: B3PackPackId;
7000
+ /**
7001
+ * The version. <x.y.z>-dev.<unix seconds> is a dev version (README, publish check 23): org-private tools only, outside the version limit, and replaced by the next dev version of the pack.
7002
+ */
4813
7003
  version: B3PackSemver;
4814
7004
  title: string;
4815
7005
  description: string;
@@ -4837,7 +7027,7 @@ export interface B3Pack {
4837
7027
  sizes?: string[];
4838
7028
  }[];
4839
7029
  /**
4840
- * Pack runtime API the pack needs, as a caret range (npm and Cargo read it the same way). The v1 runtime is 1.0.0, so packs declare ^1 or ^1.0.
7030
+ * Pack runtime API the pack needs, as a caret range (npm and Cargo read it the same way). The runtime is 1.1.0: packs without a tool block declare ^1, ^1.0 or ^1.1; a pack with a tool block declares ^1.1 or later (the vm kind is runtime API 1.1), so a node from before hosted tools refuses it instead of loading half of it.
4841
7031
  */
4842
7032
  engine: string;
4843
7033
  /**
@@ -4851,9 +7041,10 @@ export interface B3Pack {
4851
7041
  actions: B3PackAction[];
4852
7042
  triggers?: B3PackTrigger[];
4853
7043
  /**
4854
- * Default price for every action that does not set its own. v0.1 packs are free; the node still meters actions.call (ARCHITECTURE 4.5).
7044
+ * Default price for every action that does not set its own. A price is charged on vm actions only (a hosted tool's publisher price, usage unit actions.publisher_microusd); packs without vm actions are free and the node still meters actions.call (ARCHITECTURE 4.5).
4855
7045
  */
4856
7046
  pricing?: B3PackPricing;
7047
+ tool?: B3PackTool;
4857
7048
  compat?: {
4858
7049
  /**
4859
7050
  * Maps an action key in this pack to the flat action id it replaces in the old B3OS catalog (research 12.3, 13). Used by the importer so old workflows resolve.
@@ -4915,7 +7106,7 @@ export interface B3PackEgressEntry {
4915
7106
  }
4916
7107
 
4917
7108
  /**
4918
- * A JSON Schema 2020-12 document whose top level describes an object (MCP requires object-typed inputSchema and outputSchema). Objects should be closed (additionalProperties false) unless declared open (research 12.4). x-b3-* keywords (x-b3-widget, x-b3-semantic, x-b3-options, ...) are allowed as annotations and ignored by validation.
7109
+ * A JSON Schema 2020-12 document whose top level describes an object (MCP requires object-typed inputSchema and outputSchema). Objects should be closed (additionalProperties false) unless declared open (research 12.4). x-b3-* keywords (x-b3-widget, x-b3-semantic, x-b3-options, ...) are allowed as annotations and ignored by validation. x-b3os-file marks a file field of a vm action: on a top-level property of inputSchema it is {"accept": [media types]} and the property's value is a file value; on a top-level property of outputSchema it is {"produces": [media types]} and the tool answers {"path": "/out/<name>"} there (README, 'b3pack publish checks' 19).
4919
7110
  */
4920
7111
  export type B3PackJsonSchemaObject = JsonSchemaDocument & {
4921
7112
  type: "object";
@@ -4977,11 +7168,12 @@ export interface B3PackEffects {
4977
7168
  }
4978
7169
 
4979
7170
  /**
4980
- * Publisher price on top of the platform's actions.call meter. v0.1 first-party packs are free. Amounts are decimal strings in USD to avoid float rounding.
7171
+ * Publisher price, charged on vm actions only, on top of the platform's own meters (a hosted tool's call bills actions.tool_call, actions.vcpu_ms and actions.gib_ms; the price is actions.publisher_microusd). First-party packs and org-private tools are free. Amounts are decimal strings in USD to avoid float rounding; the publish checks hold usd to at most 6 decimal places, so it is a whole number of micro-USD, and to at most 1 USD a call (per_call), 0.01 USD a second (per_second) or 0.01 USD a MiB (per_input_mb). per_call charges usd once per call; per_second charges ceil(usd in micro-USD x run_ms / 1000), run_ms being the node's clock around the tool's own command only (copy and unpack never count); per_input_mb charges ceil(usd in micro-USD x in_bytes / 1048576), in_bytes being the call's input file bytes plus its stdin JSON. A price is charged only on a call that answered validly. freeCalls (priced models only): the calls each calling organization makes free of the price each UTC month, per pack, counted on the node.
4981
7172
  */
4982
7173
  export interface B3PackPricing {
4983
- model: "free" | "per_call";
7174
+ model: "free" | "per_call" | "per_second" | "per_input_mb";
4984
7175
  usd?: string;
7176
+ freeCalls?: number;
4985
7177
  }
4986
7178
 
4987
7179
  export type B3PackHeaderName = string;
@@ -5037,7 +7229,7 @@ export interface B3PackHttpResponse {
5037
7229
  }
5038
7230
 
5039
7231
  /**
5040
- * How the action runs. http = T0, declarative HTTP inside b3osd. js = T1, a first-party ES module run by the actions-js sidecar (packages/spec/sidecars/actions-js.md).
7232
+ * How the action runs. http = T0, declarative HTTP inside b3osd. js = T1, a first-party ES module run by the actions-js sidecar (packages/spec/sidecars/actions-js.md). vm = a hosted tool: each call runs cmd in a fresh microVM of tool.base with the tool's archive unpacked at /tool, the request as one JSON object on stdin and one JSON object as the last line of stdout (protocol json-stdio, README 'Hosted tools').
5041
7233
  */
5042
7234
  export type B3PackImpl =
5043
7235
  | {
@@ -5056,6 +7248,17 @@ export type B3PackImpl =
5056
7248
  * @default "run"
5057
7249
  */
5058
7250
  export?: string;
7251
+ }
7252
+ | {
7253
+ kind: "vm";
7254
+ /**
7255
+ * The request is one JSON object on stdin; the answer is the last line of stdout, {"output": ...} or {"error": {code, message, retryable}}, with exit status 0 either way.
7256
+ */
7257
+ protocol: "json-stdio";
7258
+ /**
7259
+ * The command and its arguments, run with no shell, working directory /work, as the guest's user. Fixed text: no caller value ever enters it. cmd[0] is a path under /tool/ (publish check 18).
7260
+ */
7261
+ cmd: string[];
5059
7262
  };
5060
7263
 
5061
7264
  export type B3PackExample =
@@ -5094,9 +7297,24 @@ export type B3PackAction = {
5094
7297
  egress?: B3PackEgressEntry[];
5095
7298
  execution?: {
5096
7299
  /**
5097
- * Wall-clock budget per call, including upstream time. Default 10000 for http, 30000 for js. A caller's shorter deadline wins.
7300
+ * Wall-clock budget per call, including upstream time. Default 10000 for http, 30000 for js and vm; at most 60000 for vm. A caller's shorter deadline wins, except on a priced vm action, where a shorter timeout_ms is refused.
5098
7301
  */
5099
7302
  timeoutMs?: number;
7303
+ /**
7304
+ * vm only: the most input file data one call may carry, in MiB, summed over its file values ($bytes, $url and $file alike). Default 16, at most 64.
7305
+ * @default 16
7306
+ */
7307
+ maxInputMb?: number;
7308
+ /**
7309
+ * vm only: the most output file data one call may return, in MiB, summed over its output files. Default 16, at most 64.
7310
+ * @default 16
7311
+ */
7312
+ maxOutputMb?: number;
7313
+ /**
7314
+ * vm only: the most output files one call may return. Default 4, at most 16.
7315
+ * @default 4
7316
+ */
7317
+ maxOutputFiles?: number;
5100
7318
  /** T1 only: V8 old-generation limit of the worker running the call. Default 128. */
5101
7319
  memoryMb?: number;
5102
7320
  /**
@@ -5113,7 +7331,9 @@ export type B3PackAction = {
5113
7331
  examples?: B3PackExample[];
5114
7332
  pricing?: B3PackPricing;
5115
7333
  mcp?: {
5116
- /** MCP tool name override; must be unique in the pack. */
7334
+ /**
7335
+ * MCP tool name override; must be unique in the pack. A name that starts with browser_, vision_ or render_ (and not another _ after it) is reserved for B3OS's product tools (node release 1119).
7336
+ */
5117
7337
  name?: string;
5118
7338
  /**
5119
7339
  * false keeps the action out of tools/list (still callable through actions_call). Default true.
@@ -5271,6 +7491,105 @@ export type B3PackTrigger = {
5271
7491
  aliases?: B3PackSearchPhrases;
5272
7492
  };
5273
7493
 
7494
+ /**
7495
+ * A hosted tool: the software a pack's vm actions run, and what it needs to run. Required when any action is vm and refused otherwise (publish checks 13 to 23). The schema admits the values of later versions (mcp, the other bases, session, hosts, caller, any size) and the reserved keys (setup, image, formats, bundle.files, base.range), so that what this version refuses is refused with a plain sentence of the publish checks rather than a schema error.
7496
+ */
7497
+ export interface B3PackTool {
7498
+ /**
7499
+ * cli: a command that reads a request on stdin and writes an answer on stdout. mcp (later, not in this version): an MCP server. Shown on the listing.
7500
+ */
7501
+ kind: "cli" | "mcp";
7502
+ /** The shared template the tool runs on. Bases have no versions yet. */
7503
+ base: {
7504
+ name: "base" | "files" | "browser" | "code-interpreter";
7505
+ /** Reserved: not read, because bases have no versions yet. Refused in this version. */
7506
+ range?: string;
7507
+ };
7508
+ /**
7509
+ * The tool VM's size, one of the base's size classes. Absent: 1 vCPU and 512 MiB, the only size of this version.
7510
+ */
7511
+ size?: {
7512
+ vcpu: number;
7513
+ memoryMb: number;
7514
+ };
7515
+ /**
7516
+ * Where the tool's files come from. This version reads one archive, unpacked at /tool before each call.
7517
+ */
7518
+ bundle?: {
7519
+ archive?: B3PackToolArchive;
7520
+ /**
7521
+ * Reserved: files carried inside the pack bundle under tool/, with their sources (later versions). Refused in this version.
7522
+ */
7523
+ files?: unknown[];
7524
+ };
7525
+ /**
7526
+ * call: one fresh VM per call, deleted before the call answers. session (later): a keyed instance kept between calls.
7527
+ */
7528
+ runtime?: {
7529
+ mode: "call" | "session";
7530
+ /** Reserved for session tools. */
7531
+ start?: unknown;
7532
+ /** Reserved for session tools. */
7533
+ ready?: unknown;
7534
+ /** Reserved for session tools. */
7535
+ idleS?: number;
7536
+ /** Reserved for session tools. */
7537
+ maxS?: number;
7538
+ };
7539
+ /**
7540
+ * What the tool's VM may reach. none: nothing (egress deny); the pack's egress list is empty. hosts (later): the pack's egress list, port 443 only. caller (later, first-party only): hosts the caller names.
7541
+ */
7542
+ network?: {
7543
+ mode: "none" | "hosts" | "caller";
7544
+ };
7545
+ /** The software the tool runs and did not write. Stored and returned by describe. */
7546
+ upstream?: {
7547
+ name: string;
7548
+ url: string;
7549
+ version: string;
7550
+ /** SPDX license expression. */
7551
+ license: string;
7552
+ /** Where the publisher got the upstream's files, and their digest. */
7553
+ obtained?: {
7554
+ url: string;
7555
+ sha256?: string;
7556
+ };
7557
+ patchedBy?: string;
7558
+ trademarkPolicy?: string;
7559
+ }[];
7560
+ /**
7561
+ * Bundle-relative path of the notices file (licences, attributions, 'Not affiliated with ...'). It must be a file of the pack bundle.
7562
+ */
7563
+ notices?: string;
7564
+ /**
7565
+ * Reserved: a command run once when the node prepares the tool's snapshot (later). Refused in this version.
7566
+ */
7567
+ setup?: unknown;
7568
+ /** Reserved: an imported image's artifact (later). Refused in this version. */
7569
+ image?: unknown;
7570
+ /** Reserved: output formats a takedown can turn off by name (later). Refused in this version. */
7571
+ formats?: unknown;
7572
+ /**
7573
+ * The error codes the tool answers with ({"error": {"code": ...}}), so the publisher's health view counts each one. A code the list does not name still reaches the caller as tool_code, and the health view counts it as undeclared.
7574
+ */
7575
+ errors?: string[];
7576
+ }
7577
+
7578
+ /**
7579
+ * One archive of the tool's files, named by its sha256, uploaded to the registry's blob store before the pack is published, and unpacked at /tool before each call. The publish checks cap it at 64 MiB packed (bytes 67108864), 512 MiB unpacked (unpackedBytes 536870912) and 20,000 entries.
7580
+ */
7581
+ export interface B3PackToolArchive {
7582
+ /** Lowercase hex sha256 of the archive's bytes. */
7583
+ sha256: string;
7584
+ /** The archive's size in bytes. */
7585
+ bytes: number;
7586
+ format: "tar.gz" | "tar";
7587
+ /** The sum of the sizes of the archive's regular files. */
7588
+ unpackedBytes: number;
7589
+ /** Files, directories and links in the archive. */
7590
+ entries: number;
7591
+ }
7592
+
5274
7593
  /**
5275
7594
  * Publisher signature written by the publish tool and repeated in the registry record. contentHash covers the whole bundle with this member removed (README, 'Pack content hash and signature'). sig is Ed25519 over the UTF-8 bytes of 'b3pack-sig-v1\n<pack>\n<version>\n<contentHash>'. Nodes verify contentHash and sig against the registry record and the publisher's registered key before loading (ARCHITECTURE 5.5).
5276
7595
  */
@@ -5358,6 +7677,10 @@ export interface ActionSummary {
5358
7677
  score?: number;
5359
7678
  /** Set in search results when the search asked for `kind=any`. */
5360
7679
  kind?: "action";
7680
+ /**
7681
+ * In a pack (`GET /v1/actions/packs/{namespace}/{name}`), for a hosted tool's action; absent in search results and for other actions.
7682
+ */
7683
+ tool?: ActionTool;
5361
7684
  }
5362
7685
 
5363
7686
  /** A trigger in search results (`kind=trigger` or `kind=any`). */
@@ -5457,6 +7780,7 @@ export interface ActionDescription {
5457
7780
  * when the node loads the pack. Their inputs also appear as `examples` in `mcp.inputSchema`.
5458
7781
  */
5459
7782
  examples: ActionExample[];
7783
+ tool?: ActionTool;
5460
7784
  }
5461
7785
 
5462
7786
  export interface ActionCallRequest {
@@ -5479,13 +7803,111 @@ export interface ActionResult {
5479
7803
  object: "action_result";
5480
7804
  /** The exact version that ran. */
5481
7805
  ref: string;
5482
- /** Matches the action's output schema. */
7806
+ /** Matches the action's output schema. A hosted tool's output file is a `ToolFileOutput`, a link. */
5483
7807
  output: unknown;
5484
7808
  /** HTTP status of the upstream call, for declarative HTTP actions. */
5485
7809
  upstream_status?: number;
7810
+ /**
7811
+ * `vm` for a hosted tool's call (its command ran in a microVM made for the call). Absent for other actions.
7812
+ */
7813
+ tier?: "vm";
7814
+ cost?: ToolCallCost;
5486
7815
  timing: Timing;
5487
7816
  }
5488
7817
 
7818
+ /**
7819
+ * What a hosted tool's call costs, in micro-USD (millionths of a US dollar), from the node's unit prices when
7820
+ * the call ran: `compute` (`actions.vcpu_ms` and `actions.gib_ms`), `floor` (`actions.tool_call`), `price` (the
7821
+ * publisher's, `actions.publisher_microusd`; 0 when the tool failed or is free) and their sum, `total`. The
7822
+ * same numbers are in the `actions.tool_call` usage record's `meta.cost_micro_usd`.
7823
+ */
7824
+ export interface ToolCallCost {
7825
+ compute: number;
7826
+ floor: number;
7827
+ price: number;
7828
+ total: number;
7829
+ }
7830
+
7831
+ /** A file name, without directories. */
7832
+ export type ToolFileName = string;
7833
+
7834
+ /**
7835
+ * A hosted tool's file in the node's file store: an upload, a fetched `$url` or an output file. It is kept
7836
+ * 1 hour from when it was written (`expires_at`), counts toward `actions.files_bytes` until then, and is
7837
+ * readable only from its project. `link` is a fresh signed download link that expires at the earlier of
7838
+ * `expires_at` and 1 hour from now.
7839
+ */
7840
+ export interface ToolFile {
7841
+ object: "tool_file";
7842
+ id: string;
7843
+ name: ToolFileName;
7844
+ bytes: number;
7845
+ sha256: string;
7846
+ /** From the name's extension (`.pdf` is `application/pdf`), else `application/octet-stream`. */
7847
+ content_type: string;
7848
+ created_at: string;
7849
+ expires_at: string;
7850
+ /** The signed download link, as `ToolFileOutput.$link`. */
7851
+ link: string;
7852
+ }
7853
+
7854
+ /**
7855
+ * A hosted tool action's publisher price, from its manifest (`pricing`, b3pack publish check 20). `micro_usd`
7856
+ * is the rate in micro-USD (millionths of a US dollar): per call, per second of the tool's own run, or per MiB
7857
+ * of input; 0 when free. `free_calls` is the calls each calling organization makes free of the price per UTC
7858
+ * month, for the pack.
7859
+ */
7860
+ export interface ToolPrice {
7861
+ model: "free" | "per_call" | "per_second" | "per_input_mb";
7862
+ micro_usd: number;
7863
+ free_calls: number;
7864
+ }
7865
+
7866
+ /**
7867
+ * What one call of this action costs all in, in micro-USD, from this version's own last calls on this node
7868
+ * (at most the last 100): the price at the median call (the median `run_ms` or input size for a rate), the
7869
+ * median compute, and the floor, at the node's unit prices now. `basis` says what it was taken from.
7870
+ */
7871
+ export interface ToolAllIn {
7872
+ /** `compute` + `floor` + `price`. */
7873
+ micro_usd: number;
7874
+ compute: number;
7875
+ floor: number;
7876
+ price: number;
7877
+ basis: string;
7878
+ }
7879
+
7880
+ /**
7881
+ * For a hosted tool's action (`impl.kind` `vm`), what it runs on, what it may take and return, and what it costs; absent for other actions.
7882
+ */
7883
+ export interface ActionTool {
7884
+ kind: "cli";
7885
+ /** The template its VM is made from. */
7886
+ base: string;
7887
+ network: "none";
7888
+ price: ToolPrice;
7889
+ /** `execution.maxInputMb`: the most input file data one call may carry, in MiB. */
7890
+ max_input_mb: number;
7891
+ /** `execution.maxOutputMb`: the most output file data one call may return, in MiB. */
7892
+ max_output_mb: number;
7893
+ /** `execution.maxOutputFiles`: the most output files one call may return. */
7894
+ max_output_files: number;
7895
+ /** The tool's declared error codes (`tool.errors`); empty when it declares none. */
7896
+ errors: string[];
7897
+ /** The software the tool runs and did not write (the manifest's `tool.upstream`). */
7898
+ upstream: Record<string, unknown>[];
7899
+ /** The bundle path of the tool's notices file. */
7900
+ notices?: string;
7901
+ /**
7902
+ * The node's estimate of the time from claim to the tool's command starting, in milliseconds, for this
7903
+ * version's archive: a warm-pool claim plus the copy and the unpack for its size and format, from the
7904
+ * table measured on 2026-11-13 (warm pool, 1 vCPU and 512 MiB).
7905
+ */
7906
+ start_estimate_ms: number;
7907
+ /** What one call costs all in, or `null` before this version's first call on this node. */
7908
+ all_in: ToolAllIn | null;
7909
+ }
7910
+
5489
7911
  export interface TriggerSummary {
5490
7912
  ref: string;
5491
7913
  pack: string;
@@ -5657,7 +8079,10 @@ export interface ConnectionCreateRequest {
5657
8079
  * connection. Without `pack`, list the hosts your own HTTP steps call, or omit it (or give `[]`) for a
5658
8080
  * verification-only connection: a connection with no hosts is never injected anywhere, because egress
5659
8081
  * injection matches on hosts. It only holds a secret B3OS itself uses, such as a routine webhook's
5660
- * `verify.secret`.
8082
+ * `verify.secret`. A `basic` connection may also list public IP addresses (IPv4, or IPv6 with or without
8083
+ * brackets, kept in canonical form), such as a proxy given by its address; a private, loopback,
8084
+ * link-local, CGNAT, multicast or metadata address is refused with `422 connection_invalid`, and no other
8085
+ * type lists an IP address.
5661
8086
  */
5662
8087
  hosts?: string[];
5663
8088
  /** Non-secret configuration the pack's connection declares (for example a Jira site name). */
@@ -5669,7 +8094,10 @@ export interface ConnectionCreateRequest {
5669
8094
  export interface ConnectionUpdateRequest {
5670
8095
  label?: string;
5671
8096
  subject?: string | null;
5672
- /** Connections without a pack only. `[]` makes the connection verification-only (never injected). */
8097
+ /**
8098
+ * Connections without a pack only. `[]` makes the connection verification-only (never injected). The same
8099
+ * rules as on create: a `basic` connection may list public IP addresses, no other type any.
8100
+ */
5673
8101
  hosts?: string[];
5674
8102
  params?: Record<string, unknown>;
5675
8103
  secret?: ConnectionSecret;
@@ -5924,6 +8352,14 @@ export interface InferMeta {
5924
8352
  model_ms?: number;
5925
8353
  total_ms?: number;
5926
8354
  };
8355
+ /**
8356
+ * What `platform.capture_content` (prompt logging) applied to this call and where it came from (`request`, `project`, `org`, `node`); `clamped` when a stored value could not apply and `off` did instead. `model`: the call's prompt and answer are kept for 7 days (`GET /v1/llm-calls/{request_id}/content`). Also in the `X-B3OS-Options` response header.
8357
+ */
8358
+ capture?: {
8359
+ value: "off" | "model";
8360
+ from: "request" | "project" | "org" | "node";
8361
+ clamped: boolean;
8362
+ };
5927
8363
  }
5928
8364
 
5929
8365
  export interface ChatCompletion {
@@ -5986,7 +8422,10 @@ export interface ModelInfo {
5986
8422
  * On `b3os/default` only: the chat model it names, whose limits apply. A request for the alias is served, limited and metered as that model, and its response names that model.
5987
8423
  */
5988
8424
  alias_of?: string;
5989
- kind: "chat" | "embedding" | "speech";
8425
+ kind: "chat" | "embedding" | "rerank" | "speech";
8426
+ /**
8427
+ * Tokens per request on chat models; on embedding models, tokens per input; on rerank models, tokens per query and document pair.
8428
+ */
5990
8429
  context_length: number | null;
5991
8430
  /**
5992
8431
  * The output cap of a chat request that sets no `max_tokens` (or `max_completion_tokens`, or Responses'
@@ -6000,6 +8439,12 @@ export interface ModelInfo {
6000
8439
  json_schema: boolean;
6001
8440
  image_input: boolean;
6002
8441
  max_request_bytes: number;
8442
+ /** Embedding models only. Values per vector, and the most `dimensions` takes. */
8443
+ dimensions?: number;
8444
+ /**
8445
+ * Embedding models only. The fewest values `dimensions` takes; the same as `dimensions` when the model offers no shorter vectors.
8446
+ */
8447
+ min_dimensions?: number;
6003
8448
  limits: {
6004
8449
  /**
6005
8450
  * Tokens per minute for your organization (its own value from the node's budget snapshot, else the node's default).
@@ -6024,12 +8469,28 @@ export interface ModelList {
6024
8469
  }
6025
8470
 
6026
8471
  export interface EmbeddingRequest {
8472
+ /** An embedding model's ID from `GET /v1/infer/models`. */
6027
8473
  model: string;
6028
- input: string | string[] | number[] | number[][];
8474
+ /** The text to embed. Arrays of token IDs are `400 unsupported_parameter`. */
8475
+ input: string | string[];
6029
8476
  /** @default "float" */
6030
8477
  encoding_format?: "float" | "base64";
8478
+ /** Values per vector, from the model's `b3os.min_dimensions` to its `b3os.dimensions`. */
6031
8479
  dimensions?: number;
8480
+ /** Accepted and ignored. */
6032
8481
  user?: string;
8482
+ /**
8483
+ * B3OS extension. `query` puts the model's query prompt before each input.
8484
+ * @default "document"
8485
+ */
8486
+ input_type?: "document" | "query";
8487
+ /** B3OS extension. The task the query prompt describes; only with `input_type` `query`. */
8488
+ instruction?: string;
8489
+ /**
8490
+ * B3OS extension. `end` cuts an input longer than the model's `context_length` at the end; `none` refuses it.
8491
+ * @default "none"
8492
+ */
8493
+ truncate?: "none" | "end";
6033
8494
  }
6034
8495
 
6035
8496
  export interface EmbeddingList {
@@ -6044,6 +8505,78 @@ export interface EmbeddingList {
6044
8505
  prompt_tokens: number;
6045
8506
  total_tokens: number;
6046
8507
  };
8508
+ b3os?: EmbeddingMeta;
8509
+ }
8510
+
8511
+ /** B3OS extension; OpenAI SDKs ignore it. */
8512
+ export interface EmbeddingMeta {
8513
+ route: "local";
8514
+ node: string;
8515
+ /** Values per vector. */
8516
+ dimensions: number;
8517
+ /** Every vector has length 1. */
8518
+ normalized: true;
8519
+ /** Server-side milliseconds from the request head. */
8520
+ timing: {
8521
+ model_ms?: number;
8522
+ total_ms?: number;
8523
+ };
8524
+ }
8525
+
8526
+ export interface RerankRequest {
8527
+ /** A rerank model's ID from `GET /v1/infer/models`. */
8528
+ model: string;
8529
+ /** At most 2,048 tokens. */
8530
+ query: string;
8531
+ documents: Array<
8532
+ | string
8533
+ | {
8534
+ text: string;
8535
+ }
8536
+ >;
8537
+ /** How many results to return; default every document. */
8538
+ top_n?: number;
8539
+ /**
8540
+ * Each document is cut at the end to this many tokens.
8541
+ * @default 4096
8542
+ */
8543
+ max_tokens_per_doc?: number;
8544
+ /**
8545
+ * B3OS extension. Each result also carries its document.
8546
+ * @default false
8547
+ */
8548
+ return_documents?: boolean;
8549
+ /** B3OS extension. The task the model's query prompt describes. */
8550
+ instruction?: string;
8551
+ }
8552
+
8553
+ export interface RerankList {
8554
+ /** The request ID. */
8555
+ id: string;
8556
+ model: string;
8557
+ /** Highest `relevance_score` first. */
8558
+ results: {
8559
+ /** The document's position in `documents`. */
8560
+ index: number;
8561
+ relevance_score: number;
8562
+ /** With `return_documents: true`: the document as sent. */
8563
+ document?: {
8564
+ text: string;
8565
+ };
8566
+ }[];
8567
+ usage: {
8568
+ total_tokens: number;
8569
+ };
8570
+ /** Cohere's metadata. */
8571
+ meta: {
8572
+ api_version: {
8573
+ version: "2";
8574
+ };
8575
+ billed_units: {
8576
+ input_tokens: number;
8577
+ };
8578
+ };
8579
+ b3os?: InferMeta;
6047
8580
  }
6048
8581
 
6049
8582
  /** OpenAI speech parameters; `null` means unset on the optional ones. */
@@ -6746,12 +9279,158 @@ export interface RegistryPackVersion {
6746
9279
  alg: "ed25519";
6747
9280
  kid: string;
6748
9281
  sig: string;
9282
+ /**
9283
+ * An org-private version only: the organization's public key for `kid` (`org.<org>#g<generation>`),
9284
+ * base64url without padding of its 32 bytes. A node verifies `sig` with it only for a pack in that same
9285
+ * `org.` namespace, for that organization; a listed pack never verifies with a record's key.
9286
+ */
9287
+ public_key?: string;
6749
9288
  };
6750
9289
  publisher: RegistryPublisher;
6751
9290
  size_bytes: number;
6752
9291
  published_at: string;
9292
+ /** A yanked version resolves only when pinned exactly (`@1.2.0`); a range or major (`@1`) skips it. */
6753
9293
  yanked: boolean;
9294
+ /**
9295
+ * A dev version (`<x.y.z>-dev.<unix seconds>`, org-private tools only), replaced by the pack's next dev version and outside the version limits. Nodes deployed before slice B do not send it.
9296
+ */
9297
+ dev?: boolean;
6754
9298
  download_url: string;
9299
+ /**
9300
+ * The API key (`key_...`) or dashboard user (`usr_...`) that published the version, shown to the namespace's owner and to B3's organizations; `null` for any other reader, a node, and versions published before it was recorded.
9301
+ */
9302
+ published_by?: string | null;
9303
+ }
9304
+
9305
+ /** A hosted tool's archive in the registry's blob store, named by its sha256. */
9306
+ export interface RegistryBlob {
9307
+ object: "registry_blob";
9308
+ digest: string;
9309
+ bytes: number;
9310
+ created_at: string;
9311
+ }
9312
+
9313
+ export interface RegistryYankRequest {
9314
+ /** `true` yanks the version, `false` restores it. */
9315
+ yanked: boolean;
9316
+ }
9317
+
9318
+ /**
9319
+ * What to block. `publisher` is a namespace; `pack` (`<namespace>/<name>`, in `publisher`) is required for the
9320
+ * scopes `pack`, `version` and `action`; `version` (exact) for `version`, and optionally for `action` (absent:
9321
+ * the action in every version); `action` (an action key) for `action`.
9322
+ */
9323
+ export interface ToolBlockCreateRequest {
9324
+ scope: "publisher" | "pack" | "version" | "action";
9325
+ publisher: string;
9326
+ pack?: string;
9327
+ version?: string;
9328
+ action?: string;
9329
+ /** Why, for B3's own records. Never sent to nodes or shown to the publisher. */
9330
+ reason: string;
9331
+ /**
9332
+ * Who asked, for B3's own records (a ticket, a notice). Never sent to nodes or shown to the publisher.
9333
+ */
9334
+ requested_by: string;
9335
+ /** The sha256 of the evidence B3 keeps elsewhere. */
9336
+ evidence_sha256?: string;
9337
+ }
9338
+
9339
+ export interface ToolBlockLift {
9340
+ lifted_at: string;
9341
+ /** An `io.b3os` key id (`io.b3os#<label>`). */
9342
+ kid: string;
9343
+ sig: string;
9344
+ }
9345
+
9346
+ /**
9347
+ * A block that removes a hosted tool, its version, one action, or every tool of a publisher. `lift` is `null` while it is in force.
9348
+ */
9349
+ export interface ToolBlock {
9350
+ object: "tool_block";
9351
+ id: string;
9352
+ scope: "publisher" | "pack" | "version" | "action";
9353
+ publisher: string;
9354
+ pack: string | null;
9355
+ version: string | null;
9356
+ action: string | null;
9357
+ reason: string;
9358
+ requested_by: string;
9359
+ evidence_sha256: string | null;
9360
+ created_at: string;
9361
+ /** The API key (`key_...`) or dashboard user (`usr_...`) that placed the block. */
9362
+ created_by: string;
9363
+ lift: ToolBlockLift | null;
9364
+ }
9365
+
9366
+ export type ToolBlockList = Omit<ListEnvelope, "data"> & {
9367
+ data: ToolBlock[];
9368
+ };
9369
+
9370
+ /** An option's value; for an enum option, one of its values (`x-b3os-options`). */
9371
+ export type SettingValue = string | number | boolean;
9372
+
9373
+ export interface SettingRequest {
9374
+ value: SettingValue;
9375
+ }
9376
+
9377
+ /** One option set for one project or organization. */
9378
+ export interface StoredSetting {
9379
+ /** The option id. */
9380
+ id: string;
9381
+ object: "setting";
9382
+ value: SettingValue;
9383
+ scope: "project" | "org";
9384
+ /** The project (`prj_`) or organization (`org_`) it is set for. */
9385
+ scope_id: string;
9386
+ updated_at: string;
9387
+ /** The user (`usr_`) or key (`key_`) that last set it. */
9388
+ updated_by: string;
9389
+ }
9390
+
9391
+ export type StoredSettingList = Omit<ListEnvelope, "data"> & {
9392
+ data: StoredSetting[];
9393
+ };
9394
+
9395
+ /**
9396
+ * `isolated`: the app's server gets only the cookies its own address set, plus the names in `script`.
9397
+ * `shared`: the browser's cookies pass, except Cloudflare's and B3OS's own names and values that are not plain
9398
+ * (a space, comma, quote or backslash).
9399
+ */
9400
+ export type AppHostCookieMode = "isolated" | "shared";
9401
+
9402
+ export interface AppHostCookies {
9403
+ mode: AppHostCookieMode;
9404
+ /** Cookies a page script writes and the app's server reads, by name. */
9405
+ script: string[];
9406
+ }
9407
+
9408
+ export interface PortHostRequest {
9409
+ /**
9410
+ * How long the link works, in seconds.
9411
+ * @default 600
9412
+ */
9413
+ ttl_s?: number;
9414
+ /**
9415
+ * Replace the host's secret first: every earlier link and cookie of this host stops working within 6 seconds (streams already open can run up to an hour).
9416
+ * @default false
9417
+ */
9418
+ rotate?: boolean;
9419
+ cookies?: AppHostCookies;
9420
+ }
9421
+
9422
+ export interface PortHost {
9423
+ object: "port_host";
9424
+ sandbox_id: string;
9425
+ port: number;
9426
+ /** `<port>-sbx-<id>.b3os.io`: the host, safe to show. */
9427
+ host: string;
9428
+ /** `https://<host>/?b3os_link=<token>`. Share it as a secret. */
9429
+ url: string;
9430
+ /** When the link stops working (a browser that opened it stays in for 24 hours from its visit). */
9431
+ expires_at: string;
9432
+ rotated: boolean;
9433
+ cookies: AppHostCookies;
6755
9434
  }
6756
9435
 
6757
9436
  /**
@@ -6765,10 +9444,21 @@ export type RequestConnection = "edge" | "uds" | "tcp" | "sandbox";
6765
9444
  * Who made the request: `api_key` (an API key), `cli_token` (the CLI's device-login token), `dashboard` (a
6766
9445
  * signed-in dashboard session; its successful reads are not logged, its changes and errors are), `sandbox` (code
6767
9446
  * inside a sandbox, as its creating key), `routine` (a routine run, as the key that published its version),
6768
- * `local` (a host-local caller on the node's Unix socket) or `public` (no credential: a webhook or signed
6769
- * callback to a public route, or a request refused before authentication).
9447
+ * `local` (a host-local caller on the node's Unix socket), `public` (no credential: a webhook or signed
9448
+ * callback to a public route, or a request refused before authentication), `address` (a visitor of an app
9449
+ * address, `<label>.b3os.io`) or `preview` (a visitor of a sandbox port preview). `address` and `preview`
9450
+ * records belong to the sandbox's project; their `path` is the app's path, without the query, cut at 1,024 bytes.
6770
9451
  */
6771
- export type RequestSource = "api_key" | "cli_token" | "dashboard" | "sandbox" | "routine" | "local" | "public";
9452
+ export type RequestSource =
9453
+ | "api_key"
9454
+ | "cli_token"
9455
+ | "dashboard"
9456
+ | "sandbox"
9457
+ | "routine"
9458
+ | "local"
9459
+ | "public"
9460
+ | "address"
9461
+ | "preview";
6772
9462
 
6773
9463
  export interface RequestPhase {
6774
9464
  name: string;
@@ -6815,8 +9505,30 @@ export interface RequestRecord {
6815
9505
  trace_id: string | null;
6816
9506
  user_agent: string | null;
6817
9507
  source: RequestSource;
9508
+ action?: RequestAction;
6818
9509
  }
6819
9510
 
9511
+ /**
9512
+ * The pack action the request ran: a `POST /v1/actions/call`, or one `tools/call` of a sandbox's MCP server
9513
+ * (`POST /v1/actions/mcp`, with `tool` set). `null` for any other request, and absent from records written
9514
+ * before node release 1118. A tool call answers HTTP 200 whether or not the action succeeded, so its own outcome
9515
+ * is here: `status_code` 200, or the status of the problem that refused or failed it. For a product tool (node
9516
+ * release 1119: `browser_*`, `vision_*`, `render_*`), `pack` is the toolset (`browser`, `vision` or `render`)
9517
+ * and `ref` is `<product>/<operationId>` of the product request the tool made (`vision/visionAct`), which has a
9518
+ * record of its own on the sandbox's connection, with the same `trace_id` when the call sent a `traceparent`.
9519
+ */
9520
+ export type RequestAction = {
9521
+ /**
9522
+ * `<namespace>/<name>/<action>@<version>`: the exact version that ran, or the ref as asked when the call was refused before it resolved one; `<product>/<operationId>` for a product tool.
9523
+ */
9524
+ ref: string;
9525
+ pack: string;
9526
+ /** The MCP tool name, for a `tools/call`; `null` for `POST /v1/actions/call`. */
9527
+ tool: string | null;
9528
+ status_code: number;
9529
+ error_code: string | null;
9530
+ } | null;
9531
+
6820
9532
  export type RequestRecordList = Omit<ListEnvelope, "data"> & {
6821
9533
  data: RequestRecord[];
6822
9534
  };
@@ -7208,6 +9920,17 @@ export interface VisionListSessionsParams {
7208
9920
  status?: SessionStatus;
7209
9921
  }
7210
9922
 
9923
+ /** Parameters of `listAliases`. */
9924
+ export interface RenderListAliasesParams {
9925
+ /**
9926
+ * Page size, from 1 to 100.
9927
+ * @default 20
9928
+ */
9929
+ limit?: number;
9930
+ /** Opaque cursor from the previous page's `next_cursor`. Omit it for the first page. */
9931
+ cursor?: string;
9932
+ }
9933
+
7211
9934
  /** Parameters of `listBackgrounds`. */
7212
9935
  export interface RenderListBackgroundsParams {
7213
9936
  /** Only this pack's backgrounds (`GET /v1/render/backgrounds/packs` lists the packs). */
@@ -7287,6 +10010,15 @@ export interface SandboxesListSandboxesParams {
7287
10010
  cursor?: string;
7288
10011
  /** Only sandboxes with this status. */
7289
10012
  status?: SandboxStatus;
10013
+ /** Only sandboxes with this `owner` (`project`, the services of applications, or `key`). */
10014
+ owner?: SandboxOwner;
10015
+ /** Only the sandboxes this project's service started, directly or not (`root`). */
10016
+ root?: string;
10017
+ /**
10018
+ * Only sandboxes this key created (`created_by_key`). With `owner=project`: the services a key deployed,
10019
+ * which keep running after it is revoked.
10020
+ */
10021
+ created_by_key?: string;
7290
10022
  /**
7291
10023
  * Only sandboxes whose `metadata` holds each of these pairs, as `metadata[<key>]=<value>`: up to 4, all of
7292
10024
  * which must match exactly. Keys follow the `metadata` key rule (1 to 40 of `A-Z a-z 0-9 _ . : -`).
@@ -7305,6 +10037,58 @@ export interface SandboxesListSnapshotsParams {
7305
10037
  cursor?: string;
7306
10038
  }
7307
10039
 
10040
+ /** Parameters of `listSwarms`. */
10041
+ export interface SandboxesListSwarmsParams {
10042
+ /**
10043
+ * Page size, from 1 to 100.
10044
+ * @default 20
10045
+ */
10046
+ limit?: number;
10047
+ /** Opaque cursor from the previous page's `next_cursor`. Omit it for the first page. */
10048
+ cursor?: string;
10049
+ /** Only swarms with this status. */
10050
+ status?: JobStatus;
10051
+ }
10052
+
10053
+ /** Parameters of `getSwarm`. */
10054
+ export interface SandboxesGetSwarmParams {
10055
+ /**
10056
+ * Seconds to wait for the job to finish before responding, from 0 to 60. If it finishes in time the response
10057
+ * is `200` with the finished job; otherwise `202` with the job as it is, a `Location` to poll and
10058
+ * `Retry-After`. `0` (the default) returns immediately.
10059
+ * @default 0
10060
+ */
10061
+ wait?: number;
10062
+ }
10063
+
10064
+ /** Parameters of `listSwarmChildren`. */
10065
+ export interface SandboxesListSwarmChildrenParams {
10066
+ /**
10067
+ * Page size, from 1 to 100.
10068
+ * @default 20
10069
+ */
10070
+ limit?: number;
10071
+ /** Opaque cursor from the previous page's `next_cursor`. Omit it for the first page. */
10072
+ cursor?: string;
10073
+ /** Only children with this status. */
10074
+ status?: "queued" | "running" | "exited" | "timed_out" | "failed" | "canceled";
10075
+ }
10076
+
10077
+ /** Parameters of `listVolumes`. */
10078
+ export interface SandboxesListVolumesParams {
10079
+ /**
10080
+ * Page size, from 1 to 100.
10081
+ * @default 20
10082
+ */
10083
+ limit?: number;
10084
+ /** Opaque cursor from the previous page's `next_cursor`. Omit it for the first page. */
10085
+ cursor?: string;
10086
+ /** Only the volume with this name. */
10087
+ name?: string;
10088
+ /** Only volumes in this status. */
10089
+ status?: "available" | "attached" | "deleted";
10090
+ }
10091
+
7308
10092
  /** Parameters of `deleteFile`. */
7309
10093
  export interface SandboxesDeleteFileParams {
7310
10094
  /** Absolute path inside the sandbox. */
@@ -7392,6 +10176,71 @@ export interface SandboxesListRequestsParams {
7392
10176
  /** Only requests of this W3C trace (the trace id of their `traceparent`). */
7393
10177
  trace_id?: string;
7394
10178
  since?: string;
10179
+ /**
10180
+ * Only requests that ran an action of this pack (their `action.pack`), or a tool of this product toolset of a sandbox's MCP server (`browser`, `vision` or `render`, node release 1119).
10181
+ */
10182
+ pack?: string;
10183
+ }
10184
+
10185
+ /** Parameters of `getImage`. */
10186
+ export interface ImagesGetImageParams {
10187
+ /**
10188
+ * Hold the answer up to this many seconds until the image is `ready`, `failed` or `evicted`.
10189
+ * @default 0
10190
+ */
10191
+ wait?: number;
10192
+ }
10193
+
10194
+ /** Parameters of `listAgents`. */
10195
+ export interface AgentsListAgentsParams {
10196
+ /**
10197
+ * Page size, from 1 to 100.
10198
+ * @default 20
10199
+ */
10200
+ limit?: number;
10201
+ /** Opaque cursor from the previous page's `next_cursor`. Omit it for the first page. */
10202
+ cursor?: string;
10203
+ }
10204
+
10205
+ /** Parameters of `listInstances`. */
10206
+ export interface AgentsListInstancesParams {
10207
+ /**
10208
+ * Page size, from 1 to 100.
10209
+ * @default 20
10210
+ */
10211
+ limit?: number;
10212
+ /** Opaque cursor from the previous page's `next_cursor`. Omit it for the first page. */
10213
+ cursor?: string;
10214
+ /** Only instances with this status. */
10215
+ status?: AgentInstanceStatus;
10216
+ }
10217
+
10218
+ /** Parameters of `listInstanceEvents`. */
10219
+ export interface AgentsListInstanceEventsParams {
10220
+ /**
10221
+ * Page size, from 1 to 100.
10222
+ * @default 20
10223
+ */
10224
+ limit?: number;
10225
+ /** Opaque cursor from the previous page's `next_cursor`. Omit it for the first page. */
10226
+ cursor?: string;
10227
+ }
10228
+
10229
+ /** Parameters of `listSessions`. */
10230
+ export interface AgentsListSessionsParams {
10231
+ /**
10232
+ * Page size, from 1 to 100.
10233
+ * @default 20
10234
+ */
10235
+ limit?: number;
10236
+ /** Opaque cursor from the previous page's `next_cursor`. Omit it for the first page. */
10237
+ cursor?: string;
10238
+ /** Only sessions of this instance. */
10239
+ key?: AgentInstanceKey;
10240
+ /** Only sessions of this conversation. */
10241
+ conversation?: string;
10242
+ /** Only sessions with this status. */
10243
+ status?: JobStatus;
7395
10244
  }
7396
10245
 
7397
10246
  /** Parameters of `listRoutines`. */
@@ -7457,12 +10306,44 @@ export interface RoutinesListVersionsParams {
7457
10306
  cursor?: string;
7458
10307
  }
7459
10308
 
10309
+ /** Parameters of `listListeners`. */
10310
+ export interface ListenersListListenersParams {
10311
+ /**
10312
+ * Page size, from 1 to 100.
10313
+ * @default 20
10314
+ */
10315
+ limit?: number;
10316
+ /** Opaque cursor from the previous page's `next_cursor`. Omit it for the first page. */
10317
+ cursor?: string;
10318
+ /** Only listeners in this status. */
10319
+ status?: ListenerStatus;
10320
+ }
10321
+
10322
+ /** Parameters of `listEvents`. */
10323
+ export interface ListenersListEventsParams {
10324
+ /**
10325
+ * Page size, from 1 to 100.
10326
+ * @default 20
10327
+ */
10328
+ limit?: number;
10329
+ /** Opaque cursor from the previous page's `next_cursor`. Omit it for the first page. */
10330
+ cursor?: string;
10331
+ /** Only events in this status. */
10332
+ status?: ListenerEventStatus;
10333
+ }
10334
+
7460
10335
  /** Parameters of `describe`. */
7461
10336
  export interface ActionsDescribeParams {
7462
10337
  /** `<namespace>/<name>/<action>@<version>`; the version may be exact (`1.0.0`) or a major (`1`). */
7463
10338
  ref: ActionRef;
7464
10339
  }
7465
10340
 
10341
+ /** Parameters of `uploadFile`. */
10342
+ export interface ActionsUploadFileParams {
10343
+ /** The file's name, which the tool sees at `/in/<field>/<name>`. */
10344
+ name: ToolFileName;
10345
+ }
10346
+
7466
10347
  /** Parameters of `listPacks`. */
7467
10348
  export interface ActionsListPacksParams {
7468
10349
  /** Words to search for in pack titles and descriptions. */
@@ -7494,6 +10375,17 @@ export interface ActionsGetPackToolsParams {
7494
10375
  if_none_match?: string;
7495
10376
  }
7496
10377
 
10378
+ /** Parameters of `listToolBlocks`. */
10379
+ export interface PlatformListToolBlocksParams {
10380
+ /**
10381
+ * Page size, from 1 to 100.
10382
+ * @default 20
10383
+ */
10384
+ limit?: number;
10385
+ /** Opaque cursor from the previous page's `next_cursor`. Omit it for the first page. */
10386
+ cursor?: string;
10387
+ }
10388
+
7497
10389
  /** Parameters of `listRegistryPacks`. */
7498
10390
  export interface PlatformListRegistryPacksParams {
7499
10391
  /**
@@ -7579,6 +10471,42 @@ export interface InferListVoicesParams {
7579
10471
  model?: string;
7580
10472
  }
7581
10473
 
10474
+ /** Parameters of `createChatCompletion` (header parameters are sent as their `X-B3OS-*` headers). */
10475
+ export interface InferCreateChatCompletionParams {
10476
+ /**
10477
+ * `off` keeps nothing of this call in the model call log, whatever the project's `platform.capture_content` setting. The only value: a request can turn prompt logging off, never on. Any other value is `400 invalid_request`.
10478
+ */
10479
+ capture_content?: "off";
10480
+ /**
10481
+ * The request id of a kept model call this call replays (the console's Replay). When this call is kept, its record names that call in `replay_of` if it is in the same project. Not capture mode's `x-b3os-replay`.
10482
+ */
10483
+ replay_of?: string;
10484
+ }
10485
+
10486
+ /** Parameters of `createResponse` (header parameters are sent as their `X-B3OS-*` headers). */
10487
+ export interface InferCreateResponseParams {
10488
+ /**
10489
+ * `off` keeps nothing of this call in the model call log, whatever the project's `platform.capture_content` setting. The only value: a request can turn prompt logging off, never on. Any other value is `400 invalid_request`.
10490
+ */
10491
+ capture_content?: "off";
10492
+ /**
10493
+ * The request id of a kept model call this call replays (the console's Replay). When this call is kept, its record names that call in `replay_of` if it is in the same project. Not capture mode's `x-b3os-replay`.
10494
+ */
10495
+ replay_of?: string;
10496
+ }
10497
+
10498
+ /** Parameters of `createMessage` (header parameters are sent as their `X-B3OS-*` headers). */
10499
+ export interface InferCreateMessageParams {
10500
+ /**
10501
+ * `off` keeps nothing of this call in the model call log, whatever the project's `platform.capture_content` setting. The only value: a request can turn prompt logging off, never on. Any other value is `400 invalid_request`.
10502
+ */
10503
+ capture_content?: "off";
10504
+ /**
10505
+ * The request id of a kept model call this call replays (the console's Replay). When this call is kept, its record names that call in `replay_of` if it is in the same project. Not capture mode's `x-b3os-replay`.
10506
+ */
10507
+ replay_of?: string;
10508
+ }
10509
+
7582
10510
  /** Parameters of `listKeys`. */
7583
10511
  export interface PlatformListKeysParams {
7584
10512
  /**
@@ -7622,6 +10550,10 @@ export interface PlatformListUsageRecordsParams {
7622
10550
  product?: string;
7623
10551
  unit?: string;
7624
10552
  key_id?: string;
10553
+ /**
10554
+ * The usage a sandbox's own API calls caused (an application's pack calls, say). Only the calling project's sandboxes; another project's sandbox lists no records.
10555
+ */
10556
+ sandbox_id?: string;
7625
10557
  request_id?: string;
7626
10558
  }
7627
10559
 
@@ -7652,6 +10584,10 @@ export interface PlatformListRequestsParams {
7652
10584
  */
7653
10585
  trace_id?: string;
7654
10586
  since?: string;
10587
+ /**
10588
+ * Only requests that ran an action of this pack (their `action.pack`), or a tool of this product toolset of a sandbox's MCP server (`browser`, `vision` or `render`, node release 1119).
10589
+ */
10590
+ pack?: string;
7655
10591
  }
7656
10592
 
7657
10593
  /** Parameters of `listDeliveries`. */