@colixsystems/widget-sdk 0.350.0 → 0.352.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -91,7 +91,21 @@ See the design reference for the full architecture: [`docs/architecture/widget-m
91
91
 
92
92
  ## Status
93
93
 
94
- `v0.350.0` — pre-publish. The package surface (types, function names, export paths) is the v1 contract; runtime behaviour for some hooks is stubbed (each hook documents what's wired and what isn't). It is **not yet published to npm**.
94
+ `v0.352.0` — pre-publish. The package surface (types, function names, export paths) is the v1 contract; runtime behaviour for some hooks is stubbed (each hook documents what's wired and what isn't). It is **not yet published to npm**.
95
+
96
+ ### What's new in 0.352.0 (contract 1.289.0)
97
+
98
+ **The server prices an order, so a buyer cannot lower what is charged.** Until now an order's total was whatever the buyer's own create wrote, so a shop that took prices from the browser could be paid any amount a buyer typed into a page address. The server now prices the order itself when its charge opens, from the shop's own price tables, and a payer who could write or create a price there is refused. Declare it in the `datastoreTemplate`: `unitPrice: true` on a products table's NUMBER price column (minor units), a lines table with a write-once relation to the orders table, a write-once `pricedItem: true` relation to the products table and an optional write-once NUMBER `lineQuantity: true` (1 to 999; empty is 1), and on the orders table `orderTotal: { lines: "<lines table suffix>", via: "<the lines table's relation to the orders>" }`. An orders table may also hold one `pricedItem` of its own, counted once (a shipping option), and an order without lines may be priced by that alone (`orderTotal: true`). Create the order, then its lines, then call `requestPayment({ description, kind, order })` (or `requestGuestPayment`) without `amount_cents`: the server sums quantity × unit price plus the order's own item, writes the total on the order and charges exactly that. Any total or price the widget writes or sends is ignored or refused, so a buyer cannot lower the charge by editing the total or the prices they send. A payer who could write or create a price (by a grant on a priced row or its table, write on a parent a new row could inherit from, or a priced row they created; a shop's own admin included) is refused with `ORDER_NOT_PAYABLE`, as is an order whose total is not priced by the server: publishing a `datastoreTemplate` with an unpriced `orderTotal` is refused (a template already published still installs). Once an order holds its total its lines are fixed: adding or removing one answers `409 ORDER_LOCKED`, and a retried charge charges the same total. New non-retryable `PaymentError` code `ORDER_LINES_INVALID`: no lines, a gone or unpriced product, a quantity outside 1–999, or more than 100 lines. Breaking for order charges on a table whose total the server does not price.
99
+
100
+ ### What's new in 0.351.0 (contract 1.288.0)
101
+
102
+ **An agent run lives on the server (`useAgent()`).** Leaving the page, a refresh or a lost connection no longer ends the turn.
103
+
104
+ - **`sending` covers a run found on mount.** The hook reads the thread until the run ends and its answer lands in `messages`, so a widget that gates its composer and Stop control on `sending` needs no change. It spends no credit. A lost connection is followed the same way: `send()` stays pending and resolves with the reply. A send that cannot reach the server again within a minute rejects with its first error.
105
+ - **`cancel()` really stops the run.** `send()` then **resolves** with the stopped row (it used to reject `CANCELLED`). What the agent already changed stays changed. If the stop fails, `error` is set and `sending` stays true. On a host that cannot stop a run, `cancel()` still only ends the wait.
106
+ - **`outcome`** — an assistant message that ended early carries `"stopped"` or `"failed"` with the content `…`. Render its `activity` and a line of your own, not a bubble.
107
+ - **`TURN_IN_PROGRESS`** (409) — the agent is still working on an earlier message, perhaps from another device. Nothing was sent: put the text back.
108
+ - **`AgentError.stored`** — true when the turn failed but the server kept the message. It is in `messages`, so do not put the text back in the composer.
95
109
 
96
110
  ### What's new in 0.350.0 (contract 1.287.0)
97
111
 
@@ -2151,7 +2165,7 @@ Additive: `isNarrowWidth` and `NARROW_WIDTH_PX` are unchanged, and `widthTier(w)
2151
2165
 
2152
2166
  **`useAgent()` returns `cancel()` — and two error codes that tell the truth about a slow turn (sc-8519).** A turn can legitimately run for minutes; the client used to give up after 10 seconds and report it as `NETWORK`, so a widget showed "you appear to be offline" to a user whose connection was fine, while the server finished the turn and the workspace paid for a reply nobody saw.
2153
2167
 
2154
- - **`cancel()`** stops WAITING for the turn in flight. The abort never reaches the server, which finishes and bills the turn either way — so label the control **stop**, not *cancel*, and never imply the work was called off.
2168
+ - **`cancel()`** stops waiting for the turn in flight. (Since 0.351.0 it stops the run itself.)
2155
2169
  - **`TIMEOUT`** — the client stopped waiting. Still running, still billed: say it is taking longer than usual, never that it failed.
2156
2170
  - **`CANCELLED`** — the user pressed your stop control. Render no error at all.
2157
2171
 
package/dist/contract.cjs CHANGED
@@ -2264,9 +2264,21 @@ const HOOKS = [
2264
2264
  "it off, so hide the affordance rather than retrying; TIMEOUT means the " +
2265
2265
  "client stopped waiting and the turn is STILL running and billed, so " +
2266
2266
  "say it is taking longer, never that it failed or that they are " +
2267
- "offline; CANCELLED is the user pressing your stop control, so render " +
2268
- "no error at all. Call cancel() to stop waiting -- it ends the WAIT, " +
2269
- "not the turn. NEVER surface a " +
2267
+ "offline; TURN_IN_PROGRESS (409) means the agent is still working on an " +
2268
+ "earlier message, so nothing was sent: put the text back and say they can " +
2269
+ "send it when that one is done; CANCELLED is the user's own choice, so " +
2270
+ "render no error at all. A RUN LIVES ON THE SERVER (sc-18562): leaving the " +
2271
+ "page, a refresh or a lost connection does not end it. `sending` is true " +
2272
+ "while one is in progress, on a later mount too, and its answer lands in " +
2273
+ "`messages` by itself, so gate the composer on `sending` and never resend. " +
2274
+ "cancel() really stops the run (label it 'Stop'): send() then RESOLVES with " +
2275
+ "the stopped row, and changes already made stay made. If the stop fails, " +
2276
+ "`error` is set while `sending` stays true. On an older host cancel() only " +
2277
+ "ends the wait and send() rejects CANCELLED. An assistant message that " +
2278
+ "ended early carries `outcome` ('stopped' | 'failed') and the content '…': " +
2279
+ "render its `activity` and your own line instead of a bubble. A rejection " +
2280
+ "with `stored: true` kept the message in `messages`, so do not put the text " +
2281
+ "back. NEVER surface a " +
2270
2282
  "raw error or the workspace's billing state to an app user. " +
2271
2283
  "RENDER AN ASSISTANT REPLY WITH <RichText value={msg.content} />, " +
2272
2284
  "not <Text>: a model answers in MARKDOWN by default — **bold**, " +
@@ -2310,9 +2322,10 @@ const HOOKS = [
2310
2322
  "Reads ctx.agents.",
2311
2323
  returnShape: {
2312
2324
  send: "(text, { files }?) => Promise<{ id, role, content, created_at } | null>",
2325
+ cancel: "() => void // stops the run; send() resolves with the stopped row",
2313
2326
  reset: "() => void",
2314
- messages: "Array<{ id, conversation_id, role, content, created_at }>",
2315
- sending: "boolean",
2327
+ messages: "Array<{ id, conversation_id, role, content, activity?, outcome?, created_at }>",
2328
+ sending: "boolean // true while a run is in progress, also one found on mount",
2316
2329
  resuming:
2317
2330
  "boolean // true only while the stored transcript is being reopened on mount; show a loading state, not an empty thread",
2318
2331
  error: "AgentError | null",
@@ -2504,11 +2517,11 @@ const HOOKS = [
2504
2517
  signature: "usePayments()",
2505
2518
  returnShape: {
2506
2519
  requestPayment:
2507
- "({ amount_cents?, currency?, description, kind, return_path?, order? }) => Promise<{ id, status, order }> // kind is REQUIRED: \"physical\" | \"service\" | \"digital\" — what is sold; a digital charge is refused in an iOS/Android build (DIGITAL_SALE_NEEDS_STORE_BILLING); amount_cents (minor units) is REQUIRED without order; order: { table_id, record_id } — the order row this pays for, in a table with a payment-status column; the SERVER marks it paid when the payment settles, so never write \"paid\" yourself (refused: ORDER_NOT_FOUND, ORDER_NOT_PAYABLE, ORDER_ALREADY_PAID; ORDER_PAYMENT_IN_PROGRESS is retryable while another checkout for the order is open). The orders table also REQUIRES an order-total column (orderTotal; without one: ORDER_NOT_PAYABLE) and the server charges the total stored on the order: create the order with its total, then pass order and omit amount_cents (if sent it must equal the total; refused, not retryable: ORDER_TOTAL_INVALID when the total is empty, zero, negative or not whole, ORDER_AMOUNT_MISMATCH when amount_cents differs). The total is write-once but written by the order's creator, so compute it from prices the buyer cannot change; host opens hosted Checkout; rejects with PaymentError { code, message, retryable } — render the message when retryable is false, never \"try again\"",
2520
+ "({ amount_cents?, currency?, description, kind, return_path?, order? }) => Promise<{ id, status, order }> // kind is REQUIRED: \"physical\" | \"service\" | \"digital\" — what is sold; a digital charge is refused in an iOS/Android build (DIGITAL_SALE_NEEDS_STORE_BILLING); amount_cents (minor units) is REQUIRED without order; order: { table_id, record_id } — the order row this pays for, in a table with a payment-status column; the SERVER marks it paid when the payment settles, so never write \"paid\" yourself (refused: ORDER_NOT_FOUND, ORDER_NOT_PAYABLE, ORDER_ALREADY_PAID; ORDER_PAYMENT_IN_PROGRESS is retryable while another checkout for the order is open). The orders table also REQUIRES an order-total column the server prices (orderTotal: { lines, via } in the datastoreTemplate; without one: ORDER_NOT_PAYABLE): create the order, then its lines, then pass order and omit amount_cents — the server sums quantity × the products table's unitPrice (plus the order's own pricedItem, e.g. shipping), writes the total and charges it; never compute, write or send a total (if amount_cents is sent it must equal the total; refused, not retryable: ORDER_LINES_INVALID when the lines cannot be priced, ORDER_TOTAL_INVALID when the total is zero, ORDER_AMOUNT_MISMATCH when amount_cents differs; ORDER_NOT_PAYABLE also when the payer could write or create a price). Once priced, the order's lines are fixed (adding or removing one: ORDER_LOCKED); host opens hosted Checkout; rejects with PaymentError { code, message, retryable } — render the message when retryable is false, never \"try again\"",
2508
2521
  getPayment:
2509
2522
  "(paymentId) => Promise<{ id, status, amount_cents, currency, description, order }> // order: { table_id, record_id } | null — read it after returning from Checkout",
2510
2523
  requestGuestPayment:
2511
- "({ amount_cents?, currency?, description, return_path?, order }) => Promise<{ id, status, order }> // a visitor who is NOT signed in buys physical goods (no kind). The orders table needs a payment-status AND an order-total column, as for requestPayment: create the order with its total and omit amount_cents (if sent it must equal the total). order is REQUIRED: create the order row first with useDatastoreMutation().create (the maker lets everyone add rows to the orders table and nobody read them; collect the shipping address and contact there), then pay for it within 15 minutes — only the visitor who created it can. Needs the payments.charge:guest scope too. The orders table needs a buyerEmail column the order is created with: the platform emails the order confirmation there, and an order without a valid address is refused with BUYER_EMAIL_INVALID (not retryable). The host runs a security check and opens hosted Checkout. Refused: TRIAL_RESTRICTED, GUEST_CHECKOUT_LIMIT_REACHED (retryable), CAPTCHA_FAILED / CAPTCHA_UNAVAILABLE (retryable), NOT_FOUND where the shop does not offer guest checkout, plus the requestPayment refusals",
2524
+ "({ amount_cents?, currency?, description, return_path?, order }) => Promise<{ id, status, order }> // a visitor who is NOT signed in buys physical goods (no kind). The orders table needs a payment-status AND a server-priced order-total column, as for requestPayment: create the order, then its lines, and omit amount_cents (if sent it must equal the total). order is REQUIRED: create the order row first with useDatastoreMutation().create (the maker lets everyone add rows to the orders table and nobody read them; collect the shipping address and contact there), then pay for it within 15 minutes — only the visitor who created it can. Needs the payments.charge:guest scope too. The orders table needs a buyerEmail column the order is created with: the platform emails the order confirmation there, and an order without a valid address is refused with BUYER_EMAIL_INVALID (not retryable). The host runs a security check and opens hosted Checkout. Refused: TRIAL_RESTRICTED, GUEST_CHECKOUT_LIMIT_REACHED (retryable), CAPTCHA_FAILED / CAPTCHA_UNAVAILABLE (retryable), NOT_FOUND where the shop does not offer guest checkout, plus the requestPayment refusals",
2512
2525
  getGuestPayment:
2513
2526
  "(paymentId) => Promise<{ id, status, amount_cents, currency, description, order }> // a guest's status read; the host holds the guest's one-time credential, so pass only the id",
2514
2527
  },
@@ -4377,7 +4390,7 @@ const MANIFEST_SCHEMA = {
4377
4390
  type: "object",
4378
4391
  required: false,
4379
4392
  description:
4380
- "Optional. Tables the widget needs, seeded into the workspace at install time. Authors wire them into the widget's `tableRef` properties via the Properties Panel — the SDK does not auto-bind. Limits: 100 tables, 200 columns per table, 100 sample rows per table and 20000 sample cells across the whole template (each row counts the keys it sets, and at least one, summed over every table). RELATION columns address siblings by `targetSuffix` (any table in the same array, in any order; tables may relate to each other both ways). Tables persist across uninstalls. A `tableRef` property may also carry `sharedTable: true`, declaring that the table is the APP'S OWN — the author picks an existing table and the widget seeds nothing for it. That is the correct shape for a widget that reads data it does not own (a chart, a metric, a manager view over another widget's table). `sharedTable` exempts the property from needing a seeded table at publish (`manifest.requiredTableRefsHaveTemplate`) WITHOUT making it optional: the author must still bind one, and the host still refuses to place the widget unbound. Use it instead of dropping `required` — a widget that silently renders an empty tile is the defect it looks like a fix for. sc-7530: a table may also declare `roleGrants` — group-scoped access named SYMBOLICALLY, because a group id belongs to the workspace that installs the widget and could never travel in the manifest. Declare the audiences once at template level as `roles: [{ key, label, description? }]` (key is lowercase kebab, max 32 roles), then per table `roleGrants: [{ role, canRead?, canWrite?, canDelete? }]`. The installing workspace binds each role to one of its own user groups (or has one created) during the install consent step, so a permission model where an admin group does everything and signed-in users only read survives the trip between workspaces. Use `publicGrant` for the two id-less audiences (everyone / any signed-in user) and `roleGrants` for anything that names a group. A role nobody binds simply writes no grant — it never fails the install. sc-7557: a column may declare `encrypted: true` — its values are stored AES-256-GCM encrypted at rest under a per-workspace subkey. The widget still reads and writes PLAINTEXT (the platform encrypts on write, decrypts for end users); studio users see `🔒` instead, and the column cannot be searched, filtered or sorted on. Sample `rows` you seed for it are encrypted the same way. Not valid on `RELATION` — its value is a foreign key the backend must resolve — and publishing one is rejected. An `inheritAcl` RELATION column may add `inheritAclReadOnly: true` — rows then inherit READ access only, so members of the parent read every child and may add children, but change or delete only the rows they created (pair with `grantCreatorPermissions`). A column may declare `defaultValue`, written when a create omits it: `@currentUser` on USER, `@now` on DATE / DATETIME, `@uuid` on UUID (a new random id per row), or a literal of the column's own type (none on FILE, RELATION or USER_GROUP — ids belong to the installing workspace). `defaultLocked: true` on an `@currentUser` / `@now` / `@uuid` default makes the server always stamp it and ignore any client value on create and update, so an author column cannot be forged. `immutable: true` makes a column write-once: a create sets it as usual and any value sent for it on update is ignored (not valid on a MANY_TO_MANY relation). `defaultOnCreate: true` makes every create start the column at its `defaultValue` (or empty without one) whatever the client sends, while an update may change it through the row's normal access, so a creator cannot file a row already approved; it protects only a table whose filers cannot edit their row afterwards, so no `grantCreatorPermissions` there (a required column needs a non-empty default; not on a paymentStatus, latestVia or copyOf column). `paymentStatus: true` makes a STRING or BOOL column the table's payment status (at most one per table; not required, encrypted, immutable or defaulting to paid): the table also needs an `orderTotal` column; a settled `requestPayment({ order: { table_id, record_id } })` for one of its rows writes it (`PAID`, or `true` on a BOOL; `REFUNDED` / `false` after a full refund), and every client value for it is ignored, so a buyer cannot mark their own order paid. `orderTotal: true` makes a NUMBER column the order's total, which a charge for the order bills: integer MINOR units (339 kr is 33900) in the workspace's charge currency, no currency stored. A table with a paymentStatus column REQUIRES exactly one (and it is valid only beside one), and it must be `immutable: true` (not encrypted, latestVia or copyOf). The order's creator writes it on create and a later update is ignored; `requestPayment({ order })` then charges that stored total, so omit `amount_cents`. It fixes the total, not the price: compute it from prices the buyer cannot change. `buyerEmail: true` makes a STRING column the buyer's email address, at most one per table, only in a table with a paymentStatus column, and it must be `immutable: true` (not encrypted, latestVia or copyOf): when a charge marks the order paid the platform emails the buyer an order confirmation (a guest at this address, a signed-in buyer at their account's address), and a refund notice after a full refund, so a widget never sends its own. A guest charge (`requestGuestPayment`) for an order whose table has no buyerEmail column, or whose address is empty or invalid, is refused. A table may declare `presence: true` so the people who share a row see which of each other are online (useOnlineMembers); it takes effect only while the workspace records user activity, and an upgrade that declares it turns it on for the existing table. A table whose rows people join and leave through per-record grants (conversations) may declare `deleteWhenLastMemberLeaves: true`: when a signed-in member giving up their own grant leaves a row with no grant and no table-wide grant lets anyone read it, the row and every row a CASCADE relation ties to it (including rows deleted earlier) are deleted for good. A row that never had a grant (a seeded sample row) is never deleted this way, and a revoke made in the Studio never deletes. An upgrade that declares it turns it on for the existing table. A ONE_TO_ONE / ONE_TO_MANY RELATION may declare `latestVia: \"<relation column on its target that points back>\"` (onDelete left at SET_NULL; that relation must have inheritAcl and be immutable): the server keeps it at the newest row of the target table that points back at this row. A column may declare `copyOf: { via, column }`: the server keeps it equal to `column` on the row the latest-row column `via` points at (same type, or text into text, cut to 140 characters in a STRING column; a copy of an encrypted column must be encrypted, and a copy cannot inheritAcl). Both are written only by the server, in the same write as the related row; a client value is ignored. A table may declare `constraints`, checked on every write for every client and refused as CONSTRAINT_VIOLATION: `unique` ({ columns, partitionColumns?, unlessRelated?: { relation, column } } — waived for rows whose related row has that yes/no column set), `no-overlap` ({ startColumn, endColumn, partitionColumns? }), `related-open` ({ relation, closedColumn } — no row is added, changed or removed while the related row's column is filled) and `related-index` ({ column, relation, listColumn } — the number must be a position in the related row's list). An upgrade adds a declared constraint to an existing table without judging the rows already in it.",
4393
+ "Optional. Tables the widget needs, seeded into the workspace at install time. Authors wire them into the widget's `tableRef` properties via the Properties Panel — the SDK does not auto-bind. Limits: 100 tables, 200 columns per table, 100 sample rows per table and 20000 sample cells across the whole template (each row counts the keys it sets, and at least one, summed over every table). RELATION columns address siblings by `targetSuffix` (any table in the same array, in any order; tables may relate to each other both ways). Tables persist across uninstalls. A `tableRef` property may also carry `sharedTable: true`, declaring that the table is the APP'S OWN — the author picks an existing table and the widget seeds nothing for it. That is the correct shape for a widget that reads data it does not own (a chart, a metric, a manager view over another widget's table). `sharedTable` exempts the property from needing a seeded table at publish (`manifest.requiredTableRefsHaveTemplate`) WITHOUT making it optional: the author must still bind one, and the host still refuses to place the widget unbound. Use it instead of dropping `required` — a widget that silently renders an empty tile is the defect it looks like a fix for. sc-7530: a table may also declare `roleGrants` — group-scoped access named SYMBOLICALLY, because a group id belongs to the workspace that installs the widget and could never travel in the manifest. Declare the audiences once at template level as `roles: [{ key, label, description? }]` (key is lowercase kebab, max 32 roles), then per table `roleGrants: [{ role, canRead?, canWrite?, canDelete? }]`. The installing workspace binds each role to one of its own user groups (or has one created) during the install consent step, so a permission model where an admin group does everything and signed-in users only read survives the trip between workspaces. Use `publicGrant` for the two id-less audiences (everyone / any signed-in user) and `roleGrants` for anything that names a group. A role nobody binds simply writes no grant — it never fails the install. sc-7557: a column may declare `encrypted: true` — its values are stored AES-256-GCM encrypted at rest under a per-workspace subkey. The widget still reads and writes PLAINTEXT (the platform encrypts on write, decrypts for end users); studio users see `🔒` instead, and the column cannot be searched, filtered or sorted on. Sample `rows` you seed for it are encrypted the same way. Not valid on `RELATION` — its value is a foreign key the backend must resolve — and publishing one is rejected. An `inheritAcl` RELATION column may add `inheritAclReadOnly: true` — rows then inherit READ access only, so members of the parent read every child and may add children, but change or delete only the rows they created (pair with `grantCreatorPermissions`). A column may declare `defaultValue`, written when a create omits it: `@currentUser` on USER, `@now` on DATE / DATETIME, `@uuid` on UUID (a new random id per row), or a literal of the column's own type (none on FILE, RELATION or USER_GROUP — ids belong to the installing workspace). `defaultLocked: true` on an `@currentUser` / `@now` / `@uuid` default makes the server always stamp it and ignore any client value on create and update, so an author column cannot be forged. `immutable: true` makes a column write-once: a create sets it as usual and any value sent for it on update is ignored (not valid on a MANY_TO_MANY relation). `defaultOnCreate: true` makes every create start the column at its `defaultValue` (or empty without one) whatever the client sends, while an update may change it through the row's normal access, so a creator cannot file a row already approved; it protects only a table whose filers cannot edit their row afterwards, so no `grantCreatorPermissions` there (a required column needs a non-empty default; not on a paymentStatus, latestVia or copyOf column). `paymentStatus: true` makes a STRING or BOOL column the table's payment status (at most one per table; not required, encrypted, immutable or defaulting to paid): the table also needs an `orderTotal` column; a settled `requestPayment({ order: { table_id, record_id } })` for one of its rows writes it (`PAID`, or `true` on a BOOL; `REFUNDED` / `false` after a full refund), and every client value for it is ignored, so a buyer cannot mark their own order paid. `orderTotal: { lines: \"<lines table suffix>\", via: \"<its relation to this table>\" }` makes a NUMBER column the order's total, which a charge for the order bills: integer MINOR units (339 kr is 33900) in the workspace's charge currency, no currency stored. A table with a paymentStatus column REQUIRES exactly one (and it is valid only beside one), and it must be `immutable: true` (not encrypted, latestVia or copyOf). The SERVER prices it when the charge opens and ignores any client value: Σ over the order's lines of `lineQuantity` × the `unitPrice` of the row the line's `pricedItem` names, plus the order table's own `pricedItem` once (a shipping option). `via` is a write-once ONE_TO_MANY relation on the lines table pointing at this table. A bare `orderTotal: true` is accepted only on an orders table that has its own `pricedItem`; publishing any other unpriced order total is refused (an already published template still installs, and its order charges are refused with ORDER_NOT_PAYABLE). `unitPrice: true` makes a NUMBER column a product's price in minor units (one per table). `pricedItem: true` makes a write-once single RELATION (one per table) to a table with a unitPrice column the item a line or an order is priced by. `lineQuantity: true` makes a write-once NUMBER column (one per table) a line's quantity, a whole number from 1 to 999 (empty is 1). A payer who may edit or create rows in a priced table is refused, and once an order holds its total no line is added or removed (ORDER_LOCKED). `buyerEmail: true` makes a STRING column the buyer's email address, at most one per table, only in a table with a paymentStatus column, and it must be `immutable: true` (not encrypted, latestVia or copyOf): when a charge marks the order paid the platform emails the buyer an order confirmation (a guest at this address, a signed-in buyer at their account's address), and a refund notice after a full refund, so a widget never sends its own. A guest charge (`requestGuestPayment`) for an order whose table has no buyerEmail column, or whose address is empty or invalid, is refused. A table may declare `presence: true` so the people who share a row see which of each other are online (useOnlineMembers); it takes effect only while the workspace records user activity, and an upgrade that declares it turns it on for the existing table. A table whose rows people join and leave through per-record grants (conversations) may declare `deleteWhenLastMemberLeaves: true`: when a signed-in member giving up their own grant leaves a row with no grant and no table-wide grant lets anyone read it, the row and every row a CASCADE relation ties to it (including rows deleted earlier) are deleted for good. A row that never had a grant (a seeded sample row) is never deleted this way, and a revoke made in the Studio never deletes. An upgrade that declares it turns it on for the existing table. A ONE_TO_ONE / ONE_TO_MANY RELATION may declare `latestVia: \"<relation column on its target that points back>\"` (onDelete left at SET_NULL; that relation must have inheritAcl and be immutable): the server keeps it at the newest row of the target table that points back at this row. A column may declare `copyOf: { via, column }`: the server keeps it equal to `column` on the row the latest-row column `via` points at (same type, or text into text, cut to 140 characters in a STRING column; a copy of an encrypted column must be encrypted, and a copy cannot inheritAcl). Both are written only by the server, in the same write as the related row; a client value is ignored. A table may declare `constraints`, checked on every write for every client and refused as CONSTRAINT_VIOLATION: `unique` ({ columns, partitionColumns?, unlessRelated?: { relation, column } } — waived for rows whose related row has that yes/no column set), `no-overlap` ({ startColumn, endColumn, partitionColumns? }), `related-open` ({ relation, closedColumn } — no row is added, changed or removed while the related row's column is filled) and `related-index` ({ column, relation, listColumn } — the number must be a position in the related row's list). An upgrade adds a declared constraint to an existing table without judging the rows already in it.",
4381
4394
  },
4382
4395
  translations: {
4383
4396
  type: "object",
@@ -4533,6 +4546,7 @@ const WIDGET_CONTEXT_SHAPE = {
4533
4546
  description:
4534
4547
  "sc-7991 — injected @colixsystems/agents-client instance. " +
4535
4548
  "{ conversations(agentId) -> { create(), list(query), remove(conversationId), " +
4549
+ "stop(conversationId) -> Promise<{ conversation_id, stopping }> (sc-18562; optional on older hosts), " +
4536
4550
  "messages(conversationId) -> { list(query), send({ content, file_ids? }) } }, " +
4537
4551
  "capabilities(agentId) -> Promise<{ accepts_files, accepted_file_types, max_files, max_pdfs, max_file_bytes, max_total_bytes }>, " +
4538
4552
  "connections(agentId) -> { list(), create({ name, server_url, token }), test(id), remove(id), " +
@@ -7174,7 +7188,16 @@ const CONTRACT = deepFreeze({
7174
7188
  // lint warning flags one that does not.
7175
7189
  // 1.287.0: additive (sc-15765) — `connection` joins `actionScriptGlobals`:
7176
7190
  // the account a per-connection scheduled run is for, null otherwise.
7177
- version: "1.287.0",
7191
+ // 1.288.0: behaviour (sc-18562) — an agent run lives on the server: `sending`
7192
+ // covers a run found on mount, cancel() really stops it and send() resolves
7193
+ // with the stopped row, messages carry `outcome`, and a send during a run
7194
+ // rejects TURN_IN_PROGRESS. A rejection says `stored` when the message was kept.
7195
+ // 1.289.0 (sc-16651): the server prices an order. Template columns
7196
+ // `unitPrice`, `pricedItem`, `lineQuantity` and `orderTotal: { lines, via }`;
7197
+ // an unpriced order total is refused at publish and its order charges
7198
+ // with ORDER_NOT_PAYABLE (breaking for those). New PaymentError code
7199
+ // ORDER_LINES_INVALID; a priced order's line writes refuse ORDER_LOCKED.
7200
+ version: "1.289.0",
7178
7201
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7179
7202
  hooks: HOOKS,
7180
7203
  primitives: PRIMITIVES,
package/dist/contract.js CHANGED
@@ -2259,9 +2259,21 @@ const HOOKS = [
2259
2259
  "it off, so hide the affordance rather than retrying; TIMEOUT means the " +
2260
2260
  "client stopped waiting and the turn is STILL running and billed, so " +
2261
2261
  "say it is taking longer, never that it failed or that they are " +
2262
- "offline; CANCELLED is the user pressing your stop control, so render " +
2263
- "no error at all. Call cancel() to stop waiting -- it ends the WAIT, " +
2264
- "not the turn. NEVER surface a " +
2262
+ "offline; TURN_IN_PROGRESS (409) means the agent is still working on an " +
2263
+ "earlier message, so nothing was sent: put the text back and say they can " +
2264
+ "send it when that one is done; CANCELLED is the user's own choice, so " +
2265
+ "render no error at all. A RUN LIVES ON THE SERVER (sc-18562): leaving the " +
2266
+ "page, a refresh or a lost connection does not end it. `sending` is true " +
2267
+ "while one is in progress, on a later mount too, and its answer lands in " +
2268
+ "`messages` by itself, so gate the composer on `sending` and never resend. " +
2269
+ "cancel() really stops the run (label it 'Stop'): send() then RESOLVES with " +
2270
+ "the stopped row, and changes already made stay made. If the stop fails, " +
2271
+ "`error` is set while `sending` stays true. On an older host cancel() only " +
2272
+ "ends the wait and send() rejects CANCELLED. An assistant message that " +
2273
+ "ended early carries `outcome` ('stopped' | 'failed') and the content '…': " +
2274
+ "render its `activity` and your own line instead of a bubble. A rejection " +
2275
+ "with `stored: true` kept the message in `messages`, so do not put the text " +
2276
+ "back. NEVER surface a " +
2265
2277
  "raw error or the workspace's billing state to an app user. " +
2266
2278
  "RENDER AN ASSISTANT REPLY WITH <RichText value={msg.content} />, " +
2267
2279
  "not <Text>: a model answers in MARKDOWN by default — **bold**, " +
@@ -2305,9 +2317,10 @@ const HOOKS = [
2305
2317
  "Reads ctx.agents.",
2306
2318
  returnShape: {
2307
2319
  send: "(text, { files }?) => Promise<{ id, role, content, created_at } | null>",
2320
+ cancel: "() => void // stops the run; send() resolves with the stopped row",
2308
2321
  reset: "() => void",
2309
- messages: "Array<{ id, conversation_id, role, content, created_at }>",
2310
- sending: "boolean",
2322
+ messages: "Array<{ id, conversation_id, role, content, activity?, outcome?, created_at }>",
2323
+ sending: "boolean // true while a run is in progress, also one found on mount",
2311
2324
  resuming:
2312
2325
  "boolean // true only while the stored transcript is being reopened on mount; show a loading state, not an empty thread",
2313
2326
  error: "AgentError | null",
@@ -2499,11 +2512,11 @@ const HOOKS = [
2499
2512
  signature: "usePayments()",
2500
2513
  returnShape: {
2501
2514
  requestPayment:
2502
- "({ amount_cents?, currency?, description, kind, return_path?, order? }) => Promise<{ id, status, order }> // kind is REQUIRED: \"physical\" | \"service\" | \"digital\" — what is sold; a digital charge is refused in an iOS/Android build (DIGITAL_SALE_NEEDS_STORE_BILLING); amount_cents (minor units) is REQUIRED without order; order: { table_id, record_id } — the order row this pays for, in a table with a payment-status column; the SERVER marks it paid when the payment settles, so never write \"paid\" yourself (refused: ORDER_NOT_FOUND, ORDER_NOT_PAYABLE, ORDER_ALREADY_PAID; ORDER_PAYMENT_IN_PROGRESS is retryable while another checkout for the order is open). The orders table also REQUIRES an order-total column (orderTotal; without one: ORDER_NOT_PAYABLE) and the server charges the total stored on the order: create the order with its total, then pass order and omit amount_cents (if sent it must equal the total; refused, not retryable: ORDER_TOTAL_INVALID when the total is empty, zero, negative or not whole, ORDER_AMOUNT_MISMATCH when amount_cents differs). The total is write-once but written by the order's creator, so compute it from prices the buyer cannot change; host opens hosted Checkout; rejects with PaymentError { code, message, retryable } — render the message when retryable is false, never \"try again\"",
2515
+ "({ amount_cents?, currency?, description, kind, return_path?, order? }) => Promise<{ id, status, order }> // kind is REQUIRED: \"physical\" | \"service\" | \"digital\" — what is sold; a digital charge is refused in an iOS/Android build (DIGITAL_SALE_NEEDS_STORE_BILLING); amount_cents (minor units) is REQUIRED without order; order: { table_id, record_id } — the order row this pays for, in a table with a payment-status column; the SERVER marks it paid when the payment settles, so never write \"paid\" yourself (refused: ORDER_NOT_FOUND, ORDER_NOT_PAYABLE, ORDER_ALREADY_PAID; ORDER_PAYMENT_IN_PROGRESS is retryable while another checkout for the order is open). The orders table also REQUIRES an order-total column the server prices (orderTotal: { lines, via } in the datastoreTemplate; without one: ORDER_NOT_PAYABLE): create the order, then its lines, then pass order and omit amount_cents — the server sums quantity × the products table's unitPrice (plus the order's own pricedItem, e.g. shipping), writes the total and charges it; never compute, write or send a total (if amount_cents is sent it must equal the total; refused, not retryable: ORDER_LINES_INVALID when the lines cannot be priced, ORDER_TOTAL_INVALID when the total is zero, ORDER_AMOUNT_MISMATCH when amount_cents differs; ORDER_NOT_PAYABLE also when the payer could write or create a price). Once priced, the order's lines are fixed (adding or removing one: ORDER_LOCKED); host opens hosted Checkout; rejects with PaymentError { code, message, retryable } — render the message when retryable is false, never \"try again\"",
2503
2516
  getPayment:
2504
2517
  "(paymentId) => Promise<{ id, status, amount_cents, currency, description, order }> // order: { table_id, record_id } | null — read it after returning from Checkout",
2505
2518
  requestGuestPayment:
2506
- "({ amount_cents?, currency?, description, return_path?, order }) => Promise<{ id, status, order }> // a visitor who is NOT signed in buys physical goods (no kind). The orders table needs a payment-status AND an order-total column, as for requestPayment: create the order with its total and omit amount_cents (if sent it must equal the total). order is REQUIRED: create the order row first with useDatastoreMutation().create (the maker lets everyone add rows to the orders table and nobody read them; collect the shipping address and contact there), then pay for it within 15 minutes — only the visitor who created it can. Needs the payments.charge:guest scope too. The orders table needs a buyerEmail column the order is created with: the platform emails the order confirmation there, and an order without a valid address is refused with BUYER_EMAIL_INVALID (not retryable). The host runs a security check and opens hosted Checkout. Refused: TRIAL_RESTRICTED, GUEST_CHECKOUT_LIMIT_REACHED (retryable), CAPTCHA_FAILED / CAPTCHA_UNAVAILABLE (retryable), NOT_FOUND where the shop does not offer guest checkout, plus the requestPayment refusals",
2519
+ "({ amount_cents?, currency?, description, return_path?, order }) => Promise<{ id, status, order }> // a visitor who is NOT signed in buys physical goods (no kind). The orders table needs a payment-status AND a server-priced order-total column, as for requestPayment: create the order, then its lines, and omit amount_cents (if sent it must equal the total). order is REQUIRED: create the order row first with useDatastoreMutation().create (the maker lets everyone add rows to the orders table and nobody read them; collect the shipping address and contact there), then pay for it within 15 minutes — only the visitor who created it can. Needs the payments.charge:guest scope too. The orders table needs a buyerEmail column the order is created with: the platform emails the order confirmation there, and an order without a valid address is refused with BUYER_EMAIL_INVALID (not retryable). The host runs a security check and opens hosted Checkout. Refused: TRIAL_RESTRICTED, GUEST_CHECKOUT_LIMIT_REACHED (retryable), CAPTCHA_FAILED / CAPTCHA_UNAVAILABLE (retryable), NOT_FOUND where the shop does not offer guest checkout, plus the requestPayment refusals",
2507
2520
  getGuestPayment:
2508
2521
  "(paymentId) => Promise<{ id, status, amount_cents, currency, description, order }> // a guest's status read; the host holds the guest's one-time credential, so pass only the id",
2509
2522
  },
@@ -4372,7 +4385,7 @@ const MANIFEST_SCHEMA = {
4372
4385
  type: "object",
4373
4386
  required: false,
4374
4387
  description:
4375
- "Optional. Tables the widget needs, seeded into the workspace at install time. Authors wire them into the widget's `tableRef` properties via the Properties Panel — the SDK does not auto-bind. Limits: 100 tables, 200 columns per table, 100 sample rows per table and 20000 sample cells across the whole template (each row counts the keys it sets, and at least one, summed over every table). RELATION columns address siblings by `targetSuffix` (any table in the same array, in any order; tables may relate to each other both ways). Tables persist across uninstalls. A `tableRef` property may also carry `sharedTable: true`, declaring that the table is the APP'S OWN — the author picks an existing table and the widget seeds nothing for it. That is the correct shape for a widget that reads data it does not own (a chart, a metric, a manager view over another widget's table). `sharedTable` exempts the property from needing a seeded table at publish (`manifest.requiredTableRefsHaveTemplate`) WITHOUT making it optional: the author must still bind one, and the host still refuses to place the widget unbound. Use it instead of dropping `required` — a widget that silently renders an empty tile is the defect it looks like a fix for. sc-7530: a table may also declare `roleGrants` — group-scoped access named SYMBOLICALLY, because a group id belongs to the workspace that installs the widget and could never travel in the manifest. Declare the audiences once at template level as `roles: [{ key, label, description? }]` (key is lowercase kebab, max 32 roles), then per table `roleGrants: [{ role, canRead?, canWrite?, canDelete? }]`. The installing workspace binds each role to one of its own user groups (or has one created) during the install consent step, so a permission model where an admin group does everything and signed-in users only read survives the trip between workspaces. Use `publicGrant` for the two id-less audiences (everyone / any signed-in user) and `roleGrants` for anything that names a group. A role nobody binds simply writes no grant — it never fails the install. sc-7557: a column may declare `encrypted: true` — its values are stored AES-256-GCM encrypted at rest under a per-workspace subkey. The widget still reads and writes PLAINTEXT (the platform encrypts on write, decrypts for end users); studio users see `🔒` instead, and the column cannot be searched, filtered or sorted on. Sample `rows` you seed for it are encrypted the same way. Not valid on `RELATION` — its value is a foreign key the backend must resolve — and publishing one is rejected. An `inheritAcl` RELATION column may add `inheritAclReadOnly: true` — rows then inherit READ access only, so members of the parent read every child and may add children, but change or delete only the rows they created (pair with `grantCreatorPermissions`). A column may declare `defaultValue`, written when a create omits it: `@currentUser` on USER, `@now` on DATE / DATETIME, `@uuid` on UUID (a new random id per row), or a literal of the column's own type (none on FILE, RELATION or USER_GROUP — ids belong to the installing workspace). `defaultLocked: true` on an `@currentUser` / `@now` / `@uuid` default makes the server always stamp it and ignore any client value on create and update, so an author column cannot be forged. `immutable: true` makes a column write-once: a create sets it as usual and any value sent for it on update is ignored (not valid on a MANY_TO_MANY relation). `defaultOnCreate: true` makes every create start the column at its `defaultValue` (or empty without one) whatever the client sends, while an update may change it through the row's normal access, so a creator cannot file a row already approved; it protects only a table whose filers cannot edit their row afterwards, so no `grantCreatorPermissions` there (a required column needs a non-empty default; not on a paymentStatus, latestVia or copyOf column). `paymentStatus: true` makes a STRING or BOOL column the table's payment status (at most one per table; not required, encrypted, immutable or defaulting to paid): the table also needs an `orderTotal` column; a settled `requestPayment({ order: { table_id, record_id } })` for one of its rows writes it (`PAID`, or `true` on a BOOL; `REFUNDED` / `false` after a full refund), and every client value for it is ignored, so a buyer cannot mark their own order paid. `orderTotal: true` makes a NUMBER column the order's total, which a charge for the order bills: integer MINOR units (339 kr is 33900) in the workspace's charge currency, no currency stored. A table with a paymentStatus column REQUIRES exactly one (and it is valid only beside one), and it must be `immutable: true` (not encrypted, latestVia or copyOf). The order's creator writes it on create and a later update is ignored; `requestPayment({ order })` then charges that stored total, so omit `amount_cents`. It fixes the total, not the price: compute it from prices the buyer cannot change. `buyerEmail: true` makes a STRING column the buyer's email address, at most one per table, only in a table with a paymentStatus column, and it must be `immutable: true` (not encrypted, latestVia or copyOf): when a charge marks the order paid the platform emails the buyer an order confirmation (a guest at this address, a signed-in buyer at their account's address), and a refund notice after a full refund, so a widget never sends its own. A guest charge (`requestGuestPayment`) for an order whose table has no buyerEmail column, or whose address is empty or invalid, is refused. A table may declare `presence: true` so the people who share a row see which of each other are online (useOnlineMembers); it takes effect only while the workspace records user activity, and an upgrade that declares it turns it on for the existing table. A table whose rows people join and leave through per-record grants (conversations) may declare `deleteWhenLastMemberLeaves: true`: when a signed-in member giving up their own grant leaves a row with no grant and no table-wide grant lets anyone read it, the row and every row a CASCADE relation ties to it (including rows deleted earlier) are deleted for good. A row that never had a grant (a seeded sample row) is never deleted this way, and a revoke made in the Studio never deletes. An upgrade that declares it turns it on for the existing table. A ONE_TO_ONE / ONE_TO_MANY RELATION may declare `latestVia: \"<relation column on its target that points back>\"` (onDelete left at SET_NULL; that relation must have inheritAcl and be immutable): the server keeps it at the newest row of the target table that points back at this row. A column may declare `copyOf: { via, column }`: the server keeps it equal to `column` on the row the latest-row column `via` points at (same type, or text into text, cut to 140 characters in a STRING column; a copy of an encrypted column must be encrypted, and a copy cannot inheritAcl). Both are written only by the server, in the same write as the related row; a client value is ignored. A table may declare `constraints`, checked on every write for every client and refused as CONSTRAINT_VIOLATION: `unique` ({ columns, partitionColumns?, unlessRelated?: { relation, column } } — waived for rows whose related row has that yes/no column set), `no-overlap` ({ startColumn, endColumn, partitionColumns? }), `related-open` ({ relation, closedColumn } — no row is added, changed or removed while the related row's column is filled) and `related-index` ({ column, relation, listColumn } — the number must be a position in the related row's list). An upgrade adds a declared constraint to an existing table without judging the rows already in it.",
4388
+ "Optional. Tables the widget needs, seeded into the workspace at install time. Authors wire them into the widget's `tableRef` properties via the Properties Panel — the SDK does not auto-bind. Limits: 100 tables, 200 columns per table, 100 sample rows per table and 20000 sample cells across the whole template (each row counts the keys it sets, and at least one, summed over every table). RELATION columns address siblings by `targetSuffix` (any table in the same array, in any order; tables may relate to each other both ways). Tables persist across uninstalls. A `tableRef` property may also carry `sharedTable: true`, declaring that the table is the APP'S OWN — the author picks an existing table and the widget seeds nothing for it. That is the correct shape for a widget that reads data it does not own (a chart, a metric, a manager view over another widget's table). `sharedTable` exempts the property from needing a seeded table at publish (`manifest.requiredTableRefsHaveTemplate`) WITHOUT making it optional: the author must still bind one, and the host still refuses to place the widget unbound. Use it instead of dropping `required` — a widget that silently renders an empty tile is the defect it looks like a fix for. sc-7530: a table may also declare `roleGrants` — group-scoped access named SYMBOLICALLY, because a group id belongs to the workspace that installs the widget and could never travel in the manifest. Declare the audiences once at template level as `roles: [{ key, label, description? }]` (key is lowercase kebab, max 32 roles), then per table `roleGrants: [{ role, canRead?, canWrite?, canDelete? }]`. The installing workspace binds each role to one of its own user groups (or has one created) during the install consent step, so a permission model where an admin group does everything and signed-in users only read survives the trip between workspaces. Use `publicGrant` for the two id-less audiences (everyone / any signed-in user) and `roleGrants` for anything that names a group. A role nobody binds simply writes no grant — it never fails the install. sc-7557: a column may declare `encrypted: true` — its values are stored AES-256-GCM encrypted at rest under a per-workspace subkey. The widget still reads and writes PLAINTEXT (the platform encrypts on write, decrypts for end users); studio users see `🔒` instead, and the column cannot be searched, filtered or sorted on. Sample `rows` you seed for it are encrypted the same way. Not valid on `RELATION` — its value is a foreign key the backend must resolve — and publishing one is rejected. An `inheritAcl` RELATION column may add `inheritAclReadOnly: true` — rows then inherit READ access only, so members of the parent read every child and may add children, but change or delete only the rows they created (pair with `grantCreatorPermissions`). A column may declare `defaultValue`, written when a create omits it: `@currentUser` on USER, `@now` on DATE / DATETIME, `@uuid` on UUID (a new random id per row), or a literal of the column's own type (none on FILE, RELATION or USER_GROUP — ids belong to the installing workspace). `defaultLocked: true` on an `@currentUser` / `@now` / `@uuid` default makes the server always stamp it and ignore any client value on create and update, so an author column cannot be forged. `immutable: true` makes a column write-once: a create sets it as usual and any value sent for it on update is ignored (not valid on a MANY_TO_MANY relation). `defaultOnCreate: true` makes every create start the column at its `defaultValue` (or empty without one) whatever the client sends, while an update may change it through the row's normal access, so a creator cannot file a row already approved; it protects only a table whose filers cannot edit their row afterwards, so no `grantCreatorPermissions` there (a required column needs a non-empty default; not on a paymentStatus, latestVia or copyOf column). `paymentStatus: true` makes a STRING or BOOL column the table's payment status (at most one per table; not required, encrypted, immutable or defaulting to paid): the table also needs an `orderTotal` column; a settled `requestPayment({ order: { table_id, record_id } })` for one of its rows writes it (`PAID`, or `true` on a BOOL; `REFUNDED` / `false` after a full refund), and every client value for it is ignored, so a buyer cannot mark their own order paid. `orderTotal: { lines: \"<lines table suffix>\", via: \"<its relation to this table>\" }` makes a NUMBER column the order's total, which a charge for the order bills: integer MINOR units (339 kr is 33900) in the workspace's charge currency, no currency stored. A table with a paymentStatus column REQUIRES exactly one (and it is valid only beside one), and it must be `immutable: true` (not encrypted, latestVia or copyOf). The SERVER prices it when the charge opens and ignores any client value: Σ over the order's lines of `lineQuantity` × the `unitPrice` of the row the line's `pricedItem` names, plus the order table's own `pricedItem` once (a shipping option). `via` is a write-once ONE_TO_MANY relation on the lines table pointing at this table. A bare `orderTotal: true` is accepted only on an orders table that has its own `pricedItem`; publishing any other unpriced order total is refused (an already published template still installs, and its order charges are refused with ORDER_NOT_PAYABLE). `unitPrice: true` makes a NUMBER column a product's price in minor units (one per table). `pricedItem: true` makes a write-once single RELATION (one per table) to a table with a unitPrice column the item a line or an order is priced by. `lineQuantity: true` makes a write-once NUMBER column (one per table) a line's quantity, a whole number from 1 to 999 (empty is 1). A payer who may edit or create rows in a priced table is refused, and once an order holds its total no line is added or removed (ORDER_LOCKED). `buyerEmail: true` makes a STRING column the buyer's email address, at most one per table, only in a table with a paymentStatus column, and it must be `immutable: true` (not encrypted, latestVia or copyOf): when a charge marks the order paid the platform emails the buyer an order confirmation (a guest at this address, a signed-in buyer at their account's address), and a refund notice after a full refund, so a widget never sends its own. A guest charge (`requestGuestPayment`) for an order whose table has no buyerEmail column, or whose address is empty or invalid, is refused. A table may declare `presence: true` so the people who share a row see which of each other are online (useOnlineMembers); it takes effect only while the workspace records user activity, and an upgrade that declares it turns it on for the existing table. A table whose rows people join and leave through per-record grants (conversations) may declare `deleteWhenLastMemberLeaves: true`: when a signed-in member giving up their own grant leaves a row with no grant and no table-wide grant lets anyone read it, the row and every row a CASCADE relation ties to it (including rows deleted earlier) are deleted for good. A row that never had a grant (a seeded sample row) is never deleted this way, and a revoke made in the Studio never deletes. An upgrade that declares it turns it on for the existing table. A ONE_TO_ONE / ONE_TO_MANY RELATION may declare `latestVia: \"<relation column on its target that points back>\"` (onDelete left at SET_NULL; that relation must have inheritAcl and be immutable): the server keeps it at the newest row of the target table that points back at this row. A column may declare `copyOf: { via, column }`: the server keeps it equal to `column` on the row the latest-row column `via` points at (same type, or text into text, cut to 140 characters in a STRING column; a copy of an encrypted column must be encrypted, and a copy cannot inheritAcl). Both are written only by the server, in the same write as the related row; a client value is ignored. A table may declare `constraints`, checked on every write for every client and refused as CONSTRAINT_VIOLATION: `unique` ({ columns, partitionColumns?, unlessRelated?: { relation, column } } — waived for rows whose related row has that yes/no column set), `no-overlap` ({ startColumn, endColumn, partitionColumns? }), `related-open` ({ relation, closedColumn } — no row is added, changed or removed while the related row's column is filled) and `related-index` ({ column, relation, listColumn } — the number must be a position in the related row's list). An upgrade adds a declared constraint to an existing table without judging the rows already in it.",
4376
4389
  },
4377
4390
  translations: {
4378
4391
  type: "object",
@@ -4528,6 +4541,7 @@ const WIDGET_CONTEXT_SHAPE = {
4528
4541
  description:
4529
4542
  "sc-7991 — injected @colixsystems/agents-client instance. " +
4530
4543
  "{ conversations(agentId) -> { create(), list(query), remove(conversationId), " +
4544
+ "stop(conversationId) -> Promise<{ conversation_id, stopping }> (sc-18562; optional on older hosts), " +
4531
4545
  "messages(conversationId) -> { list(query), send({ content, file_ids? }) } }, " +
4532
4546
  "capabilities(agentId) -> Promise<{ accepts_files, accepted_file_types, max_files, max_pdfs, max_file_bytes, max_total_bytes }>, " +
4533
4547
  "connections(agentId) -> { list(), create({ name, server_url, token }), test(id), remove(id), " +
@@ -7169,7 +7183,16 @@ const CONTRACT = deepFreeze({
7169
7183
  // lint warning flags one that does not.
7170
7184
  // 1.287.0: additive (sc-15765) — `connection` joins `actionScriptGlobals`:
7171
7185
  // the account a per-connection scheduled run is for, null otherwise.
7172
- version: "1.287.0",
7186
+ // 1.288.0: behaviour (sc-18562) — an agent run lives on the server: `sending`
7187
+ // covers a run found on mount, cancel() really stops it and send() resolves
7188
+ // with the stopped row, messages carry `outcome`, and a send during a run
7189
+ // rejects TURN_IN_PROGRESS. A rejection says `stored` when the message was kept.
7190
+ // 1.289.0 (sc-16651): the server prices an order. Template columns
7191
+ // `unitPrice`, `pricedItem`, `lineQuantity` and `orderTotal: { lines, via }`;
7192
+ // an unpriced order total is refused at publish and its order charges
7193
+ // with ORDER_NOT_PAYABLE (breaking for those). New PaymentError code
7194
+ // ORDER_LINES_INVALID; a priced order's line writes refuse ORDER_LOCKED.
7195
+ version: "1.289.0",
7173
7196
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7174
7197
  hooks: HOOKS,
7175
7198
  primitives: PRIMITIVES,
package/dist/hooks.js CHANGED
@@ -3645,6 +3645,10 @@ export function useInterpretDraft(tableId) {
3645
3645
  * control rather than retrying)
3646
3646
  * - "AGENT_FILES_BUSY" — 503 (the server could not take the files on
3647
3647
  * right now; retry shortly)
3648
+ * - "TURN_IN_PROGRESS" — 409 (the agent is still working on an earlier
3649
+ * message, maybe from another device; nothing
3650
+ * was sent. Give the text back; `sending` stays
3651
+ * true until that run ends)
3648
3652
  * - "AI_QUOTA_EXCEEDED" — 429 (the WORKSPACE is out of AI credit; this
3649
3653
  * does NOT clear by retrying — say so)
3650
3654
  * - "RATE_LIMITED" — 429 (too many turns — retry shortly)
@@ -3656,10 +3660,13 @@ export function useInterpretDraft(tableId) {
3656
3660
  * turn: the server finishes it and the
3657
3661
  * workspace is billed, so say "still
3658
3662
  * working", never "failed"
3659
- * - "CANCELLED" — `cancel()` was called. The user chose it,
3660
- * so render no error at all (the turn is
3661
- * still billed — never imply it stopped)
3663
+ * - "CANCELLED" — `cancel()` ended the send before it reached
3664
+ * the server, or on a host that cannot stop a
3665
+ * run. The user chose it, so render no error
3662
3666
  * - "INTERNAL" — anything else (a 5xx carrying no code)
3667
+ *
3668
+ * `stored` is true when the server kept the message although the turn failed:
3669
+ * it is in `messages`, so do not put the text back in the composer.
3663
3670
  */
3664
3671
  export class AgentError extends Error {
3665
3672
  constructor(code, message, opts) {
@@ -3675,6 +3682,43 @@ function statusOfAgentFailure(err) {
3675
3682
  return err && typeof err.status === "number" ? err.status : null;
3676
3683
  }
3677
3684
 
3685
+ // The server's page size; a thread is read from its END.
3686
+ const AGENT_TAIL_ROWS = 50;
3687
+ // Re-read beside the newest known row, so a long thread costs one read a check.
3688
+ const AGENT_TAIL_SLACK = 25;
3689
+ // Past the server's own limit on a run.
3690
+ const AGENT_WATCH_MS = 6 * 60 * 1000;
3691
+ // How long a lost send waits for the connection before it is given back.
3692
+ const AGENT_LOST_MS = 60 * 1000;
3693
+ const AGENT_LOST_CODES = ["NETWORK", "TIMEOUT", "GATEWAY_TIMEOUT"];
3694
+
3695
+ const agentPause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
3696
+ const agentBackoff = (failures) => Math.min(15000, 2000 * 2 ** failures);
3697
+ // A refusal a later try cannot change.
3698
+ const agentRefused = (status) => status >= 400 && status < 500 && status !== 429;
3699
+
3700
+ /** The newest rows of a thread and whether a run is in progress. */
3701
+ async function readAgentTail(channel, knownTotal) {
3702
+ let offset = Math.max(0, knownTotal - AGENT_TAIL_SLACK);
3703
+ for (let attempt = 0; ; attempt += 1) {
3704
+ const page = await channel.list({ limit: AGENT_TAIL_ROWS, offset });
3705
+ const rows = page && Array.isArray(page.data) ? page.data : [];
3706
+ const meta = (page && page.meta) || {};
3707
+ const total = typeof meta.total === "number" ? meta.total : 0;
3708
+ if (offset + rows.length >= total || attempt === 2) {
3709
+ return { rows, total, running: meta.turn_running === true };
3710
+ }
3711
+ offset = Math.max(0, total - AGENT_TAIL_ROWS);
3712
+ }
3713
+ }
3714
+
3715
+ /** `prior` with the server's rows in their own order; the same array when it lacks none. */
3716
+ function mergeAgentRows(prior, rows) {
3717
+ const has = (list, row) => Boolean(row.id) && list.some((other) => other.id === row.id);
3718
+ if (rows.every((row) => has(prior, row))) return prior;
3719
+ return prior.filter((row) => !has(rows, row)).concat(rows);
3720
+ }
3721
+
3678
3722
  const NO_CONNECTIONS = Object.freeze({
3679
3723
  agentId: null,
3680
3724
  supported: false,
@@ -3717,6 +3761,12 @@ function toAgentError(err) {
3717
3761
  *
3718
3762
  * send(text) → Promise<{ role, content }> the agent's reply
3719
3763
  *
3764
+ * A run lives on the server: leaving, a refresh or a lost connection does not
3765
+ * end it. `sending` is true while one is in progress, on a later mount too, and
3766
+ * its ending lands in `messages` by itself. `cancel()` really stops it where
3767
+ * the host can: `send` then resolves with the stopped row, and what the agent
3768
+ * already changed stays changed.
3769
+ *
3720
3770
  * Sending is IMPERATIVE — no PAID call is ever made on mount; the widget calls
3721
3771
  * `send` from an event handler, and the first `send` opens the conversation, so
3722
3772
  * an author who places the widget and never types costs the workspace nothing.
@@ -3731,6 +3781,8 @@ function toAgentError(err) {
3731
3781
  * each `{ id, role, content, created_at }` with `role` of "user" | "assistant".
3732
3782
  * An assistant message that used a tool also carries `activity` — what the
3733
3783
  * agent DID with the user's data. Render the writes: "done!" is not evidence.
3784
+ * One that ended early carries `outcome` ("stopped" | "failed"): render that and
3785
+ * its `activity`, not its "…" content.
3734
3786
  * The SERVER owns the real transcript and the system prompt: the widget sends
3735
3787
  * one message and can neither read nor set the prompt.
3736
3788
  *
@@ -3801,6 +3853,9 @@ export function useAgent(agentRef, options) {
3801
3853
  // is a different agent and therefore a different decision.
3802
3854
  const suppressResumeRef = useRef(false);
3803
3855
 
3856
+ // The run `sending` reports: this hook's own send, or one found on the server.
3857
+ const runRef = useRef(null);
3858
+
3804
3859
  // A changed binding is a different agent, so neither the open thread nor the
3805
3860
  // transcript carries — leaving the messages would render agent A's
3806
3861
  // conversation underneath agent B.
@@ -3816,25 +3871,138 @@ export function useAgent(agentRef, options) {
3816
3871
  // A different agent is a different decision: leaving the old agent's
3817
3872
  // "new conversation" set would stop this one from ever resuming.
3818
3873
  suppressResumeRef.current = false;
3874
+ // The previous agent's run goes on in its own thread, unwatched.
3875
+ runRef.current = null;
3819
3876
  }
3820
3877
 
3821
- const abortRef = useRef(null);
3878
+ const messagesRef = useRef(messages);
3879
+ messagesRef.current = messages;
3880
+
3881
+ const startRun = useCallback((fields) => {
3882
+ const run = { thread: null, conversationId: null, controller: null, cancelled: false, stopping: false, stored: false, ...fields };
3883
+ runRef.current = run;
3884
+ setSending(true);
3885
+ return run;
3886
+ }, []);
3887
+
3888
+ // A run that is no longer this hook's own changes nothing on screen.
3889
+ const endRun = useCallback((run, failure) => {
3890
+ if (runRef.current !== run) return;
3891
+ runRef.current = null;
3892
+ // A stale thread is recoverable on the next send rather than permanently
3893
+ // broken: drop it so the widget opens a fresh one.
3894
+ if (failure && failure.code === "CONVERSATION_NOT_FOUND") conversationRef.current = null;
3895
+ // A cancel is the user's own choice, so it is not a failure to report.
3896
+ setError(failure && failure.code !== "CANCELLED" ? failure : null);
3897
+ setSending(false);
3898
+ }, []);
3899
+
3900
+ // Reads the thread until the run ends; resolves with the row it ended on, or
3901
+ // null once this hook has left the run.
3902
+ const followRun = useCallback(async (run, channel, firstPage) => {
3903
+ const deadline = Date.now() + AGENT_WATCH_MS;
3904
+ let page = firstPage;
3905
+ let total = page ? page.total : 0;
3906
+ let failures = 0;
3907
+ let lastFailure = null;
3908
+ for (let polls = 0; ; polls += 1) {
3909
+ if (page) {
3910
+ const rows = page.rows;
3911
+ setMessages((prior) => mergeAgentRows(prior, rows));
3912
+ if (run.asked && rows.some(run.asked)) run.stored = true;
3913
+ if (!page.running) {
3914
+ const last = rows[rows.length - 1];
3915
+ if (last && last.role === "user") {
3916
+ throw new AgentError("AI_GENERATION_FAILED", "The agent did not finish");
3917
+ }
3918
+ return last || null;
3919
+ }
3920
+ }
3921
+ if (polls > 0 || page) {
3922
+ if (Date.now() > deadline) throw lastFailure || new AgentError("TIMEOUT", "The agent did not answer in time");
3923
+ await agentPause(failures > 0 ? agentBackoff(failures) : polls < 5 ? 2000 : 4000);
3924
+ if (runRef.current !== run) return null;
3925
+ }
3926
+ page = null;
3927
+ try {
3928
+ page = await readAgentTail(channel, total);
3929
+ total = page.total;
3930
+ failures = 0;
3931
+ lastFailure = null;
3932
+ } catch (err) {
3933
+ if (agentRefused(statusOfAgentFailure(err))) throw toAgentError(err);
3934
+ failures += 1;
3935
+ lastFailure = toAgentError(err);
3936
+ }
3937
+ if (runRef.current !== run) return null;
3938
+ }
3939
+ }, []);
3940
+
3941
+ // A lost send: what became of it can only be told once the thread is readable.
3942
+ const readWhenBack = useCallback(async (run, channel) => {
3943
+ const deadline = Date.now() + AGENT_LOST_MS;
3944
+ for (let failures = 1; ; failures += 1) {
3945
+ try {
3946
+ return await readAgentTail(channel, 0);
3947
+ } catch (err) {
3948
+ if (agentRefused(statusOfAgentFailure(err)) || Date.now() > deadline) throw err;
3949
+ }
3950
+ await agentPause(agentBackoff(failures));
3951
+ if (runRef.current !== run) return null;
3952
+ }
3953
+ }, []);
3954
+
3955
+ const watchRun = useCallback(
3956
+ (run, channel, firstPage) => {
3957
+ followRun(run, channel, firstPage).then(
3958
+ () => endRun(run),
3959
+ (failure) => endRun(run, failure),
3960
+ );
3961
+ },
3962
+ [followRun, endRun],
3963
+ );
3822
3964
 
3823
3965
  const reset = useCallback(() => {
3824
3966
  // Outdates any resume in flight, so its transcript is discarded on arrival.
3825
3967
  resumeGenerationRef.current += 1;
3826
3968
  suppressResumeRef.current = true;
3827
3969
  conversationRef.current = null;
3970
+ // The run goes on in the thread that was left; this is another one.
3971
+ runRef.current = null;
3828
3972
  setMessages([]);
3829
3973
  setError(null);
3830
3974
  setResuming(false);
3975
+ setSending(false);
3831
3976
  }, []);
3832
3977
 
3833
- // Ends the WAIT, not the turn: the abort never reaches the server, which
3834
- // finishes and bills it either way. Never imply the work was stopped.
3835
- const cancel = useCallback(() => {
3836
- const controller = abortRef.current;
3837
- if (controller) controller.abort();
3978
+ const cancel = useCallback(async () => {
3979
+ const run = runRef.current;
3980
+ if (!run || run.stopping) return;
3981
+ setError(null);
3982
+ if (!run.conversationId) {
3983
+ run.cancelled = true;
3984
+ return;
3985
+ }
3986
+ if (typeof run.thread.stop !== "function") {
3987
+ // An older client can only end the wait; the server finishes the turn.
3988
+ if (run.controller) run.controller.abort();
3989
+ return;
3990
+ }
3991
+ run.stopping = true;
3992
+ try {
3993
+ // The message may still be on its way, so an idle answer is asked again.
3994
+ for (const wait of [1000, 2000, 4000, 4000, 4000]) {
3995
+ const answer = await run.thread.stop(run.conversationId);
3996
+ if (!answer || answer.stopping !== false) return;
3997
+ await agentPause(wait);
3998
+ if (runRef.current !== run) return;
3999
+ }
4000
+ setError(new AgentError("INTERNAL", "The run could not be stopped"));
4001
+ } catch (err) {
4002
+ if (runRef.current === run) setError(toAgentError(err));
4003
+ } finally {
4004
+ run.stopping = false;
4005
+ }
3838
4006
  }, []);
3839
4007
 
3840
4008
  // sc-8867 — reopen the caller's most recent thread with this agent.
@@ -3897,7 +4065,7 @@ export function useAgent(agentRef, options) {
3897
4065
  if (!conversationId) return;
3898
4066
  const transcript = thread.messages(conversationId);
3899
4067
  if (!transcript || typeof transcript.list !== "function") return;
3900
- const history = await transcript.list();
4068
+ const history = await readAgentTail(transcript, 0);
3901
4069
  // Re-checked AFTER the awaits: a rebind, an unmount or a reset during
3902
4070
  // the round trip must not adopt this agent's thread under another.
3903
4071
  if (
@@ -3913,10 +4081,10 @@ export function useAgent(agentRef, options) {
3913
4081
  return;
3914
4082
  }
3915
4083
  conversationRef.current = Promise.resolve(conversationId);
3916
- const rows =
3917
- history && Array.isArray(history.data) ? history.data : [];
4084
+ const rows = history.rows;
3918
4085
  // Never clobber a turn a concurrent send already appended.
3919
4086
  if (rows.length > 0) setMessages((prior) => (prior.length > 0 ? prior : rows));
4087
+ if (history.running) watchRun(startRun({ thread, conversationId }), transcript, history);
3920
4088
  } catch {
3921
4089
  // A transcript that will not load is not a failed turn, and the widget
3922
4090
  // is fully usable without it: a visible error here would report a
@@ -3928,12 +4096,15 @@ export function useAgent(agentRef, options) {
3928
4096
 
3929
4097
  return () => {
3930
4098
  cancelled = true;
4099
+ // Left: the run goes on at the server and a later mount finds it again.
4100
+ runRef.current = null;
4101
+ setSending(false);
3931
4102
  // A hung `list()` never settles, so the `finally` above may never run.
3932
4103
  // Without this the next render stays latched on a spinner with the
3933
4104
  // composer disabled — the wedge this whole path exists to avoid.
3934
4105
  setResuming(false);
3935
4106
  };
3936
- }, [available, agentRef]);
4107
+ }, [available, agentRef, startRun, watchRun]);
3937
4108
 
3938
4109
  // sc-16546 — what this agent reads; null until known, or when it reads none.
3939
4110
  const wantsFiles = Boolean(options && options.files === true);
@@ -3976,8 +4147,16 @@ export function useAgent(agentRef, options) {
3976
4147
  .map((file) => (typeof file === "string" ? file : file && file.id))
3977
4148
  .filter((id) => typeof id === "string" && id.length > 0);
3978
4149
 
3979
- setSending(true);
4150
+ // The server would refuse it too: one run at a time in a thread.
4151
+ if (runRef.current) {
4152
+ throw new AgentError("TURN_IN_PROGRESS", "The agent is still working on an earlier message");
4153
+ }
4154
+ const known = new Set(messagesRef.current.map((row) => row.id));
4155
+ const run = startRun({
4156
+ asked: (row) => row.role === "user" && row.content === content && !known.has(row.id),
4157
+ });
3980
4158
  setError(null);
4159
+ let channel = null;
3981
4160
  try {
3982
4161
  const thread = client.conversations(agentId);
3983
4162
  if (!conversationRef.current) {
@@ -3991,49 +4170,73 @@ export function useAgent(agentRef, options) {
3991
4170
  });
3992
4171
  }
3993
4172
  let conversationId;
4173
+ const opening = conversationRef.current;
3994
4174
  try {
3995
4175
  conversationId = await conversationRef.current;
3996
4176
  } catch (err) {
3997
4177
  // A failed open must not wedge the widget on a rejected promise.
3998
- conversationRef.current = null;
4178
+ if (conversationRef.current === opening) conversationRef.current = null;
3999
4179
  throw err;
4000
4180
  }
4001
- const controller =
4002
- typeof AbortController === "function" ? new AbortController() : null;
4003
- abortRef.current = controller;
4004
- const turn = await thread
4005
- .messages(conversationId)
4181
+ if (run.cancelled) throw new AgentError("CANCELLED", "The request was cancelled");
4182
+ run.thread = thread;
4183
+ run.conversationId = conversationId;
4184
+ run.controller = typeof AbortController === "function" ? new AbortController() : null;
4185
+ channel = thread.messages(conversationId);
4186
+ const turn = await channel
4006
4187
  .send(
4007
4188
  fileIds.length > 0 ? { content, file_ids: fileIds } : { content },
4008
- controller ? { signal: controller.signal } : undefined,
4189
+ run.controller ? { signal: run.controller.signal } : undefined,
4009
4190
  );
4010
- abortRef.current = null;
4011
- // A rebind during the round trip makes this the PREVIOUS agent's reply;
4012
- // writing it now would render it under the new one.
4013
- if (agentIdRef.current !== agentId) {
4014
- setSending(false);
4015
- return turn && turn.reply ? turn.reply : null;
4016
- }
4017
- const userMessage = turn && turn.user_message ? turn.user_message : null;
4018
4191
  const reply = turn && turn.reply ? turn.reply : null;
4019
- setMessages((prior) =>
4020
- prior.concat(userMessage ? [userMessage] : [], reply ? [reply] : []),
4021
- );
4022
- setSending(false);
4192
+ // Left meanwhile (reset, rebind): the reply belongs to the other thread.
4193
+ if (runRef.current === run) {
4194
+ setMessages((prior) =>
4195
+ mergeAgentRows(prior, [turn && turn.user_message, reply].filter(Boolean)),
4196
+ );
4197
+ }
4198
+ endRun(run);
4023
4199
  return reply;
4024
4200
  } catch (err) {
4025
4201
  const e = toAgentError(err);
4026
- // A stale thread is recoverable on the next send rather than permanently
4027
- // broken: drop it so the widget opens a fresh one.
4028
- if (e.code === "CONVERSATION_NOT_FOUND") conversationRef.current = null;
4029
- abortRef.current = null;
4030
- // Same rebind guard: a new agent must not inherit the old one's error.
4031
- // A cancel is the user's own choice, so it is not a failure to report.
4032
- if (e.code !== "CANCELLED" && agentIdRef.current === agentId) setError(e);
4033
- setSending(false);
4034
- throw e;
4202
+ const readable = channel && typeof channel.list === "function" && runRef.current === run;
4203
+ if (e.code === "TURN_IN_PROGRESS" && readable) {
4204
+ setError(e);
4205
+ watchRun(run, channel);
4206
+ throw e;
4207
+ }
4208
+ const lost = AGENT_LOST_CODES.includes(e.code) || statusOfAgentFailure(err) === 504;
4209
+ const reread = () => (lost ? readWhenBack(run, channel) : readAgentTail(channel, 0));
4210
+ const page = readable && e.code !== "CANCELLED" ? await reread().catch(() => null) : null;
4211
+ if (!page || runRef.current !== run) {
4212
+ endRun(run, e);
4213
+ throw e;
4214
+ }
4215
+ run.stored = page.rows.some(run.asked);
4216
+ const last = page.rows[page.rows.length - 1];
4217
+ const answered = run.stored && last.role === "assistant" && last.outcome !== "failed";
4218
+ let failure = e;
4219
+ // The server claims a run before it keeps the message, so a lost send may
4220
+ // be the one running without its row being there yet.
4221
+ if (page.running ? lost || run.stored : answered || (lost && run.stored)) {
4222
+ try {
4223
+ const reply = await followRun(run, channel, page);
4224
+ if (run.stored) {
4225
+ endRun(run);
4226
+ return reply;
4227
+ }
4228
+ } catch (ended) {
4229
+ if (run.stored) failure = ended;
4230
+ }
4231
+ } else if (run.stored) {
4232
+ // It failed after keeping the message, and perhaps some steps: show them.
4233
+ setMessages((prior) => mergeAgentRows(prior, page.rows));
4234
+ }
4235
+ if (run.stored) failure.stored = true;
4236
+ endRun(run, failure);
4237
+ throw failure;
4035
4238
  }
4036
- }, []);
4239
+ }, [startRun, endRun, followRun, readWhenBack, watchRun]);
4037
4240
 
4038
4241
  // sc-17588 — the caller's own MCP servers for this agent. Asked only with
4039
4242
  // `{ connections: true }`, so a widget without the control sends nothing.
@@ -4183,6 +4386,7 @@ export function useAgent(agentRef, options) {
4183
4386
  let visibleMessages = messages;
4184
4387
  let visibleError = error;
4185
4388
  let visibleResuming = resuming;
4389
+ let visibleSending = sending;
4186
4390
  if (pendingResetRef.current) {
4187
4391
  pendingResetRef.current = false;
4188
4392
  visibleMessages = [];
@@ -4195,6 +4399,8 @@ export function useAgent(agentRef, options) {
4195
4399
  // loading now rather than showing an empty thread for one frame.
4196
4400
  visibleResuming = available;
4197
4401
  if (resuming !== available) setResuming(available);
4402
+ visibleSending = false;
4403
+ if (sending) setSending(false);
4198
4404
  }
4199
4405
 
4200
4406
  return {
@@ -4202,7 +4408,8 @@ export function useAgent(agentRef, options) {
4202
4408
  cancel,
4203
4409
  reset,
4204
4410
  messages: visibleMessages,
4205
- sending,
4411
+ // This hook's own send, or a run found still in progress on the server.
4412
+ sending: visibleSending,
4206
4413
  // sc-8867 — true only while the stored transcript is being reopened, so a
4207
4414
  // widget shows a loading state instead of an empty thread that is about to
4208
4415
  // fill. Never true for a turn in flight; that is `sending`.
@@ -7304,6 +7511,7 @@ const NON_RETRYABLE_PAYMENT_CODES = new Set([
7304
7511
  "ORDER_ALREADY_PAID",
7305
7512
  "ORDER_NOT_FOUND",
7306
7513
  "ORDER_AMOUNT_MISMATCH",
7514
+ "ORDER_LINES_INVALID",
7307
7515
  "ORDER_NOT_PAYABLE",
7308
7516
  "ORDER_TOTAL_INVALID",
7309
7517
  "PAYMENTS_DISABLED",
@@ -7341,6 +7549,9 @@ const NON_RETRYABLE_PAYMENT_CODES = new Set([
7341
7549
  * or not a whole number of minor units
7342
7550
  * - "ORDER_AMOUNT_MISMATCH" — `amount_cents` was sent and differs from
7343
7551
  * the order's total; omit it
7552
+ * - "ORDER_LINES_INVALID" — the server cannot price the order's lines
7553
+ * (none, a gone or unpriced product, a
7554
+ * quantity outside 1–999, over 100 lines)
7344
7555
  * - "BUYER_EMAIL_INVALID" — a guest's order has no valid email in
7345
7556
  * its buyer-email column; the receipt needs one
7346
7557
  * - "ORDER_PAYMENT_IN_PROGRESS" — another checkout for the order is open
package/dist/index.d.ts CHANGED
@@ -292,11 +292,23 @@ export interface WidgetDatastoreTemplateColumn {
292
292
  * NUMBER only, required once in every table with a `paymentStatus` column
293
293
  * (and only there), and it must be `immutable: true` (not encrypted,
294
294
  * `latestVia` or `copyOf`). The order's total in integer minor units (339 kr
295
- * is 33900) of the workspace's charge currency. The order's creator sets it
296
- * on create, and `requestPayment({ order })` charges it, so omit
297
- * `amount_cents`. Compute it from prices the buyer cannot change.
295
+ * is 33900) of the workspace's charge currency, which the SERVER prices when
296
+ * the charge opens: `{ lines, via }` names the lines table (its suffix) and
297
+ * its write-once relation back to this table. A bare `true` is accepted only
298
+ * where this table has its own `pricedItem`. `requestPayment({ order })`
299
+ * charges the priced total, so omit `amount_cents`; never write a total.
298
300
  */
299
- orderTotal?: boolean;
301
+ orderTotal?: boolean | { lines: string; via: string };
302
+ /** NUMBER only, one per table: a product's price in integer minor units. */
303
+ unitPrice?: boolean;
304
+ /**
305
+ * Single RELATION only, `immutable: true`, one per table, pointing at a table
306
+ * with a `unitPrice`: the item a line is priced by (times its quantity), or
307
+ * on the orders table an item counted once (a shipping option).
308
+ */
309
+ pricedItem?: boolean;
310
+ /** NUMBER only, `immutable: true`, one per table: a line's quantity, 1 to 999 (empty is 1). */
311
+ lineQuantity?: boolean;
300
312
  /**
301
313
  * STRING only, at most one per table, in a table with a `paymentStatus`
302
314
  * column, and it must be `immutable: true` (not encrypted, `latestVia` or
@@ -1666,10 +1678,12 @@ export interface PaymentRequest {
1666
1678
  * column, so never write "paid" yourself; the platform ignores it anyway.
1667
1679
  * Refused with ORDER_NOT_FOUND, ORDER_NOT_PAYABLE or ORDER_ALREADY_PAID, and
1668
1680
  * with the retryable ORDER_PAYMENT_IN_PROGRESS while another checkout is open.
1669
- * The table also needs an order-total column (ORDER_NOT_PAYABLE without
1670
- * one), and the charge is the order's stored total: ORDER_TOTAL_INVALID when
1671
- * it is empty, zero, negative or not whole, and ORDER_AMOUNT_MISMATCH when
1672
- * `amount_cents` differs from it.
1681
+ * The table also needs a server-priced order-total column (ORDER_NOT_PAYABLE
1682
+ * without one, or when the payer could write or create a price). The server prices the
1683
+ * order from its lines and charges that: ORDER_LINES_INVALID when it cannot,
1684
+ * ORDER_TOTAL_INVALID when the total is zero, and ORDER_AMOUNT_MISMATCH when
1685
+ * `amount_cents` differs from it. Once priced, adding or removing a line is
1686
+ * refused with ORDER_LOCKED.
1673
1687
  */
1674
1688
  order?: PaymentOrder;
1675
1689
  }
@@ -1697,7 +1711,7 @@ export interface PaymentResult {
1697
1711
  * `buyerEmail` column holding a valid address (BUYER_EMAIL_INVALID otherwise).
1698
1712
  */
1699
1713
  export interface GuestPaymentRequest {
1700
- /** Optional: the server charges the order's stored total, as for `requestPayment`. */
1714
+ /** Optional: the server prices the order and charges that, as for `requestPayment`. */
1701
1715
  amount_cents?: number;
1702
1716
  currency?: string;
1703
1717
  description: string;
@@ -1845,6 +1859,7 @@ export class PaymentError extends Error {
1845
1859
  | "ORDER_ALREADY_PAID"
1846
1860
  | "ORDER_TOTAL_INVALID"
1847
1861
  | "ORDER_AMOUNT_MISMATCH"
1862
+ | "ORDER_LINES_INVALID"
1848
1863
  | "BUYER_EMAIL_INVALID"
1849
1864
  | "ORDER_PAYMENT_IN_PROGRESS"
1850
1865
  | "ALREADY_OWNED"
@@ -2192,6 +2207,11 @@ export interface AgentMessage {
2192
2207
  activity?: AgentActivity[];
2193
2208
  /** sc-16546 — the files a user message carried, by reference. Absent when none. */
2194
2209
  attachments?: Array<{ file_id: string; name: string; mime_type: string; size_bytes: number }>;
2210
+ /**
2211
+ * sc-18562 — set on an assistant message whose run ended early. `content` is
2212
+ * then "…": render `activity` and a line of your own instead of a bubble.
2213
+ */
2214
+ outcome?: "stopped" | "failed";
2195
2215
  created_at: string;
2196
2216
  }
2197
2217
 
@@ -2239,9 +2259,10 @@ export interface AgentApi {
2239
2259
  */
2240
2260
  send(text: string, options?: { files?: Array<string | { id: string }> }): Promise<AgentMessage | null>;
2241
2261
  /**
2242
- * Stop WAITING for the turn in flight. The abort never reaches the server,
2243
- * which finishes and bills it either way — label the control "stop", not
2244
- * "cancel", and show no error when the user presses it.
2262
+ * Stop the run in progress. `send` then resolves with the stopped row; what
2263
+ * the agent already changed stays changed. A stop that fails sets `error`
2264
+ * while `sending` stays true. On an older host it only ends the wait, and
2265
+ * `send` rejects CANCELLED: show no error for that.
2245
2266
  */
2246
2267
  cancel(): void;
2247
2268
  /**
@@ -2251,6 +2272,7 @@ export interface AgentApi {
2251
2272
  reset(): void;
2252
2273
  /** Oldest first. The SERVER owns the real transcript. */
2253
2274
  messages: AgentMessage[];
2275
+ /** True while a run is in progress, also one this mount found on the server. */
2254
2276
  sending: boolean;
2255
2277
  /**
2256
2278
  * sc-8867 — true only while the caller's most recent thread is being
@@ -3791,6 +3813,7 @@ export class AgentError extends Error {
3791
3813
  | "AGENT_DISABLED"
3792
3814
  | "CONVERSATION_NOT_FOUND"
3793
3815
  | "INVALID_MESSAGE"
3816
+ | "TURN_IN_PROGRESS"
3794
3817
  | "AI_QUOTA_EXCEEDED"
3795
3818
  | "RATE_LIMITED"
3796
3819
  | "AI_UNAVAILABLE"
@@ -3801,6 +3824,8 @@ export class AgentError extends Error {
3801
3824
  | "CANCELLED"
3802
3825
  | "INTERNAL"
3803
3826
  | (string & {});
3827
+ /** True when the server kept the message although the turn failed. */
3828
+ stored?: boolean;
3804
3829
  constructor(code: string, message: string, opts?: { cause?: unknown });
3805
3830
  }
3806
3831
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@colixsystems/widget-sdk",
3
- "version": "0.350.0",
3
+ "version": "0.352.0",
4
4
  "description": "Common widget interface for AppStudio. Implements WidgetManifest, WidgetContext, property schema, and helper hooks.",
5
5
  "repository": {
6
6
  "type": "git",
package/src/contract.js CHANGED
@@ -2259,9 +2259,21 @@ const HOOKS = [
2259
2259
  "it off, so hide the affordance rather than retrying; TIMEOUT means the " +
2260
2260
  "client stopped waiting and the turn is STILL running and billed, so " +
2261
2261
  "say it is taking longer, never that it failed or that they are " +
2262
- "offline; CANCELLED is the user pressing your stop control, so render " +
2263
- "no error at all. Call cancel() to stop waiting -- it ends the WAIT, " +
2264
- "not the turn. NEVER surface a " +
2262
+ "offline; TURN_IN_PROGRESS (409) means the agent is still working on an " +
2263
+ "earlier message, so nothing was sent: put the text back and say they can " +
2264
+ "send it when that one is done; CANCELLED is the user's own choice, so " +
2265
+ "render no error at all. A RUN LIVES ON THE SERVER (sc-18562): leaving the " +
2266
+ "page, a refresh or a lost connection does not end it. `sending` is true " +
2267
+ "while one is in progress, on a later mount too, and its answer lands in " +
2268
+ "`messages` by itself, so gate the composer on `sending` and never resend. " +
2269
+ "cancel() really stops the run (label it 'Stop'): send() then RESOLVES with " +
2270
+ "the stopped row, and changes already made stay made. If the stop fails, " +
2271
+ "`error` is set while `sending` stays true. On an older host cancel() only " +
2272
+ "ends the wait and send() rejects CANCELLED. An assistant message that " +
2273
+ "ended early carries `outcome` ('stopped' | 'failed') and the content '…': " +
2274
+ "render its `activity` and your own line instead of a bubble. A rejection " +
2275
+ "with `stored: true` kept the message in `messages`, so do not put the text " +
2276
+ "back. NEVER surface a " +
2265
2277
  "raw error or the workspace's billing state to an app user. " +
2266
2278
  "RENDER AN ASSISTANT REPLY WITH <RichText value={msg.content} />, " +
2267
2279
  "not <Text>: a model answers in MARKDOWN by default — **bold**, " +
@@ -2305,9 +2317,10 @@ const HOOKS = [
2305
2317
  "Reads ctx.agents.",
2306
2318
  returnShape: {
2307
2319
  send: "(text, { files }?) => Promise<{ id, role, content, created_at } | null>",
2320
+ cancel: "() => void // stops the run; send() resolves with the stopped row",
2308
2321
  reset: "() => void",
2309
- messages: "Array<{ id, conversation_id, role, content, created_at }>",
2310
- sending: "boolean",
2322
+ messages: "Array<{ id, conversation_id, role, content, activity?, outcome?, created_at }>",
2323
+ sending: "boolean // true while a run is in progress, also one found on mount",
2311
2324
  resuming:
2312
2325
  "boolean // true only while the stored transcript is being reopened on mount; show a loading state, not an empty thread",
2313
2326
  error: "AgentError | null",
@@ -2499,11 +2512,11 @@ const HOOKS = [
2499
2512
  signature: "usePayments()",
2500
2513
  returnShape: {
2501
2514
  requestPayment:
2502
- "({ amount_cents?, currency?, description, kind, return_path?, order? }) => Promise<{ id, status, order }> // kind is REQUIRED: \"physical\" | \"service\" | \"digital\" — what is sold; a digital charge is refused in an iOS/Android build (DIGITAL_SALE_NEEDS_STORE_BILLING); amount_cents (minor units) is REQUIRED without order; order: { table_id, record_id } — the order row this pays for, in a table with a payment-status column; the SERVER marks it paid when the payment settles, so never write \"paid\" yourself (refused: ORDER_NOT_FOUND, ORDER_NOT_PAYABLE, ORDER_ALREADY_PAID; ORDER_PAYMENT_IN_PROGRESS is retryable while another checkout for the order is open). The orders table also REQUIRES an order-total column (orderTotal; without one: ORDER_NOT_PAYABLE) and the server charges the total stored on the order: create the order with its total, then pass order and omit amount_cents (if sent it must equal the total; refused, not retryable: ORDER_TOTAL_INVALID when the total is empty, zero, negative or not whole, ORDER_AMOUNT_MISMATCH when amount_cents differs). The total is write-once but written by the order's creator, so compute it from prices the buyer cannot change; host opens hosted Checkout; rejects with PaymentError { code, message, retryable } — render the message when retryable is false, never \"try again\"",
2515
+ "({ amount_cents?, currency?, description, kind, return_path?, order? }) => Promise<{ id, status, order }> // kind is REQUIRED: \"physical\" | \"service\" | \"digital\" — what is sold; a digital charge is refused in an iOS/Android build (DIGITAL_SALE_NEEDS_STORE_BILLING); amount_cents (minor units) is REQUIRED without order; order: { table_id, record_id } — the order row this pays for, in a table with a payment-status column; the SERVER marks it paid when the payment settles, so never write \"paid\" yourself (refused: ORDER_NOT_FOUND, ORDER_NOT_PAYABLE, ORDER_ALREADY_PAID; ORDER_PAYMENT_IN_PROGRESS is retryable while another checkout for the order is open). The orders table also REQUIRES an order-total column the server prices (orderTotal: { lines, via } in the datastoreTemplate; without one: ORDER_NOT_PAYABLE): create the order, then its lines, then pass order and omit amount_cents — the server sums quantity × the products table's unitPrice (plus the order's own pricedItem, e.g. shipping), writes the total and charges it; never compute, write or send a total (if amount_cents is sent it must equal the total; refused, not retryable: ORDER_LINES_INVALID when the lines cannot be priced, ORDER_TOTAL_INVALID when the total is zero, ORDER_AMOUNT_MISMATCH when amount_cents differs; ORDER_NOT_PAYABLE also when the payer could write or create a price). Once priced, the order's lines are fixed (adding or removing one: ORDER_LOCKED); host opens hosted Checkout; rejects with PaymentError { code, message, retryable } — render the message when retryable is false, never \"try again\"",
2503
2516
  getPayment:
2504
2517
  "(paymentId) => Promise<{ id, status, amount_cents, currency, description, order }> // order: { table_id, record_id } | null — read it after returning from Checkout",
2505
2518
  requestGuestPayment:
2506
- "({ amount_cents?, currency?, description, return_path?, order }) => Promise<{ id, status, order }> // a visitor who is NOT signed in buys physical goods (no kind). The orders table needs a payment-status AND an order-total column, as for requestPayment: create the order with its total and omit amount_cents (if sent it must equal the total). order is REQUIRED: create the order row first with useDatastoreMutation().create (the maker lets everyone add rows to the orders table and nobody read them; collect the shipping address and contact there), then pay for it within 15 minutes — only the visitor who created it can. Needs the payments.charge:guest scope too. The orders table needs a buyerEmail column the order is created with: the platform emails the order confirmation there, and an order without a valid address is refused with BUYER_EMAIL_INVALID (not retryable). The host runs a security check and opens hosted Checkout. Refused: TRIAL_RESTRICTED, GUEST_CHECKOUT_LIMIT_REACHED (retryable), CAPTCHA_FAILED / CAPTCHA_UNAVAILABLE (retryable), NOT_FOUND where the shop does not offer guest checkout, plus the requestPayment refusals",
2519
+ "({ amount_cents?, currency?, description, return_path?, order }) => Promise<{ id, status, order }> // a visitor who is NOT signed in buys physical goods (no kind). The orders table needs a payment-status AND a server-priced order-total column, as for requestPayment: create the order, then its lines, and omit amount_cents (if sent it must equal the total). order is REQUIRED: create the order row first with useDatastoreMutation().create (the maker lets everyone add rows to the orders table and nobody read them; collect the shipping address and contact there), then pay for it within 15 minutes — only the visitor who created it can. Needs the payments.charge:guest scope too. The orders table needs a buyerEmail column the order is created with: the platform emails the order confirmation there, and an order without a valid address is refused with BUYER_EMAIL_INVALID (not retryable). The host runs a security check and opens hosted Checkout. Refused: TRIAL_RESTRICTED, GUEST_CHECKOUT_LIMIT_REACHED (retryable), CAPTCHA_FAILED / CAPTCHA_UNAVAILABLE (retryable), NOT_FOUND where the shop does not offer guest checkout, plus the requestPayment refusals",
2507
2520
  getGuestPayment:
2508
2521
  "(paymentId) => Promise<{ id, status, amount_cents, currency, description, order }> // a guest's status read; the host holds the guest's one-time credential, so pass only the id",
2509
2522
  },
@@ -4372,7 +4385,7 @@ const MANIFEST_SCHEMA = {
4372
4385
  type: "object",
4373
4386
  required: false,
4374
4387
  description:
4375
- "Optional. Tables the widget needs, seeded into the workspace at install time. Authors wire them into the widget's `tableRef` properties via the Properties Panel — the SDK does not auto-bind. Limits: 100 tables, 200 columns per table, 100 sample rows per table and 20000 sample cells across the whole template (each row counts the keys it sets, and at least one, summed over every table). RELATION columns address siblings by `targetSuffix` (any table in the same array, in any order; tables may relate to each other both ways). Tables persist across uninstalls. A `tableRef` property may also carry `sharedTable: true`, declaring that the table is the APP'S OWN — the author picks an existing table and the widget seeds nothing for it. That is the correct shape for a widget that reads data it does not own (a chart, a metric, a manager view over another widget's table). `sharedTable` exempts the property from needing a seeded table at publish (`manifest.requiredTableRefsHaveTemplate`) WITHOUT making it optional: the author must still bind one, and the host still refuses to place the widget unbound. Use it instead of dropping `required` — a widget that silently renders an empty tile is the defect it looks like a fix for. sc-7530: a table may also declare `roleGrants` — group-scoped access named SYMBOLICALLY, because a group id belongs to the workspace that installs the widget and could never travel in the manifest. Declare the audiences once at template level as `roles: [{ key, label, description? }]` (key is lowercase kebab, max 32 roles), then per table `roleGrants: [{ role, canRead?, canWrite?, canDelete? }]`. The installing workspace binds each role to one of its own user groups (or has one created) during the install consent step, so a permission model where an admin group does everything and signed-in users only read survives the trip between workspaces. Use `publicGrant` for the two id-less audiences (everyone / any signed-in user) and `roleGrants` for anything that names a group. A role nobody binds simply writes no grant — it never fails the install. sc-7557: a column may declare `encrypted: true` — its values are stored AES-256-GCM encrypted at rest under a per-workspace subkey. The widget still reads and writes PLAINTEXT (the platform encrypts on write, decrypts for end users); studio users see `🔒` instead, and the column cannot be searched, filtered or sorted on. Sample `rows` you seed for it are encrypted the same way. Not valid on `RELATION` — its value is a foreign key the backend must resolve — and publishing one is rejected. An `inheritAcl` RELATION column may add `inheritAclReadOnly: true` — rows then inherit READ access only, so members of the parent read every child and may add children, but change or delete only the rows they created (pair with `grantCreatorPermissions`). A column may declare `defaultValue`, written when a create omits it: `@currentUser` on USER, `@now` on DATE / DATETIME, `@uuid` on UUID (a new random id per row), or a literal of the column's own type (none on FILE, RELATION or USER_GROUP — ids belong to the installing workspace). `defaultLocked: true` on an `@currentUser` / `@now` / `@uuid` default makes the server always stamp it and ignore any client value on create and update, so an author column cannot be forged. `immutable: true` makes a column write-once: a create sets it as usual and any value sent for it on update is ignored (not valid on a MANY_TO_MANY relation). `defaultOnCreate: true` makes every create start the column at its `defaultValue` (or empty without one) whatever the client sends, while an update may change it through the row's normal access, so a creator cannot file a row already approved; it protects only a table whose filers cannot edit their row afterwards, so no `grantCreatorPermissions` there (a required column needs a non-empty default; not on a paymentStatus, latestVia or copyOf column). `paymentStatus: true` makes a STRING or BOOL column the table's payment status (at most one per table; not required, encrypted, immutable or defaulting to paid): the table also needs an `orderTotal` column; a settled `requestPayment({ order: { table_id, record_id } })` for one of its rows writes it (`PAID`, or `true` on a BOOL; `REFUNDED` / `false` after a full refund), and every client value for it is ignored, so a buyer cannot mark their own order paid. `orderTotal: true` makes a NUMBER column the order's total, which a charge for the order bills: integer MINOR units (339 kr is 33900) in the workspace's charge currency, no currency stored. A table with a paymentStatus column REQUIRES exactly one (and it is valid only beside one), and it must be `immutable: true` (not encrypted, latestVia or copyOf). The order's creator writes it on create and a later update is ignored; `requestPayment({ order })` then charges that stored total, so omit `amount_cents`. It fixes the total, not the price: compute it from prices the buyer cannot change. `buyerEmail: true` makes a STRING column the buyer's email address, at most one per table, only in a table with a paymentStatus column, and it must be `immutable: true` (not encrypted, latestVia or copyOf): when a charge marks the order paid the platform emails the buyer an order confirmation (a guest at this address, a signed-in buyer at their account's address), and a refund notice after a full refund, so a widget never sends its own. A guest charge (`requestGuestPayment`) for an order whose table has no buyerEmail column, or whose address is empty or invalid, is refused. A table may declare `presence: true` so the people who share a row see which of each other are online (useOnlineMembers); it takes effect only while the workspace records user activity, and an upgrade that declares it turns it on for the existing table. A table whose rows people join and leave through per-record grants (conversations) may declare `deleteWhenLastMemberLeaves: true`: when a signed-in member giving up their own grant leaves a row with no grant and no table-wide grant lets anyone read it, the row and every row a CASCADE relation ties to it (including rows deleted earlier) are deleted for good. A row that never had a grant (a seeded sample row) is never deleted this way, and a revoke made in the Studio never deletes. An upgrade that declares it turns it on for the existing table. A ONE_TO_ONE / ONE_TO_MANY RELATION may declare `latestVia: \"<relation column on its target that points back>\"` (onDelete left at SET_NULL; that relation must have inheritAcl and be immutable): the server keeps it at the newest row of the target table that points back at this row. A column may declare `copyOf: { via, column }`: the server keeps it equal to `column` on the row the latest-row column `via` points at (same type, or text into text, cut to 140 characters in a STRING column; a copy of an encrypted column must be encrypted, and a copy cannot inheritAcl). Both are written only by the server, in the same write as the related row; a client value is ignored. A table may declare `constraints`, checked on every write for every client and refused as CONSTRAINT_VIOLATION: `unique` ({ columns, partitionColumns?, unlessRelated?: { relation, column } } — waived for rows whose related row has that yes/no column set), `no-overlap` ({ startColumn, endColumn, partitionColumns? }), `related-open` ({ relation, closedColumn } — no row is added, changed or removed while the related row's column is filled) and `related-index` ({ column, relation, listColumn } — the number must be a position in the related row's list). An upgrade adds a declared constraint to an existing table without judging the rows already in it.",
4388
+ "Optional. Tables the widget needs, seeded into the workspace at install time. Authors wire them into the widget's `tableRef` properties via the Properties Panel — the SDK does not auto-bind. Limits: 100 tables, 200 columns per table, 100 sample rows per table and 20000 sample cells across the whole template (each row counts the keys it sets, and at least one, summed over every table). RELATION columns address siblings by `targetSuffix` (any table in the same array, in any order; tables may relate to each other both ways). Tables persist across uninstalls. A `tableRef` property may also carry `sharedTable: true`, declaring that the table is the APP'S OWN — the author picks an existing table and the widget seeds nothing for it. That is the correct shape for a widget that reads data it does not own (a chart, a metric, a manager view over another widget's table). `sharedTable` exempts the property from needing a seeded table at publish (`manifest.requiredTableRefsHaveTemplate`) WITHOUT making it optional: the author must still bind one, and the host still refuses to place the widget unbound. Use it instead of dropping `required` — a widget that silently renders an empty tile is the defect it looks like a fix for. sc-7530: a table may also declare `roleGrants` — group-scoped access named SYMBOLICALLY, because a group id belongs to the workspace that installs the widget and could never travel in the manifest. Declare the audiences once at template level as `roles: [{ key, label, description? }]` (key is lowercase kebab, max 32 roles), then per table `roleGrants: [{ role, canRead?, canWrite?, canDelete? }]`. The installing workspace binds each role to one of its own user groups (or has one created) during the install consent step, so a permission model where an admin group does everything and signed-in users only read survives the trip between workspaces. Use `publicGrant` for the two id-less audiences (everyone / any signed-in user) and `roleGrants` for anything that names a group. A role nobody binds simply writes no grant — it never fails the install. sc-7557: a column may declare `encrypted: true` — its values are stored AES-256-GCM encrypted at rest under a per-workspace subkey. The widget still reads and writes PLAINTEXT (the platform encrypts on write, decrypts for end users); studio users see `🔒` instead, and the column cannot be searched, filtered or sorted on. Sample `rows` you seed for it are encrypted the same way. Not valid on `RELATION` — its value is a foreign key the backend must resolve — and publishing one is rejected. An `inheritAcl` RELATION column may add `inheritAclReadOnly: true` — rows then inherit READ access only, so members of the parent read every child and may add children, but change or delete only the rows they created (pair with `grantCreatorPermissions`). A column may declare `defaultValue`, written when a create omits it: `@currentUser` on USER, `@now` on DATE / DATETIME, `@uuid` on UUID (a new random id per row), or a literal of the column's own type (none on FILE, RELATION or USER_GROUP — ids belong to the installing workspace). `defaultLocked: true` on an `@currentUser` / `@now` / `@uuid` default makes the server always stamp it and ignore any client value on create and update, so an author column cannot be forged. `immutable: true` makes a column write-once: a create sets it as usual and any value sent for it on update is ignored (not valid on a MANY_TO_MANY relation). `defaultOnCreate: true` makes every create start the column at its `defaultValue` (or empty without one) whatever the client sends, while an update may change it through the row's normal access, so a creator cannot file a row already approved; it protects only a table whose filers cannot edit their row afterwards, so no `grantCreatorPermissions` there (a required column needs a non-empty default; not on a paymentStatus, latestVia or copyOf column). `paymentStatus: true` makes a STRING or BOOL column the table's payment status (at most one per table; not required, encrypted, immutable or defaulting to paid): the table also needs an `orderTotal` column; a settled `requestPayment({ order: { table_id, record_id } })` for one of its rows writes it (`PAID`, or `true` on a BOOL; `REFUNDED` / `false` after a full refund), and every client value for it is ignored, so a buyer cannot mark their own order paid. `orderTotal: { lines: \"<lines table suffix>\", via: \"<its relation to this table>\" }` makes a NUMBER column the order's total, which a charge for the order bills: integer MINOR units (339 kr is 33900) in the workspace's charge currency, no currency stored. A table with a paymentStatus column REQUIRES exactly one (and it is valid only beside one), and it must be `immutable: true` (not encrypted, latestVia or copyOf). The SERVER prices it when the charge opens and ignores any client value: Σ over the order's lines of `lineQuantity` × the `unitPrice` of the row the line's `pricedItem` names, plus the order table's own `pricedItem` once (a shipping option). `via` is a write-once ONE_TO_MANY relation on the lines table pointing at this table. A bare `orderTotal: true` is accepted only on an orders table that has its own `pricedItem`; publishing any other unpriced order total is refused (an already published template still installs, and its order charges are refused with ORDER_NOT_PAYABLE). `unitPrice: true` makes a NUMBER column a product's price in minor units (one per table). `pricedItem: true` makes a write-once single RELATION (one per table) to a table with a unitPrice column the item a line or an order is priced by. `lineQuantity: true` makes a write-once NUMBER column (one per table) a line's quantity, a whole number from 1 to 999 (empty is 1). A payer who may edit or create rows in a priced table is refused, and once an order holds its total no line is added or removed (ORDER_LOCKED). `buyerEmail: true` makes a STRING column the buyer's email address, at most one per table, only in a table with a paymentStatus column, and it must be `immutable: true` (not encrypted, latestVia or copyOf): when a charge marks the order paid the platform emails the buyer an order confirmation (a guest at this address, a signed-in buyer at their account's address), and a refund notice after a full refund, so a widget never sends its own. A guest charge (`requestGuestPayment`) for an order whose table has no buyerEmail column, or whose address is empty or invalid, is refused. A table may declare `presence: true` so the people who share a row see which of each other are online (useOnlineMembers); it takes effect only while the workspace records user activity, and an upgrade that declares it turns it on for the existing table. A table whose rows people join and leave through per-record grants (conversations) may declare `deleteWhenLastMemberLeaves: true`: when a signed-in member giving up their own grant leaves a row with no grant and no table-wide grant lets anyone read it, the row and every row a CASCADE relation ties to it (including rows deleted earlier) are deleted for good. A row that never had a grant (a seeded sample row) is never deleted this way, and a revoke made in the Studio never deletes. An upgrade that declares it turns it on for the existing table. A ONE_TO_ONE / ONE_TO_MANY RELATION may declare `latestVia: \"<relation column on its target that points back>\"` (onDelete left at SET_NULL; that relation must have inheritAcl and be immutable): the server keeps it at the newest row of the target table that points back at this row. A column may declare `copyOf: { via, column }`: the server keeps it equal to `column` on the row the latest-row column `via` points at (same type, or text into text, cut to 140 characters in a STRING column; a copy of an encrypted column must be encrypted, and a copy cannot inheritAcl). Both are written only by the server, in the same write as the related row; a client value is ignored. A table may declare `constraints`, checked on every write for every client and refused as CONSTRAINT_VIOLATION: `unique` ({ columns, partitionColumns?, unlessRelated?: { relation, column } } — waived for rows whose related row has that yes/no column set), `no-overlap` ({ startColumn, endColumn, partitionColumns? }), `related-open` ({ relation, closedColumn } — no row is added, changed or removed while the related row's column is filled) and `related-index` ({ column, relation, listColumn } — the number must be a position in the related row's list). An upgrade adds a declared constraint to an existing table without judging the rows already in it.",
4376
4389
  },
4377
4390
  translations: {
4378
4391
  type: "object",
@@ -4528,6 +4541,7 @@ const WIDGET_CONTEXT_SHAPE = {
4528
4541
  description:
4529
4542
  "sc-7991 — injected @colixsystems/agents-client instance. " +
4530
4543
  "{ conversations(agentId) -> { create(), list(query), remove(conversationId), " +
4544
+ "stop(conversationId) -> Promise<{ conversation_id, stopping }> (sc-18562; optional on older hosts), " +
4531
4545
  "messages(conversationId) -> { list(query), send({ content, file_ids? }) } }, " +
4532
4546
  "capabilities(agentId) -> Promise<{ accepts_files, accepted_file_types, max_files, max_pdfs, max_file_bytes, max_total_bytes }>, " +
4533
4547
  "connections(agentId) -> { list(), create({ name, server_url, token }), test(id), remove(id), " +
@@ -7169,7 +7183,16 @@ const CONTRACT = deepFreeze({
7169
7183
  // lint warning flags one that does not.
7170
7184
  // 1.287.0: additive (sc-15765) — `connection` joins `actionScriptGlobals`:
7171
7185
  // the account a per-connection scheduled run is for, null otherwise.
7172
- version: "1.287.0",
7186
+ // 1.288.0: behaviour (sc-18562) — an agent run lives on the server: `sending`
7187
+ // covers a run found on mount, cancel() really stops it and send() resolves
7188
+ // with the stopped row, messages carry `outcome`, and a send during a run
7189
+ // rejects TURN_IN_PROGRESS. A rejection says `stored` when the message was kept.
7190
+ // 1.289.0 (sc-16651): the server prices an order. Template columns
7191
+ // `unitPrice`, `pricedItem`, `lineQuantity` and `orderTotal: { lines, via }`;
7192
+ // an unpriced order total is refused at publish and its order charges
7193
+ // with ORDER_NOT_PAYABLE (breaking for those). New PaymentError code
7194
+ // ORDER_LINES_INVALID; a priced order's line writes refuse ORDER_LOCKED.
7195
+ version: "1.289.0",
7173
7196
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7174
7197
  hooks: HOOKS,
7175
7198
  primitives: PRIMITIVES,