@colixsystems/widget-sdk 0.357.0 → 0.359.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
@@ -58,8 +58,10 @@ The data layer lives in **four separate domain-client packages**, each instantia
58
58
  | **DATASTORE** | `useDatastoreSchema(tableId)` | `{ schema, loading, error, refetch }` | `schema(tableId)` — `datastore.read:<table>` |
59
59
  | **DATASTORE** | `useBoundColumns(tableId, shape, props)` | `{ columns, resolved, missing, loading, error }` | `schema(tableId)` (built on `useDatastoreSchema`) — `datastore.read:<table>`. Resolves author-bound column NAMES from `props` by exact name → case-insensitive name → first unclaimed column matching `shape[key].dataType`, so a column an author renamed after install still resolves instead of `record[props.titleField]` reading `undefined`. `columns` holds the resolved NAME (`record[columns.titleField]`); `resolved` holds the full `Column`; `missing` lists non-`optional` keys that never resolved. Falsy `tableId` collapses to `{ columns: {}, resolved: {}, missing: Object.keys(shape), loading: false, error: null }`. |
60
60
  | **DATASTORE** | `useInterpretDraft(tableId)` | `{ interpret, interpreting, error, result, available }` | `interpret(tableId, body)` — `datastore.read:<table>`. Turns ONE sentence a user typed ("walk at 11 am tomorrow") into DRAFT column values so a form can prefill itself. IMPERATIVE: call `interpret(text, { fields?, timeZone? })` from an event handler, never on mount. It DRAFTS and writes nothing — show the values for review, then submit through `useDatastoreMutation().create`. Resolves to `{ values, unresolved }`; `values` is keyed by column NAME (the shape `create()` takes) and `unresolved` names the fields the sentence did not state. Only text / number / boolean / date / datetime / array columns are drafted — `FILE`, `RELATION`, `USER` and `USER_GROUP` carry ids and are never guessed. Fails closed to an empty draft. **Every call spends the workspace's AI credits** and is rate-limited per actor, so call it once per user action (never on mount or in a render loop); once the workspace runs out the call is refused with a generic 429 — an app user is deliberately **not** told the workspace's billing state, since they have never heard of an AI credit and cannot buy one. Never surface a raw error to the person filling the form: say drafting is unavailable and keep every field editable by hand. `available` is false where the host brokers no interpreter. |
61
- | **AGENTS** | `useAgent(agentRef, { files }?)` | `{ send, cancel, reset, messages, sending, resuming, error, available, acceptsFiles, fileLimits }` | `ctx.agents` — `ai.invoke:*`. Hold a conversation with one of the WORKSPACE's own AI agents (an author-written name + system prompt). Sending is IMPERATIVE: call `send(text)` from an event handler, never on mount — the first send opens the conversation, so a widget nobody types into costs nothing. On mount the hook DOES reopen the caller's most recent thread with this agent, so a refresh or a navigation keeps the conversation instead of starting a blank one; that resume only READS and spends no credit. `resuming` is true while it runs — render a loading state, not an empty thread. `messages` is the running transcript, oldest first. You **cannot** set or read the system prompt, replay an edited transcript, or pick a model: the server assembles every turn from the stored prompt plus the stored history, and `content` is the only thing that reaches the wire. `reset()` drops the thread (a "new chat" affordance), and the new thread is the one a later mount resumes. **Every send spends the workspace's AI credits** and is rate-limited per caller AND per workspace. Rejects with `AgentError`; branch on `.code` — `AI_QUOTA_EXCEEDED` (429) is the workspace's credit ceiling and will NOT clear on a retry, unlike `RATE_LIMITED`, so never offer "try again" for it, and `AGENT_DISABLED` (409) means the author turned it off, so hide the affordance. Never surface a raw error or the workspace's billing state to an app user. `available` is false when no agent is bound or the host brokers none — render a visible unbound state, never a blank box. An assistant message that used a tool also carries **`activity`** — what the agent DID with the user's data: the table it read (with the `search` text and `filters` it read with), or the table and columns it CHANGED (never the values, and never a row the permissions refused). **Render a write.** A reply saying "done!" is not evidence a row was written, and if the agent got it wrong the user has no other way to notice. A talk-only turn omits the key entirely. **Files:** with `{ files: true }` the hook asks once (no credit) whether the agent reads files — `acceptsFiles`, `fileLimits` — and `send(text, { files })` sends Filestore images or PDFs with the turn. |
61
+ | **AGENTS** | `useAgent(agentRef, { files }?)` | `{ send, cancel, reset, messages, sending, resuming, error, available, acceptsFiles, fileLimits }` | `ctx.agents` — `ai.invoke:*`. Hold a conversation with one of the WORKSPACE's own AI agents (an author-written name + system prompt). Sending is IMPERATIVE: call `send(text)` from an event handler, never on mount — the first send opens the conversation, so a widget nobody types into costs nothing. On mount the hook DOES reopen the caller's most recent thread with this agent, so a refresh or a navigation keeps the conversation instead of starting a blank one; that resume only READS and spends no credit. `resuming` is true while it runs — render a loading state, not an empty thread. `messages` is the running transcript, oldest first. You **cannot** set or read the system prompt, replay an edited transcript, or pick a model: the server assembles every turn from the stored prompt plus the stored history, and `content` is the only thing that reaches the wire. `reset()` drops the thread (a "new chat" affordance), and the new thread is the one a later mount resumes. **Every send spends the workspace's AI credits** and is rate-limited per caller AND per workspace. Rejects with `AgentError`; branch on `.code` — `AI_QUOTA_EXCEEDED` (429) is the workspace's credit ceiling and will NOT clear on a retry, unlike `RATE_LIMITED`, so never offer "try again" for it, and `AGENT_DISABLED` (409) means the author turned it off, so hide the affordance. Never surface a raw error or the workspace's billing state to an app user. `available` is false when no agent is bound or the host brokers none — render a visible unbound state, never a blank box. An assistant message that used a tool also carries **`activity`** — what the agent DID with the user's data: the table it read (with the `search` text and `filters` it read with), or the table and columns it CHANGED (never the values, and never a row the permissions refused), with `count` when a create added many rows in one step. **Render a write.** A reply saying "done!" is not evidence a row was written, and if the agent got it wrong the user has no other way to notice. A talk-only turn omits the key entirely. **Files:** with `{ files: true }` the hook asks once (no credit) whether the agent reads files — `acceptsFiles`, `fileLimits` — and `send(text, { files })` sends Filestore images or PDFs with the turn. |
62
62
  | **ACTIONS** | `useAction(actionRef)` | `{ available, run, enqueue, running, result, error }` | `ctx.actions` — `actions.run:*`. Run one of the workspace's Actions from an event handler (never on mount) and read the value it passed to `respond()`, or `enqueue` it to run later with its normal limits and no answer. The Action needs the app trigger. `available` is false when nothing is bound or the host brokers no client. Errors are `ActionError` with a stable `code`. |
63
+ | **CONNECTORS** | `useConnector(connectorRef)` | `{ available, call, calling, error }` | `ctx.connectors` — `connectors.call:*`. Call one operation the workspace listed on an app-callable REST connector and use the answer. Errors are `ConnectorError` with a stable `code`. |
64
+ | **CONNECTORS** | `useConnectorAccount(connectorRef)` | `{ supported, name, mode, canConnect, unavailableReason, accounts, loading, finishing, pending, error, result, connect, disconnect, refresh }` | `ctx.connectors.accounts` — `connectors.accounts:*`. A signed-in app user connects, lists and disconnects their own accounts at the connector's provider; the host runs the sign-in. Call `connect` from a press only and read its outcome from `result`. Errors are `ConnectorError`. |
63
65
  | **DATASTORE** | `useDatastoreMutation(table)` | `{ create, update, delete }` | `records(table).{ create, update (PATCH), delete }` — `datastore.write:*`. A successful write re-reads every query, record, figure and aggregate on that table in every widget on the screen (a run of writes at most once a second, always once more after the last), so never refetch after it, and never write from an effect that re-runs on the data it reads unless a ref or Set marks what it already wrote. **To CLEAR a cell, pass it empty** — `update(id, { when: null })` (also `""` or `[]`) empties that cell and it reads back as `null` (`[]` on an array column). There is no separate clear call, so never write a sentinel such as `0` or a placeholder date to mean "no value". `false` and `0` are values, not clears, and a REQUIRED column cannot be cleared. The result has only create, update and delete; the checker refuses a call to any other key (`datastore-method-unknown`). |
64
66
  | **DATASTORE** | `useDatastoreSubscription(table, handlers, options)` (optional: options) | `{ status }` — `"connecting" \| "live" \| "reconnecting" \| "fallback"` | `records(table).subscribe` — `datastore.read:<table>`. To keep a list, record or figure current, pass `live: true` to its read hook instead (*Live lists*); this hook is for acting on each change. Live `onCreated` / `onUpdated` / `onDeleted` off the realtime socket; never throws, resolving to `{ status: "fallback" }` so the widget polls instead. A whole-table subscribe is gated on read-EVERY-row, because one envelope reaches every subscriber of the table — so for a table governed by per-record grants pass `options.scope`: `{ kind: "record", record_id }` for one row, or `{ kind: "parent", relation_column, record_id }` for the rows whose RELATION column points at that parent (the column must carry `inheritAcl`, else the subscribe reports `"fallback"`). For a live list of the signed-in user's own rows pass `{ kind: "granted" }`: every row they read through a grant to them or one of their groups, plus `onAccessGained(record)` / `onAccessLost({ id })` as rows enter and leave that set. Re-subscribes on the scope's VALUES, so a fresh object literal each render is fine. |
65
67
  | **DATASTORE** | `useTyping(tableId, recordId)` | `{ typingUserIds, setTyping, status }` — status `"connecting" \| "live" \| "unavailable"` | `records(table).typing` — `datastore.read:<table>`. Who else is typing in one record, over the same socket as `useDatastoreSubscription`. Call `setTyping(true)` on every keystroke (throttled to one signal per 3 s; `false` is sent after 5 s idle) and `setTyping(false)` on send, clear or blur. `typingUserIds` lists the OTHER users' ids; each drops out 6 s after their last signal. Needs a signed-in user who can read the record. Never throws: an anonymous visitor, a refused subscription or a host whose client lacks `typing` reads `{ typingUserIds: [], status: "unavailable" }`. Re-subscribes when either id changes. |
@@ -91,7 +93,33 @@ See the design reference for the full architecture: [`docs/architecture/widget-m
91
93
 
92
94
  ## Status
93
95
 
94
- `v0.357.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**.
96
+ `v0.359.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**.
97
+
98
+ ### What's new in 0.359.0 (contract 1.295.0)
99
+
100
+ **New `useConnectorAccount(connectorRef)` hook: an app user connects their own account at an outside service.** The workspace's REST connector signs in with OAuth and allows app users' accounts; the hook lists them, opens the provider's sign-in through the host and disconnects them. Bind it with a `connectorRef` property carrying `use: "accounts"`, which offers the connectors whose app users may add accounts, and declare `connectors.accounts:*` (the linter refuses the hook without it: `scope-required-for-useConnectorAccount`). The hook never calls the outside API; `useConnector` does.
101
+
102
+ ```js
103
+ propertySchema: { connectorId: { type: "connectorRef", use: "accounts", label: "Connector" } },
104
+ requestedScopes: ["connectors.accounts:*"],
105
+ ```
106
+
107
+ ```js
108
+ const { name, mode, canConnect, unavailableReason, accounts, loading, pending, error, result, connect, disconnect, refresh } =
109
+ useConnectorAccount(connectorId);
110
+ ```
111
+
112
+ - `mode` is `"personal"` (one account each, id `"me"`), `"shared"` (members of one group add named accounts with `connect(label)`) or `"off"`.
113
+ - `connect()` opens a sign-in, so call it from a press only. On the web the tab leaves and the promise settles only as `CONNECT_CANCELLED`, when the user goes Back: the page that loads on the way back confirms it (`finishing`) and reports it on `result`. On native it resolves, or rejects `CONNECT_CANCELLED` when dismissed. Read `result` and it works on both.
114
+ - `unavailableReason` is `UNBOUND`, `UNSUPPORTED_HOST`, `SIGN_IN_REQUIRED`, `OFF`, `NOT_IN_GROUP` or `CONNECTOR_NOT_FOUND`, and `null` when connecting works. `error` is a list that could not be read: offer `refresh()`.
115
+ - Each account is `{ id, label, personal, own, canDisconnect, status, connectedAt }`. Offer Disconnect only where `canDisconnect`; `expired` and `error` need a reconnect (`connect` with the same label), `pending` and `awaiting_confirmation` were not finished, `revoked` is not connected.
116
+ - `connect` and `disconnect` reject with a `ConnectorError`. Branch on its `code`: `CONNECT_CANCELLED`, `LABEL_IN_USE`, `TOO_MANY_CONNECTIONS`, `ACCOUNT_IN_USE`, `INVALID_CONNECTION`, `CONNECTION_NOT_FOUND`, `TICKET_USED`, `CONNECTOR_NOT_CONFIGURED`, `NOT_IN_GROUP`, `NOT_AUTHORISED`, `RATE_LIMITED`, `CONNECT_FAILED`, `UNAVAILABLE`.
117
+
118
+ Additive.
119
+
120
+ ### What's new in 0.358.0 (contract 1.294.0)
121
+
122
+ **An agent that added many rows says how many.** A `create_record` entry in an assistant `AgentMessage`'s `activity` may carry `count` when one step added many rows, for example an import from a connected tool. Show it ("Added 487 rows"). With `ok: false` the `count` is 0 and nothing was added. Additive: an entry without `count` is one row, as before.
95
123
 
96
124
  ### What's new in 0.357.0 (contract 1.293.0)
97
125
 
@@ -4183,6 +4211,17 @@ export default function ContactList({ tableId, pageSize }) {
4183
4211
  }
4184
4212
  ```
4185
4213
 
4214
+ ## Shop bag (cart)
4215
+
4216
+ A shop's bag holds what the buyer means to buy until they pay. Build it the same way in every shop.
4217
+
4218
+ - **The bag is its own widget or page, never a placeholder.** It lists each item with its name, options, quantity and price, lets the buyer change the quantity and remove the item, shows a total that updates at once, and links to Checkout. An empty bag says so and links back to the shop. Every widget that adds to the bag or counts it (a header count) reads the same store, so they stay in step.
4219
+ - **A signed-in buyer's bag is a table.** One row per item: the product (a relation to the products table), its options, its quantity, and a buyer USER column that defaults to the signed-in user (`@currentUser`). Give the table creator-only access, so only that buyer can read or change their rows, and query it with the condition `{ column: "buyer", operator: "eq", valueMode: "currentUser" }` so a staff member's view never holds another buyer's rows. Adding a product creates a row, or raises the quantity of the row with the same product and options; changing the quantity updates the row, and Remove deletes it. A refresh, the menu and another device all show the same bag.
4220
+ - **A guest's bag exists only in a shop that takes guest payments.** There a visitor who is not signed in keeps the bag with `useDeviceStorage("bag", [])` as `[{ productId, options, qty }]`: product ids, options and quantities, never a price. Every widget uses that one key. When the guest signs in, the bag widget alone moves it: it copies the device bag, calls `remove()`, then adds each item to the buyer's bag table the way Add does. Other widgets, such as a header count, only read the bag. In a shop where only signed-in buyers pay there is no guest bag: Add shown to a signed-out visitor asks them to sign in with `useNavigation().signIn()`.
4221
+ - **Keep the bag out of the page address.** Never carry it in `useRouteParams()`, a navigation param, `useWidgetRoute` or a wire: the menu link and a refresh lose it, and Back after paying brings it back. Hand a product to the bag by its id.
4222
+ - **Prices come from the products table.** Show each price and the total from the products table, never from the bag. An option that changes the price (a larger size) is its own product row; an option is only a choice that keeps the price. Checkout refuses to start while an item's product is no longer sold, so no order is created for it. It creates the order and one line per bag item with its product, quantity and options (a write-once options column on the lines), then calls `requestPayment({ description, kind, order })` (a guest: `requestGuestPayment({ description, order })`) with no `amount_cents`: the server prices the order from its lines. Pay stays disabled while a payment runs.
4223
+ - **Empty the bag only after a successful payment.** At checkout, tag each bag row with its order (a relation column on the bag table). Whenever the bag loads, delete the rows whose order reads paid, so Back, a refresh, another device and an old success address all show an empty bag. A guest's device bag is cleared with `remove()` once the payment reads `PAID`. A cancelled or failed payment leaves the bag as it was.
4224
+
4186
4225
  ## Cross-platform widgets (single-file vs split)
4187
4226
 
4188
4227
  Every widget runs in **both** the web Player and the exported native (Expo) app.
package/dist/contract.cjs CHANGED
@@ -2240,7 +2240,8 @@ const HOOKS = [
2240
2240
  "{ id, role, content, created_at } with role 'user' | 'assistant'. " +
2241
2241
  "An assistant message that used a tool also carries `activity`: what " +
2242
2242
  "the agent DID — the table it read and the search text and filters it " +
2243
- "read with, or the table and columns it CHANGED. Render a write: a reply saying 'done!' is not evidence a " +
2243
+ "read with, or the table and columns it CHANGED. A create that added many rows " +
2244
+ "in one step carries `count` (absent means one row): say the number. Render a write: a reply saying 'done!' is not evidence a " +
2244
2245
  "row was written, and the user has no other way to notice a mistake. " +
2245
2246
  "A talk-only turn omits the key entirely. " +
2246
2247
  "You CANNOT set the system prompt, replay an edited transcript, " +
@@ -2438,6 +2439,59 @@ const HOOKS = [
2438
2439
  requiredContextSlice: ["connectors.call"],
2439
2440
  scopes: ["connectors.call:*"],
2440
2441
  },
2442
+ {
2443
+ name: "useConnectorAccount",
2444
+ signature: "useConnectorAccount(connectorRef)",
2445
+ description:
2446
+ "Let a signed-in app user connect their own account at the provider " +
2447
+ "behind one of the workspace's REST connectors, so the workspace's " +
2448
+ "Actions can use it. It only manages accounts and never calls the " +
2449
+ "outside API (useConnector does, with the workspace's own credential). " +
2450
+ "Bind it with a `connectorRef` property carrying `use: 'accounts'`. " +
2451
+ "`mode` is the maker's choice: 'personal' (each person has one account, " +
2452
+ "id 'me', used by Actions they start) or 'shared' (members of one group " +
2453
+ "add named accounts every Action can use; connect(label) takes the name: " +
2454
+ "lowercase letters, numbers, - and _, never 'me' or 'default'). " +
2455
+ "connect() opens the provider's sign-in, so call it ONLY from a press, " +
2456
+ "never on mount. On the web the tab leaves and connect() settles only as CONNECT_CANCELLED, when the user goes Back: " +
2457
+ "the page that loads on the way back confirms it (`finishing`) and puts " +
2458
+ "the outcome on `result`. On native it resolves once the account is " +
2459
+ "connected, or rejects CONNECT_CANCELLED when dismissed. So read the " +
2460
+ "outcome from `result`, never from the promise. `accounts` " +
2461
+ "holds the caller's own accounts plus, for a group member in shared " +
2462
+ "mode, everyone's shared ones; show a 'revoked' one as not connected, " +
2463
+ "'pending' and 'awaiting_confirmation' as unfinished, 'expired' and " +
2464
+ "'error' as needing a reconnect (connect again, with the same label), and " +
2465
+ "offer Disconnect only where `canDisconnect`. `unavailableReason` says " +
2466
+ "why connecting is off: UNBOUND, UNSUPPORTED_HOST (the app is older than " +
2467
+ "this hook), SIGN_IN_REQUIRED, OFF, NOT_IN_GROUP or CONNECTOR_NOT_FOUND; " +
2468
+ "render a visible state for each, NEVER a blank box, and keep listing the " +
2469
+ "accounts under OFF and NOT_IN_GROUP. `error` is a failed list: offer " +
2470
+ "refresh(). ConnectorError.code of connect/disconnect/result: " +
2471
+ "CONNECT_CANCELLED, LABEL_IN_USE, TOO_MANY_CONNECTIONS, ACCOUNT_IN_USE, " +
2472
+ "INVALID_CONNECTION (the name), CONNECTION_NOT_FOUND and TICKET_USED (the " +
2473
+ "sign-in expired: try again), CONNECTOR_NOT_CONFIGURED (the app's " +
2474
+ "administrator must fix it), NOT_IN_GROUP, NOT_AUTHORISED, RATE_LIMITED, " +
2475
+ "CONNECT_FAILED. NEVER show an app user a raw error. Reads ctx.connectors.",
2476
+ returnShape: {
2477
+ supported: "boolean // false when this host cannot run the sign-in",
2478
+ name: "string // the connector's name; '' until listed",
2479
+ mode: "'personal' | 'shared' | 'off' | null // null until listed",
2480
+ canConnect: "boolean // false until listed and whenever unavailableReason is set",
2481
+ unavailableReason: "null | 'UNBOUND' | 'UNSUPPORTED_HOST' | 'SIGN_IN_REQUIRED' | 'OFF' | 'NOT_IN_GROUP' | 'CONNECTOR_NOT_FOUND'",
2482
+ accounts: "Array<{ id, label, personal, own, canDisconnect, status, connectedAt }> // status: 'pending' | 'awaiting_confirmation' | 'connected' | 'expired' | 'revoked' | 'error'",
2483
+ loading: "boolean // true while the list is read",
2484
+ finishing: "boolean // true while a web sign-in this page came back from is confirmed",
2485
+ pending: "boolean // true while connect, disconnect or finishing runs; disable the buttons",
2486
+ error: "ConnectorError | null // the list could not be read",
2487
+ result: "null | { error: ConnectorError | null } // the last connect, including a web return",
2488
+ connect: "(label?) => Promise<void> // from a press only; on the web only Back settles it; rejects with ConnectorError",
2489
+ disconnect: "(id) => Promise<void> // rejects with ConnectorError",
2490
+ refresh: "() => Promise<void> // never rejects",
2491
+ },
2492
+ requiredContextSlice: ["connectors.accounts"],
2493
+ scopes: ["connectors.accounts:*"],
2494
+ },
2441
2495
  {
2442
2496
  name: "useDatastoreMutation",
2443
2497
  signature: "useDatastoreMutation(tableId)",
@@ -4580,11 +4634,15 @@ const WIDGET_CONTEXT_SHAPE = {
4580
4634
  "sc-15659 — injected connectors client from @colixsystems/actions-client. " +
4581
4635
  "{ call(connectorId, operation, { params, query, body }) -> Promise<{ status, content_type, body }> }. " +
4582
4636
  "Backs useConnector(). Calls one operation the workspace listed on an app-callable " +
4583
- "connector, as the signed-in caller; the credential is added server-side. Errors carry " +
4637
+ "connector, as the signed-in caller; the credential is added server-side. " +
4638
+ "accounts(connectorId) -> { list(), disconnect(label) } " +
4639
+ "and, where the host runs the sign-in, connect(label) and resumeConnect() -> Promise<null | { error }>, " +
4640
+ "backs useConnectorAccount(). Errors carry " +
4584
4641
  "the server's `code` and `status`. Absent on a host that brokers none, where " +
4585
- "useConnector() degrades to available: false rather than throwing.",
4642
+ "useConnector() degrades to available: false and useConnectorAccount() to " +
4643
+ "UNSUPPORTED_HOST rather than throwing.",
4586
4644
  required: false,
4587
- fields: { call: "function" },
4645
+ fields: { call: "function", accounts: "function" },
4588
4646
  },
4589
4647
  linkPreviews: {
4590
4648
  description:
@@ -5381,6 +5439,7 @@ const FIXED_SCOPES = Object.freeze([
5381
5439
  "ai.invoke:*",
5382
5440
  "actions.run:*",
5383
5441
  "connectors.call:*",
5442
+ "connectors.accounts:*",
5384
5443
  "users.read:*",
5385
5444
  "users.write:*",
5386
5445
  "users.delete:*",
@@ -7208,7 +7267,13 @@ const CONTRACT = deepFreeze({
7208
7267
  // 1.293.0: additive (sc-16652) — the `payment-price-from-page` lint warning
7209
7268
  // flags an order charge whose amount comes from the page address, a
7210
7269
  // wire input or the bag.
7211
- version: "1.293.0",
7270
+ // 1.294.0 (sc-18646): additive — a `create_record` activity entry may carry
7271
+ // `count`, how many rows one step added.
7272
+ // 1.295.0: additive (sc-15764) — `useConnectorAccount(connectorRef)` + the
7273
+ // `connectors.accounts` host client + the `connectors.accounts:*` scope +
7274
+ // `use: "accounts"` on a `connectorRef` property. An app user connects
7275
+ // their own account at a connector's provider.
7276
+ version: "1.295.0",
7212
7277
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7213
7278
  hooks: HOOKS,
7214
7279
  primitives: PRIMITIVES,
package/dist/contract.js CHANGED
@@ -2235,7 +2235,8 @@ const HOOKS = [
2235
2235
  "{ id, role, content, created_at } with role 'user' | 'assistant'. " +
2236
2236
  "An assistant message that used a tool also carries `activity`: what " +
2237
2237
  "the agent DID — the table it read and the search text and filters it " +
2238
- "read with, or the table and columns it CHANGED. Render a write: a reply saying 'done!' is not evidence a " +
2238
+ "read with, or the table and columns it CHANGED. A create that added many rows " +
2239
+ "in one step carries `count` (absent means one row): say the number. Render a write: a reply saying 'done!' is not evidence a " +
2239
2240
  "row was written, and the user has no other way to notice a mistake. " +
2240
2241
  "A talk-only turn omits the key entirely. " +
2241
2242
  "You CANNOT set the system prompt, replay an edited transcript, " +
@@ -2433,6 +2434,59 @@ const HOOKS = [
2433
2434
  requiredContextSlice: ["connectors.call"],
2434
2435
  scopes: ["connectors.call:*"],
2435
2436
  },
2437
+ {
2438
+ name: "useConnectorAccount",
2439
+ signature: "useConnectorAccount(connectorRef)",
2440
+ description:
2441
+ "Let a signed-in app user connect their own account at the provider " +
2442
+ "behind one of the workspace's REST connectors, so the workspace's " +
2443
+ "Actions can use it. It only manages accounts and never calls the " +
2444
+ "outside API (useConnector does, with the workspace's own credential). " +
2445
+ "Bind it with a `connectorRef` property carrying `use: 'accounts'`. " +
2446
+ "`mode` is the maker's choice: 'personal' (each person has one account, " +
2447
+ "id 'me', used by Actions they start) or 'shared' (members of one group " +
2448
+ "add named accounts every Action can use; connect(label) takes the name: " +
2449
+ "lowercase letters, numbers, - and _, never 'me' or 'default'). " +
2450
+ "connect() opens the provider's sign-in, so call it ONLY from a press, " +
2451
+ "never on mount. On the web the tab leaves and connect() settles only as CONNECT_CANCELLED, when the user goes Back: " +
2452
+ "the page that loads on the way back confirms it (`finishing`) and puts " +
2453
+ "the outcome on `result`. On native it resolves once the account is " +
2454
+ "connected, or rejects CONNECT_CANCELLED when dismissed. So read the " +
2455
+ "outcome from `result`, never from the promise. `accounts` " +
2456
+ "holds the caller's own accounts plus, for a group member in shared " +
2457
+ "mode, everyone's shared ones; show a 'revoked' one as not connected, " +
2458
+ "'pending' and 'awaiting_confirmation' as unfinished, 'expired' and " +
2459
+ "'error' as needing a reconnect (connect again, with the same label), and " +
2460
+ "offer Disconnect only where `canDisconnect`. `unavailableReason` says " +
2461
+ "why connecting is off: UNBOUND, UNSUPPORTED_HOST (the app is older than " +
2462
+ "this hook), SIGN_IN_REQUIRED, OFF, NOT_IN_GROUP or CONNECTOR_NOT_FOUND; " +
2463
+ "render a visible state for each, NEVER a blank box, and keep listing the " +
2464
+ "accounts under OFF and NOT_IN_GROUP. `error` is a failed list: offer " +
2465
+ "refresh(). ConnectorError.code of connect/disconnect/result: " +
2466
+ "CONNECT_CANCELLED, LABEL_IN_USE, TOO_MANY_CONNECTIONS, ACCOUNT_IN_USE, " +
2467
+ "INVALID_CONNECTION (the name), CONNECTION_NOT_FOUND and TICKET_USED (the " +
2468
+ "sign-in expired: try again), CONNECTOR_NOT_CONFIGURED (the app's " +
2469
+ "administrator must fix it), NOT_IN_GROUP, NOT_AUTHORISED, RATE_LIMITED, " +
2470
+ "CONNECT_FAILED. NEVER show an app user a raw error. Reads ctx.connectors.",
2471
+ returnShape: {
2472
+ supported: "boolean // false when this host cannot run the sign-in",
2473
+ name: "string // the connector's name; '' until listed",
2474
+ mode: "'personal' | 'shared' | 'off' | null // null until listed",
2475
+ canConnect: "boolean // false until listed and whenever unavailableReason is set",
2476
+ unavailableReason: "null | 'UNBOUND' | 'UNSUPPORTED_HOST' | 'SIGN_IN_REQUIRED' | 'OFF' | 'NOT_IN_GROUP' | 'CONNECTOR_NOT_FOUND'",
2477
+ accounts: "Array<{ id, label, personal, own, canDisconnect, status, connectedAt }> // status: 'pending' | 'awaiting_confirmation' | 'connected' | 'expired' | 'revoked' | 'error'",
2478
+ loading: "boolean // true while the list is read",
2479
+ finishing: "boolean // true while a web sign-in this page came back from is confirmed",
2480
+ pending: "boolean // true while connect, disconnect or finishing runs; disable the buttons",
2481
+ error: "ConnectorError | null // the list could not be read",
2482
+ result: "null | { error: ConnectorError | null } // the last connect, including a web return",
2483
+ connect: "(label?) => Promise<void> // from a press only; on the web only Back settles it; rejects with ConnectorError",
2484
+ disconnect: "(id) => Promise<void> // rejects with ConnectorError",
2485
+ refresh: "() => Promise<void> // never rejects",
2486
+ },
2487
+ requiredContextSlice: ["connectors.accounts"],
2488
+ scopes: ["connectors.accounts:*"],
2489
+ },
2436
2490
  {
2437
2491
  name: "useDatastoreMutation",
2438
2492
  signature: "useDatastoreMutation(tableId)",
@@ -4575,11 +4629,15 @@ const WIDGET_CONTEXT_SHAPE = {
4575
4629
  "sc-15659 — injected connectors client from @colixsystems/actions-client. " +
4576
4630
  "{ call(connectorId, operation, { params, query, body }) -> Promise<{ status, content_type, body }> }. " +
4577
4631
  "Backs useConnector(). Calls one operation the workspace listed on an app-callable " +
4578
- "connector, as the signed-in caller; the credential is added server-side. Errors carry " +
4632
+ "connector, as the signed-in caller; the credential is added server-side. " +
4633
+ "accounts(connectorId) -> { list(), disconnect(label) } " +
4634
+ "and, where the host runs the sign-in, connect(label) and resumeConnect() -> Promise<null | { error }>, " +
4635
+ "backs useConnectorAccount(). Errors carry " +
4579
4636
  "the server's `code` and `status`. Absent on a host that brokers none, where " +
4580
- "useConnector() degrades to available: false rather than throwing.",
4637
+ "useConnector() degrades to available: false and useConnectorAccount() to " +
4638
+ "UNSUPPORTED_HOST rather than throwing.",
4581
4639
  required: false,
4582
- fields: { call: "function" },
4640
+ fields: { call: "function", accounts: "function" },
4583
4641
  },
4584
4642
  linkPreviews: {
4585
4643
  description:
@@ -5376,6 +5434,7 @@ const FIXED_SCOPES = Object.freeze([
5376
5434
  "ai.invoke:*",
5377
5435
  "actions.run:*",
5378
5436
  "connectors.call:*",
5437
+ "connectors.accounts:*",
5379
5438
  "users.read:*",
5380
5439
  "users.write:*",
5381
5440
  "users.delete:*",
@@ -7203,7 +7262,13 @@ const CONTRACT = deepFreeze({
7203
7262
  // 1.293.0: additive (sc-16652) — the `payment-price-from-page` lint warning
7204
7263
  // flags an order charge whose amount comes from the page address, a
7205
7264
  // wire input or the bag.
7206
- version: "1.293.0",
7265
+ // 1.294.0 (sc-18646): additive — a `create_record` activity entry may carry
7266
+ // `count`, how many rows one step added.
7267
+ // 1.295.0: additive (sc-15764) — `useConnectorAccount(connectorRef)` + the
7268
+ // `connectors.accounts` host client + the `connectors.accounts:*` scope +
7269
+ // `use: "accounts"` on a `connectorRef` property. An app user connects
7270
+ // their own account at a connector's provider.
7271
+ version: "1.295.0",
7207
7272
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7208
7273
  hooks: HOOKS,
7209
7274
  primitives: PRIMITIVES,
package/dist/hooks.js CHANGED
@@ -4715,6 +4715,213 @@ export function useConnector(connectorRef) {
4715
4715
  };
4716
4716
  }
4717
4717
 
4718
+ const CONNECTOR_ACCOUNT_MODES = ["personal", "shared", "off"];
4719
+ const CONNECTOR_ACCOUNT_REASONS = { off: "OFF", not_in_group: "NOT_IN_GROUP" };
4720
+ const NO_CONNECTOR_ACCOUNTS = {
4721
+ key: null,
4722
+ listed: null,
4723
+ refused: null,
4724
+ loading: false,
4725
+ finishing: false,
4726
+ changing: 0,
4727
+ error: null,
4728
+ result: null,
4729
+ };
4730
+
4731
+ function toConnectorAccountError(err) {
4732
+ if (err instanceof ConnectorError) return err;
4733
+ const code = err && typeof err.code === "string" && err.code ? err.code : "CONNECT_FAILED";
4734
+ const message = (err && err.message) || "The account request failed";
4735
+ return new ConnectorError(code, message, { cause: err });
4736
+ }
4737
+
4738
+ // A refusal the widget shows as a state of its own rather than a load error.
4739
+ function connectorAccountsRefusal(err) {
4740
+ if (err.status === 401 || err.code === "APP_USER_SESSION_REQUIRED") return "SIGN_IN_REQUIRED";
4741
+ return err.code === "CONNECTOR_NOT_FOUND" ? "CONNECTOR_NOT_FOUND" : null;
4742
+ }
4743
+
4744
+ function connectorAccountFromRow(row) {
4745
+ return {
4746
+ id: row.label,
4747
+ label: row.label,
4748
+ personal: row.personal === true,
4749
+ own: row.own === true,
4750
+ canDisconnect: row.can_disconnect === true,
4751
+ status: row.status,
4752
+ connectedAt: row.connected_at || null,
4753
+ };
4754
+ }
4755
+
4756
+ /**
4757
+ * sc-15764 — the accounts an app user connects at a REST connector's provider.
4758
+ * In "personal" mode each person has one account of their own (id "me"); in
4759
+ * "shared" mode members of one group add named accounts everyone uses.
4760
+ *
4761
+ * connect(label?) → Promise; opens the provider's sign-in through the host.
4762
+ * On web the tab leaves and only Back settles it: the page
4763
+ * loaded on the way back reports it in `result`.
4764
+ * disconnect(id) → Promise; removes one account
4765
+ * refresh() → Promise; reads the list again, never rejects
4766
+ *
4767
+ * `error` is a failed list; `result` is the last connect's outcome, null before
4768
+ * one and `{ error: null }` after a success. Never throws at render.
4769
+ * ConnectorError.code here is one of: UNAVAILABLE, AUTH_REQUIRED,
4770
+ * APP_USER_SESSION_REQUIRED, CONNECTOR_NOT_FOUND, CONNECTOR_NOT_CONFIGURED,
4771
+ * NOT_IN_GROUP, NOT_AUTHORISED, INVALID_CONNECTION, LABEL_IN_USE,
4772
+ * ACCOUNT_IN_USE, TOO_MANY_CONNECTIONS, INVALID_RETURN_URL,
4773
+ * CONNECTION_NOT_FOUND, TICKET_USED, CONNECT_CANCELLED, CONNECT_FAILED,
4774
+ * RATE_LIMITED; any other server code passes through.
4775
+ *
4776
+ * Routes through `ctx.connectors.accounts`, where the host runs the sign-in
4777
+ * round trip, so the Player and the Expo export behave identically.
4778
+ */
4779
+ export function useConnectorAccount(connectorRef) {
4780
+ const ctx = useWidgetContextOrThrow("useConnectorAccount");
4781
+ const bound = typeof connectorRef === "string" && connectorRef.trim() !== "";
4782
+ const brokered = Boolean(ctx.connectors) && typeof ctx.connectors.accounts === "function";
4783
+ // An older baked host lists accounts but cannot run the sign-in.
4784
+ let supported = brokered;
4785
+ if (bound && brokered) {
4786
+ try {
4787
+ supported = typeof ctx.connectors.accounts(connectorRef).connect === "function";
4788
+ } catch {
4789
+ supported = false;
4790
+ }
4791
+ }
4792
+ const usable = bound && supported;
4793
+ // A sign-in or a late session restore asks again.
4794
+ const key = usable ? `${connectorRef}|${(ctx.user && ctx.user.id) || ""}` : null;
4795
+
4796
+ const clientRef = useRef(null);
4797
+ clientRef.current = usable ? ctx.connectors : null;
4798
+ // One object per binding, so an A→B→A rebind never takes A's late answer.
4799
+ const bindingRef = useRef(null);
4800
+ const [state, setState] = useState(NO_CONNECTOR_ACCOUNTS);
4801
+
4802
+ const patch = useCallback((binding, change) => {
4803
+ if (bindingRef.current !== binding) return;
4804
+ setState((prior) => ({ ...prior, ...change(prior) }));
4805
+ }, []);
4806
+
4807
+ const load = useCallback(
4808
+ async (binding) => {
4809
+ const turn = ++binding.turn;
4810
+ const latest = () => binding.turn === turn;
4811
+ patch(binding, () => ({ loading: true, error: null }));
4812
+ // A sign-in this page came back from is finished before the list, so
4813
+ // the list already shows it; the host answers it once per page load.
4814
+ if (!binding.resume) {
4815
+ binding.resume = (async () => {
4816
+ let landed = null;
4817
+ try {
4818
+ const api = clientRef.current.accounts(binding.connectorId);
4819
+ if (typeof api.resumeConnect !== "function") return;
4820
+ patch(binding, () => ({ finishing: true }));
4821
+ landed = await api.resumeConnect();
4822
+ } catch (error) {
4823
+ landed = { error };
4824
+ }
4825
+ patch(binding, (prior) => ({
4826
+ finishing: false,
4827
+ result: landed ? { error: landed.error ? toConnectorAccountError(landed.error) : null } : prior.result,
4828
+ }));
4829
+ })();
4830
+ }
4831
+ await binding.resume;
4832
+ if (bindingRef.current !== binding || !latest()) return;
4833
+ try {
4834
+ const listed = await clientRef.current.accounts(binding.connectorId).list();
4835
+ if (latest()) patch(binding, () => ({ listed: listed || {}, refused: null, loading: false }));
4836
+ } catch (err) {
4837
+ if (!latest()) return;
4838
+ const refused = connectorAccountsRefusal(err || {});
4839
+ // A blip keeps what was already shown.
4840
+ patch(binding, (prior) => ({
4841
+ listed: refused ? null : prior.listed,
4842
+ refused: refused || prior.refused,
4843
+ loading: false,
4844
+ error: refused ? null : toConnectorAccountError(err),
4845
+ }));
4846
+ }
4847
+ },
4848
+ [patch],
4849
+ );
4850
+
4851
+ useEffect(() => {
4852
+ if (!key) return undefined;
4853
+ const binding = { connectorId: connectorRef, turn: 0, resume: null };
4854
+ bindingRef.current = binding;
4855
+ setState({ ...NO_CONNECTOR_ACCOUNTS, key, loading: true });
4856
+ load(binding);
4857
+ return () => {
4858
+ bindingRef.current = null;
4859
+ };
4860
+ // eslint-disable-next-line react-hooks/exhaustive-deps
4861
+ }, [key, load]);
4862
+
4863
+ const refresh = useCallback(async () => {
4864
+ const binding = bindingRef.current;
4865
+ if (binding) await load(binding);
4866
+ }, [load]);
4867
+
4868
+ const change = useCallback(
4869
+ async (run, { reports }) => {
4870
+ const binding = bindingRef.current;
4871
+ const client = clientRef.current;
4872
+ if (!binding || !client) {
4873
+ throw new ConnectorError("UNAVAILABLE", "Connecting accounts is not available here");
4874
+ }
4875
+ patch(binding, (prior) => ({
4876
+ changing: prior.changing + 1,
4877
+ result: reports ? null : prior.result,
4878
+ }));
4879
+ let failure = null;
4880
+ try {
4881
+ await run(client.accounts(binding.connectorId));
4882
+ } catch (err) {
4883
+ failure = toConnectorAccountError(err);
4884
+ }
4885
+ if (reports) patch(binding, () => ({ result: { error: failure } }));
4886
+ const listing = bindingRef.current === binding ? load(binding) : null;
4887
+ // A success resolves once the list shows it.
4888
+ if (!failure) await listing;
4889
+ patch(binding, (prior) => ({ changing: prior.changing - 1 }));
4890
+ if (failure) throw failure;
4891
+ },
4892
+ [load, patch],
4893
+ );
4894
+
4895
+ const connect = useCallback((label) => change((api) => api.connect(label), { reports: true }), [change]);
4896
+ const disconnect = useCallback((id) => change((api) => api.disconnect(id), { reports: false }), [change]);
4897
+
4898
+ // The first render after a rebind precedes its effect.
4899
+ const current = key && state.key === key ? state : { ...NO_CONNECTOR_ACCOUNTS, loading: usable };
4900
+ const { listed } = current;
4901
+ let unavailableReason = current.refused;
4902
+ if (!bound) unavailableReason = "UNBOUND";
4903
+ else if (!supported) unavailableReason = "UNSUPPORTED_HOST";
4904
+ else if (listed && listed.can_connect !== true) {
4905
+ unavailableReason = CONNECTOR_ACCOUNT_REASONS[listed.unavailable_reason] || "OFF";
4906
+ }
4907
+ return {
4908
+ supported,
4909
+ name: (listed && listed.name) || "",
4910
+ mode: listed && CONNECTOR_ACCOUNT_MODES.includes(listed.app_user_accounts) ? listed.app_user_accounts : null,
4911
+ canConnect: Boolean(listed) && unavailableReason === null,
4912
+ unavailableReason,
4913
+ accounts: listed && Array.isArray(listed.connections) ? listed.connections.map(connectorAccountFromRow) : [],
4914
+ loading: current.loading,
4915
+ finishing: current.finishing,
4916
+ pending: current.finishing || current.changing > 0,
4917
+ error: current.error,
4918
+ result: current.result,
4919
+ connect,
4920
+ disconnect,
4921
+ refresh,
4922
+ };
4923
+ }
4924
+
4718
4925
  /**
4719
4926
  * Datastore mutation hook. Returns { create, update, delete }, each method
4720
4927
  * returning a Promise. Routes through the injected
package/dist/index.d.ts CHANGED
@@ -126,6 +126,12 @@ export interface WidgetPropertyDef {
126
126
  * Placing the widget binds the property to the connector its install created.
127
127
  */
128
128
  template?: string;
129
+ /**
130
+ * `connectorRef` only: what the widget does with the connector. "call" (the
131
+ * default) lists those callable from the app, for useConnector(); "accounts"
132
+ * those whose app users add their own accounts, for useConnectorAccount().
133
+ */
134
+ use?: "call" | "accounts";
129
135
  ui?: {
130
136
  widget?: "textarea" | "slider" | "code";
131
137
  group?: string;
@@ -1019,6 +1025,8 @@ export interface WidgetContext<TProps = unknown> {
1019
1025
  /** sc-15659 — injected @colixsystems/actions-client backing useConnector(). */
1020
1026
  connectors?: {
1021
1027
  call(connectorId: string, operation: string, args?: ConnectorCallArgs): Promise<ConnectorCallResult>;
1028
+ /** sc-15764 — backs useConnectorAccount(); optional on older hosts. */
1029
+ accounts?(connectorId: string): unknown;
1022
1030
  };
1023
1031
  /** Injected @colixsystems/link-preview-client backing useLinkPreview(). */
1024
1032
  linkPreviews?: { get(url: string): Promise<LinkPreview> };
@@ -2249,6 +2257,8 @@ export interface AgentActivity {
2249
2257
  table?: string;
2250
2258
  record_id?: string;
2251
2259
  fields?: string[];
2260
+ /** On a `create_record` that added many rows in one step: how many it added. */
2261
+ count?: number;
2252
2262
  /** A read's own search text: what the agent looked FOR, never what it found. */
2253
2263
  search?: string;
2254
2264
  /** A read's own filter conditions, as the agent asked for them. */
@@ -2431,6 +2441,63 @@ export interface ConnectorApi {
2431
2441
  */
2432
2442
  export function useConnector(connectorRef: string | null | undefined): ConnectorApi;
2433
2443
 
2444
+ export interface ConnectorAccount {
2445
+ /** The label; "me" for the caller's personal account. */
2446
+ id: string;
2447
+ label: string;
2448
+ /** Belongs to one app user, rather than shared by everyone. */
2449
+ personal: boolean;
2450
+ /** The caller connected it. */
2451
+ own: boolean;
2452
+ canDisconnect: boolean;
2453
+ status: "pending" | "awaiting_confirmation" | "connected" | "expired" | "revoked" | "error";
2454
+ connectedAt: string | null;
2455
+ }
2456
+
2457
+ export interface ConnectorAccountApi {
2458
+ /** False when this host cannot run the sign-in. */
2459
+ supported: boolean;
2460
+ /** The connector's name; "" until listed. */
2461
+ name: string;
2462
+ /** The maker's choice; null until listed. */
2463
+ mode: "personal" | "shared" | "off" | null;
2464
+ /** False until listed and whenever `unavailableReason` is set. */
2465
+ canConnect: boolean;
2466
+ unavailableReason:
2467
+ | null
2468
+ | "UNBOUND"
2469
+ | "UNSUPPORTED_HOST"
2470
+ | "SIGN_IN_REQUIRED"
2471
+ | "OFF"
2472
+ | "NOT_IN_GROUP"
2473
+ | "CONNECTOR_NOT_FOUND";
2474
+ accounts: ConnectorAccount[];
2475
+ loading: boolean;
2476
+ /** True while a web sign-in this page came back from is confirmed. */
2477
+ finishing: boolean;
2478
+ /** True while connect, disconnect or finishing runs. */
2479
+ pending: boolean;
2480
+ /** The list could not be read. */
2481
+ error: ConnectorError | null;
2482
+ /** The last connect's outcome, including a web return; null before one. */
2483
+ result: { error: ConnectorError | null } | null;
2484
+ /**
2485
+ * Open the provider's sign-in, from a press only. `label` names a shared
2486
+ * account. On the web the tab leaves and only Back settles this; read `result`.
2487
+ */
2488
+ connect(label?: string): Promise<void>;
2489
+ disconnect(id: string): Promise<void>;
2490
+ /** Read the list again; never rejects. */
2491
+ refresh(): Promise<void>;
2492
+ }
2493
+
2494
+ /**
2495
+ * sc-15764 — let a signed-in app user connect their own account at the
2496
+ * provider behind a REST connector. The widget needs `connectors.accounts:*`
2497
+ * in `requestedScopes`.
2498
+ */
2499
+ export function useConnectorAccount(connectorRef: string | null | undefined): ConnectorAccountApi;
2500
+
2434
2501
  // REQ-RT-07 realtime subscription transport state.
2435
2502
  export type DatastoreSubscriptionStatus =
2436
2503
  | "connecting"
@@ -3853,6 +3920,8 @@ export class AgentError extends Error {
3853
3920
  * sc-15659 — structured error thrown by `useConnector().call`. Branch on
3854
3921
  * `code`: `OPERATION_NOT_ALLOWED`, `CONNECTOR_NOT_FOUND` and
3855
3922
  * `CONNECTOR_SETUP_INCOMPLETE` will not clear on a retry, `RATE_LIMITED` will.
3923
+ * sc-15764 — `useConnectorAccount()` rejects and reports with it too, under
3924
+ * the codes from `APP_USER_SESSION_REQUIRED` to `CONNECT_FAILED`.
3856
3925
  * Never show an app user the raw message.
3857
3926
  */
3858
3927
  export class ConnectorError extends Error {
@@ -3869,6 +3938,19 @@ export class ConnectorError extends Error {
3869
3938
  | "UPSTREAM_ERROR"
3870
3939
  | "UPSTREAM_TIMEOUT"
3871
3940
  | "CONNECTOR_FAILED"
3941
+ | "APP_USER_SESSION_REQUIRED"
3942
+ | "CONNECTOR_NOT_CONFIGURED"
3943
+ | "NOT_IN_GROUP"
3944
+ | "NOT_AUTHORISED"
3945
+ | "INVALID_CONNECTION"
3946
+ | "LABEL_IN_USE"
3947
+ | "ACCOUNT_IN_USE"
3948
+ | "TOO_MANY_CONNECTIONS"
3949
+ | "INVALID_RETURN_URL"
3950
+ | "CONNECTION_NOT_FOUND"
3951
+ | "TICKET_USED"
3952
+ | "CONNECT_CANCELLED"
3953
+ | "CONNECT_FAILED"
3872
3954
  | (string & {});
3873
3955
  constructor(code: string, message: string, opts?: { cause?: unknown });
3874
3956
  }
package/dist/index.js CHANGED
@@ -41,6 +41,7 @@ export {
41
41
  useAgent,
42
42
  useAction,
43
43
  useConnector,
44
+ useConnectorAccount,
44
45
  useAsset,
45
46
  useAssetsByTag,
46
47
  useBundledAsset,
@@ -41,6 +41,7 @@ export {
41
41
  useAgent,
42
42
  useAction,
43
43
  useConnector,
44
+ useConnectorAccount,
44
45
  useAsset,
45
46
  useAssetsByTag,
46
47
  useBundledAsset,
package/dist/linter.cjs CHANGED
@@ -873,6 +873,16 @@ function _scopeRules(source, manifest) {
873
873
  snippet: "",
874
874
  });
875
875
  }
876
+ // sc-15764 — DISCLOSURE, as above: the server gate is the app-user JWT plus
877
+ // the connector's own app-user accounts mode.
878
+ if (/\buseConnectorAccount\s*\(/.test(source) && !declared.has("connectors.accounts:*")) {
879
+ findings.push({
880
+ rule: "scope-required-for-useConnectorAccount",
881
+ label: "useConnectorAccount() requires `connectors.accounts:*` in manifest.requestedScopes",
882
+ line: 0,
883
+ snippet: "",
884
+ });
885
+ }
876
886
  const lines = source.split(/\r?\n/);
877
887
  let firedUsersWrite = false;
878
888
  let firedUsersDelete = false;
package/dist/linter.js CHANGED
@@ -868,6 +868,16 @@ function _scopeRules(source, manifest) {
868
868
  snippet: "",
869
869
  });
870
870
  }
871
+ // sc-15764 — DISCLOSURE, as above: the server gate is the app-user JWT plus
872
+ // the connector's own app-user accounts mode.
873
+ if (/\buseConnectorAccount\s*\(/.test(source) && !declared.has("connectors.accounts:*")) {
874
+ findings.push({
875
+ rule: "scope-required-for-useConnectorAccount",
876
+ label: "useConnectorAccount() requires `connectors.accounts:*` in manifest.requestedScopes",
877
+ line: 0,
878
+ snippet: "",
879
+ });
880
+ }
871
881
  const lines = source.split(/\r?\n/);
872
882
  let firedUsersWrite = false;
873
883
  let firedUsersDelete = false;
@@ -36,6 +36,7 @@ const VALID_TYPES = new Set([
36
36
  "actionRef",
37
37
  // sc-15659: `connectorRef` picks one of the workspace's app-callable REST
38
38
  // connectors, a bare id a widget passes to `useConnector`. Remapped likewise.
39
+ // sc-15764: `use: "accounts"` picks one whose app users add accounts instead.
39
40
  "connectorRef",
40
41
  // REQ-WDG-PAGEREF: `pageRef` is a page picker that emits a bare AppPage
41
42
  // UUID into the page JSON. Renders a page `<select>` in the Studio
@@ -90,6 +91,9 @@ const VALID_TYPES = new Set([
90
91
  /** The propertySchema field types, for documentation generated from this list. */
91
92
  export const PROPERTY_TYPES = Object.freeze([...VALID_TYPES]);
92
93
 
94
+ /** What a `connectorRef` property picks a connector for; "call" when unset. */
95
+ const CONNECTOR_REF_USES = ["call", "accounts"];
96
+
93
97
  function validateDef(def, path, errors) {
94
98
  if (!isPlainObject(def)) {
95
99
  errors.push(`${path}: must be an object`);
@@ -104,6 +108,13 @@ function validateDef(def, path, errors) {
104
108
  if (def.description !== undefined && typeof def.description !== "string") {
105
109
  errors.push(`${path}.description: must be a string when present`);
106
110
  }
111
+ if (def.use !== undefined) {
112
+ if (def.type !== "connectorRef") {
113
+ errors.push(`${path}.use: only a connectorRef property takes it`);
114
+ } else if (!CONNECTOR_REF_USES.includes(def.use)) {
115
+ errors.push(`${path}.use: must be one of ${CONNECTOR_REF_USES.join(", ")}`);
116
+ }
117
+ }
107
118
  if (def.enum !== undefined) {
108
119
  if (!Array.isArray(def.enum)) {
109
120
  errors.push(`${path}.enum: must be an array`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@colixsystems/widget-sdk",
3
- "version": "0.357.0",
3
+ "version": "0.359.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
@@ -2235,7 +2235,8 @@ const HOOKS = [
2235
2235
  "{ id, role, content, created_at } with role 'user' | 'assistant'. " +
2236
2236
  "An assistant message that used a tool also carries `activity`: what " +
2237
2237
  "the agent DID — the table it read and the search text and filters it " +
2238
- "read with, or the table and columns it CHANGED. Render a write: a reply saying 'done!' is not evidence a " +
2238
+ "read with, or the table and columns it CHANGED. A create that added many rows " +
2239
+ "in one step carries `count` (absent means one row): say the number. Render a write: a reply saying 'done!' is not evidence a " +
2239
2240
  "row was written, and the user has no other way to notice a mistake. " +
2240
2241
  "A talk-only turn omits the key entirely. " +
2241
2242
  "You CANNOT set the system prompt, replay an edited transcript, " +
@@ -2433,6 +2434,59 @@ const HOOKS = [
2433
2434
  requiredContextSlice: ["connectors.call"],
2434
2435
  scopes: ["connectors.call:*"],
2435
2436
  },
2437
+ {
2438
+ name: "useConnectorAccount",
2439
+ signature: "useConnectorAccount(connectorRef)",
2440
+ description:
2441
+ "Let a signed-in app user connect their own account at the provider " +
2442
+ "behind one of the workspace's REST connectors, so the workspace's " +
2443
+ "Actions can use it. It only manages accounts and never calls the " +
2444
+ "outside API (useConnector does, with the workspace's own credential). " +
2445
+ "Bind it with a `connectorRef` property carrying `use: 'accounts'`. " +
2446
+ "`mode` is the maker's choice: 'personal' (each person has one account, " +
2447
+ "id 'me', used by Actions they start) or 'shared' (members of one group " +
2448
+ "add named accounts every Action can use; connect(label) takes the name: " +
2449
+ "lowercase letters, numbers, - and _, never 'me' or 'default'). " +
2450
+ "connect() opens the provider's sign-in, so call it ONLY from a press, " +
2451
+ "never on mount. On the web the tab leaves and connect() settles only as CONNECT_CANCELLED, when the user goes Back: " +
2452
+ "the page that loads on the way back confirms it (`finishing`) and puts " +
2453
+ "the outcome on `result`. On native it resolves once the account is " +
2454
+ "connected, or rejects CONNECT_CANCELLED when dismissed. So read the " +
2455
+ "outcome from `result`, never from the promise. `accounts` " +
2456
+ "holds the caller's own accounts plus, for a group member in shared " +
2457
+ "mode, everyone's shared ones; show a 'revoked' one as not connected, " +
2458
+ "'pending' and 'awaiting_confirmation' as unfinished, 'expired' and " +
2459
+ "'error' as needing a reconnect (connect again, with the same label), and " +
2460
+ "offer Disconnect only where `canDisconnect`. `unavailableReason` says " +
2461
+ "why connecting is off: UNBOUND, UNSUPPORTED_HOST (the app is older than " +
2462
+ "this hook), SIGN_IN_REQUIRED, OFF, NOT_IN_GROUP or CONNECTOR_NOT_FOUND; " +
2463
+ "render a visible state for each, NEVER a blank box, and keep listing the " +
2464
+ "accounts under OFF and NOT_IN_GROUP. `error` is a failed list: offer " +
2465
+ "refresh(). ConnectorError.code of connect/disconnect/result: " +
2466
+ "CONNECT_CANCELLED, LABEL_IN_USE, TOO_MANY_CONNECTIONS, ACCOUNT_IN_USE, " +
2467
+ "INVALID_CONNECTION (the name), CONNECTION_NOT_FOUND and TICKET_USED (the " +
2468
+ "sign-in expired: try again), CONNECTOR_NOT_CONFIGURED (the app's " +
2469
+ "administrator must fix it), NOT_IN_GROUP, NOT_AUTHORISED, RATE_LIMITED, " +
2470
+ "CONNECT_FAILED. NEVER show an app user a raw error. Reads ctx.connectors.",
2471
+ returnShape: {
2472
+ supported: "boolean // false when this host cannot run the sign-in",
2473
+ name: "string // the connector's name; '' until listed",
2474
+ mode: "'personal' | 'shared' | 'off' | null // null until listed",
2475
+ canConnect: "boolean // false until listed and whenever unavailableReason is set",
2476
+ unavailableReason: "null | 'UNBOUND' | 'UNSUPPORTED_HOST' | 'SIGN_IN_REQUIRED' | 'OFF' | 'NOT_IN_GROUP' | 'CONNECTOR_NOT_FOUND'",
2477
+ accounts: "Array<{ id, label, personal, own, canDisconnect, status, connectedAt }> // status: 'pending' | 'awaiting_confirmation' | 'connected' | 'expired' | 'revoked' | 'error'",
2478
+ loading: "boolean // true while the list is read",
2479
+ finishing: "boolean // true while a web sign-in this page came back from is confirmed",
2480
+ pending: "boolean // true while connect, disconnect or finishing runs; disable the buttons",
2481
+ error: "ConnectorError | null // the list could not be read",
2482
+ result: "null | { error: ConnectorError | null } // the last connect, including a web return",
2483
+ connect: "(label?) => Promise<void> // from a press only; on the web only Back settles it; rejects with ConnectorError",
2484
+ disconnect: "(id) => Promise<void> // rejects with ConnectorError",
2485
+ refresh: "() => Promise<void> // never rejects",
2486
+ },
2487
+ requiredContextSlice: ["connectors.accounts"],
2488
+ scopes: ["connectors.accounts:*"],
2489
+ },
2436
2490
  {
2437
2491
  name: "useDatastoreMutation",
2438
2492
  signature: "useDatastoreMutation(tableId)",
@@ -4575,11 +4629,15 @@ const WIDGET_CONTEXT_SHAPE = {
4575
4629
  "sc-15659 — injected connectors client from @colixsystems/actions-client. " +
4576
4630
  "{ call(connectorId, operation, { params, query, body }) -> Promise<{ status, content_type, body }> }. " +
4577
4631
  "Backs useConnector(). Calls one operation the workspace listed on an app-callable " +
4578
- "connector, as the signed-in caller; the credential is added server-side. Errors carry " +
4632
+ "connector, as the signed-in caller; the credential is added server-side. " +
4633
+ "accounts(connectorId) -> { list(), disconnect(label) } " +
4634
+ "and, where the host runs the sign-in, connect(label) and resumeConnect() -> Promise<null | { error }>, " +
4635
+ "backs useConnectorAccount(). Errors carry " +
4579
4636
  "the server's `code` and `status`. Absent on a host that brokers none, where " +
4580
- "useConnector() degrades to available: false rather than throwing.",
4637
+ "useConnector() degrades to available: false and useConnectorAccount() to " +
4638
+ "UNSUPPORTED_HOST rather than throwing.",
4581
4639
  required: false,
4582
- fields: { call: "function" },
4640
+ fields: { call: "function", accounts: "function" },
4583
4641
  },
4584
4642
  linkPreviews: {
4585
4643
  description:
@@ -5376,6 +5434,7 @@ const FIXED_SCOPES = Object.freeze([
5376
5434
  "ai.invoke:*",
5377
5435
  "actions.run:*",
5378
5436
  "connectors.call:*",
5437
+ "connectors.accounts:*",
5379
5438
  "users.read:*",
5380
5439
  "users.write:*",
5381
5440
  "users.delete:*",
@@ -7203,7 +7262,13 @@ const CONTRACT = deepFreeze({
7203
7262
  // 1.293.0: additive (sc-16652) — the `payment-price-from-page` lint warning
7204
7263
  // flags an order charge whose amount comes from the page address, a
7205
7264
  // wire input or the bag.
7206
- version: "1.293.0",
7265
+ // 1.294.0 (sc-18646): additive — a `create_record` activity entry may carry
7266
+ // `count`, how many rows one step added.
7267
+ // 1.295.0: additive (sc-15764) — `useConnectorAccount(connectorRef)` + the
7268
+ // `connectors.accounts` host client + the `connectors.accounts:*` scope +
7269
+ // `use: "accounts"` on a `connectorRef` property. An app user connects
7270
+ // their own account at a connector's provider.
7271
+ version: "1.295.0",
7207
7272
  sharedTranslationKeys: SHARED_TRANSLATION_KEYS,
7208
7273
  hooks: HOOKS,
7209
7274
  primitives: PRIMITIVES,