@simpleplatform/sdk 2.5.0 → 3.0.1

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
@@ -10,6 +10,53 @@ Install the SDK using [pnpm](https://pnpm.io):
10
10
  pnpm add @simpleplatform/sdk
11
11
  ```
12
12
 
13
+ ## Upgrading from 2.x to 3
14
+
15
+ Version 3 is the first release that carries the Space calls added after 2.5.0.
16
+ One of those changes renamed how a Space connects, which is why this is a major.
17
+
18
+ **A Space changes these names:**
19
+
20
+ | 2.x | 3 |
21
+ | ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
22
+ | `import { connectSpace } from '@simpleplatform/sdk/space'` | `import { connect } from '@simpleplatform/sdk/space'` |
23
+ | `await connectSpace({ targetOrigin })` | `await connect({ targetOrigin })` |
24
+ | `connectSpace({ targetOrigin, window: fake })` in a test | `connect({ targetOrigin })`. It reads `globalThis.window`, so a test sets a browser-like global instead. |
25
+ | `ConnectSpaceOptions` | `ConnectOptions` |
26
+ | `SpaceWindowLike`, `SpaceMessageEvent` | No longer exported. A test declares its own. |
27
+
28
+ **A test that builds the client by hand** adds what the client gained, or it
29
+ stops type checking: `navigation`, `ui`, and `open` beside `current` under
30
+ `records` (for example `records: { current: vi.fn(), open: vi.fn() }`).
31
+
32
+ **Two behaviours change with no change in your code:**
33
+
34
+ - `connect()` sets `overscroll-behavior-y: none` on the Space's root element,
35
+ so the page no longer bounces at its top and bottom edge. A Space that wants
36
+ the bounce sets the style back after it connects.
37
+ - An AI call (`extract`, `summarize`, `transcribePages`) refuses a
38
+ `transcription` option other than `'standard'` or `'precise'`. Version 2
39
+ ignored any value. An Action is otherwise unchanged.
40
+
41
+ **A platform that embeds Spaces** must send a well-formed handshake: a
42
+ `runtime` that is not `{ url, version }` with an `http` or `https` URL is
43
+ ignored and the connection stays pending, and a malformed `form` or `formInfo`
44
+ on a record reply is refused as `invalid_response`. The Simple Platform already
45
+ sends both correctly.
46
+
47
+ **New in 3:**
48
+
49
+ - For a Space: platform tabs (`simple.ui.tabs`, with a count and its tone),
50
+ header actions and a header status, platform toasts, `simple.records.open()`,
51
+ `simple.navigation.open()`, and the bridge the UI Kit's managed `RecordForm`
52
+ and `RecordActivity` use.
53
+ - For an Action: `tasks.create()` from `@simpleplatform/sdk/tasks`, and the
54
+ `transcription` option on the AI calls.
55
+
56
+ Each new Space call needs a platform that supports it. On an older platform
57
+ tabs, the header, toasts and `records.open()` fail as `unavailable`, and
58
+ `navigation.open()` is ignored. The section for each call below says so.
59
+
13
60
  ## Quick Start
14
61
 
15
62
  Create your first Simple Platform action:
@@ -31,28 +78,25 @@ simple.Handle(async (request) => {
31
78
 
32
79
  The TypeScript SDK is organized into focused modules for different capabilities:
33
80
 
34
- | Module | Import | Purpose |
35
- | ------------ | ------------------------------ | ------------------------------------------------------- |
36
- | **Core** | `@simpleplatform/sdk` | Request handling and action execution |
37
- | **AI** | `@simpleplatform/sdk/ai` | AI operations (extract, summarize, transcribe) |
38
- | **GraphQL** | `@simpleplatform/sdk/graphql` | Database queries and mutations |
39
- | **HTTP** | `@simpleplatform/sdk/http` | External HTTP requests |
40
- | **Security** | `@simpleplatform/sdk/security` | Security policy authoring |
41
- | **Settings** | `@simpleplatform/sdk/settings` | Application settings retrieval |
42
- | **Storage** | `@simpleplatform/sdk/storage` | File upload, and reading a stored file's bytes |
43
- | **Space** | `@simpleplatform/sdk/space` | Records, data, tasks, documents, and actions in a Space |
81
+ | **Core** | `@simpleplatform/sdk` | Request handling and action execution |
82
+ | **AI** | `@simpleplatform/sdk/ai` | AI operations (extract, summarize, transcribe) |
83
+ | **GraphQL** | `@simpleplatform/sdk/graphql` | Database queries and mutations |
84
+ | **HTTP** | `@simpleplatform/sdk/http` | External HTTP requests |
85
+ | **Security** | `@simpleplatform/sdk/security` | Security policy authoring |
86
+ | **Settings** | `@simpleplatform/sdk/settings` | Application settings retrieval |
87
+ | **Storage** | `@simpleplatform/sdk/storage` | File upload, and reading a stored file's bytes |
88
+ | **Tasks** | `@simpleplatform/sdk/tasks` | Creating tasks from server actions |
89
+ | **Space** | `@simpleplatform/sdk/space` | Record, data, document, task, UI, and action capabilities in a Space |
44
90
 
45
91
  ## Embedded Spaces
46
92
 
47
- Use the explicit Space subpaths inside an embedded browser Space. The package
48
- root remains the Action/WASM API, so Action code never imports browser globals
49
- by accident.
93
+ Use the Space subpath inside a browser Space. The package root remains the
94
+ Action/WASM API, so Action code never imports browser globals by accident.
50
95
 
51
96
  ```typescript
52
- import { connectSpace } from '@simpleplatform/sdk/space'
97
+ import { connect } from '@simpleplatform/sdk/space'
53
98
 
54
- const hostOrigin = new URL(document.referrer).origin
55
- const simple = await connectSpace({ targetOrigin: hostOrigin })
99
+ const simple = await connect({ targetOrigin: new URL(document.referrer).origin })
56
100
  const record = await simple.records.current()
57
101
 
58
102
  await record.update({ first_name: 'Ada' }) // Stages values and runs update Behavior.
@@ -65,11 +109,222 @@ if (!result.ok) {
65
109
  ```
66
110
 
67
111
  Connect once when the Space starts and reuse the returned client. One embedded iframe has one host MessagePort handshake.
112
+ `targetOrigin` is the host's origin, not a full URL. If the embedding setup
113
+ does not provide a referrer, supply the host origin from the Space's trusted
114
+ configuration.
115
+
116
+ `simple.records.current()` returns the platform-owned record for the current
117
+ record page. Its handle exposes immutable snapshots, `update(values)`, and
118
+ `submit()`. The host enforces permissions and runs Record Behaviors; the Space
119
+ only renders the returned state. Snapshots may also include `formInfo` for
120
+ behavior-produced form-level guidance.
68
121
 
69
- `records.current()` returns the platform-owned record for the current record
70
- page. Its handle exposes immutable snapshots, `update(values)`, and `submit()`.
71
- The host enforces permissions and runs Record Behaviors; the Space only renders
72
- the returned state.
122
+ ### Open another managed record
123
+
124
+ `simple.records.open()` requests an independently managed record by its
125
+ application, table, and record IDs in both Record Space and general Space. The
126
+ host resolves and authorizes the target; the supplied IDs identify a record but
127
+ do not grant access. The target uses the table's standard form.
128
+
129
+ ```ts
130
+ const related = await simple.records.open({
131
+ appId: 'com.example.crm',
132
+ recordId: 'CON000123',
133
+ tableName: 'contacts',
134
+ })
135
+
136
+ if (simple.context.kind === 'record') {
137
+ const current = await simple.records.current()
138
+ // A Space can render <RecordForm record={current} /> and
139
+ // <RecordForm record={related} /> at the same time.
140
+ }
141
+
142
+ await related.update({ status: 'active' })
143
+ const result = await related.submit()
144
+ if (!result.ok)
145
+ console.log(related.snapshot().errors)
146
+ ```
147
+
148
+ Each handle has independent values, validation, behavior, and submit state.
149
+ Each `submit()` saves only that handle; multiple records are not an atomic
150
+ transaction. Opening the same target more than once in one Space connection
151
+ returns the same live handle and session. The host disposes opened sessions
152
+ when the Space connection ends; there is no per-record close method. Opening
153
+ the route-owned record itself rejects with `already_current`; use
154
+ `simple.records.current()` for it.
155
+ `open()` requires a host that negotiated the records capability; when that
156
+ transport is absent, `open()` returns a structured `unavailable` error. In
157
+ general Space context, `records.current()` remains unavailable while `open()`
158
+ succeeds whenever records transport was negotiated. An older host may still
159
+ support `current()` through the existing `record` capability while lacking
160
+ `open()`. Missing and inaccessible records return the same generic
161
+ `target_unavailable` error.
162
+
163
+ To work with another record, use `simple.records.open()` with its exact target:
164
+
165
+ ```ts
166
+ const related = await simple.records.open({
167
+ appId: 'dev.simple.ui_fixtures',
168
+ recordId: 'UIF000002',
169
+ tableName: 'ui_fixture_records',
170
+ })
171
+ await related.update({ status: 'Ready' })
172
+ const saved = await related.submit()
173
+ ```
174
+
175
+ Opened handles have the same behavior-aware update and submit workflow as the
176
+ route record. The host authorizes the target, owns an independent session, and
177
+ reuses it for repeated opens of the same target during one Space connection.
178
+ It disposes opened sessions when that connection closes; there is no public
179
+ `close()` method. `records.open()` is available in Record and standalone Spaces
180
+ when the host negotiates the `records` capability. If that capability is absent,
181
+ the call rejects with `SpaceProtocolError` code `unavailable`. The route record
182
+ cannot be opened again as a secondary session (`already_current`).
183
+
184
+ ### Managed record UI and header actions (pre-release)
185
+
186
+ The companion UI Kit currently implements a managed React form for Record
187
+ Spaces:
188
+
189
+ ```tsx
190
+ <RecordForm record={record} />
191
+ ```
192
+
193
+ It renders the complete Simple form without exposing field schemas, editor
194
+ registries, document/reference/secret internals, or Record Behavior timing as
195
+ public APIs. When a Space needs fully custom presentation, keep using the
196
+ record handle's `snapshot()`, `update()`, and `submit()` commands.
197
+
198
+ Record Spaces can replace the platform main actions in the header while
199
+ mounted:
200
+
201
+ ```ts
202
+ simple.ui.header.actions.set([
203
+ {
204
+ id: 'start-call',
205
+ label: 'Start call',
206
+ onClick: async () => startCall(),
207
+ type: 'primary',
208
+ },
209
+ ])
210
+ ```
211
+
212
+ Promise-returning callbacks show button loading automatically. `actions.set([])`
213
+ renders no main actions. While a custom Record Space is active, this replaces
214
+ the platform `Update` button and persisted View Actions; those defaults return
215
+ when the Space unloads or the user selects the standard view. The full
216
+ pre-release interface and examples live in the
217
+ [`@simpleplatform/ui-kit` README](../space-ui/README.md).
218
+
219
+ A header action owns its own save feedback. `record.submit()` returns validation
220
+ state without choosing UI; call `simple.ui.toast.show()` when the Space should
221
+ also show a platform toast. `RecordForm` continues to display detailed field
222
+ and form messages inline.
223
+
224
+ A Record Space can also show one status beside the record title:
225
+
226
+ ```ts
227
+ simple.ui.header.status.set({
228
+ description: 'A reviewer needs to check this record.',
229
+ label: 'Needs review',
230
+ tone: 'warning',
231
+ })
232
+
233
+ simple.ui.header.status.set(null) // Clear the status
234
+ ```
235
+
236
+ The label is non-blank and limited to 80 characters. Tones are `neutral`,
237
+ `info`, `success`, `warning`, and `danger`; the optional description is for
238
+ screen readers. Hosts that do not negotiate `headerStatus` reject this call
239
+ with an `unavailable` error. Header status is negotiated separately, so an
240
+ older host can continue to support header actions without supporting status.
241
+
242
+ ### Show a platform toast
243
+
244
+ Any Space can show feedback with Simple's existing toast presenter and theme:
245
+
246
+ ```ts
247
+ simple.ui.toast.show({
248
+ description: 'Your changes are ready.',
249
+ title: 'Saved',
250
+ })
251
+
252
+ simple.ui.toast.show({
253
+ description: 'The changes could not be saved.',
254
+ variant: 'destructive',
255
+ })
256
+ ```
257
+
258
+ At least one of `title` or `description` is required, and both are plain text.
259
+ Titles are limited to 160 characters and descriptions to 1,000. The supported
260
+ variants are `default` and `destructive`. React content and toast action
261
+ callbacks are not sent across the iframe boundary.
262
+
263
+ ### Record Space tabs
264
+
265
+ Record Spaces can declare tabs in the platform record header:
266
+
267
+ ```ts
268
+ const { selectedTabId } = await simple.ui.tabs.set({
269
+ onChange: (tabId) => {
270
+ console.log(`Active tab changed to ${tabId}`)
271
+ },
272
+ tabs: [
273
+ { icon: 'layout-dashboard', id: 'overview', title: 'Overview' },
274
+ { badge: 3, badgeTone: 'warning', icon: 'message-square', id: 'messages', title: 'Messages' },
275
+ { badge: 'New', icon: 'file-text', id: 'documents', title: 'Documents' },
276
+ ],
277
+ })
278
+
279
+ // Programmatically select a declared tab
280
+ await simple.ui.tabs.select('messages')
281
+ ```
282
+
283
+ Tabs are configured with up to 32 tabs and a required `onChange` callback. An
284
+ empty list clears the current declaration and resolves with
285
+ `{ selectedTabId: null }`.
286
+ Each tab requires an `id` (1–64 characters matching `^[a-z0-9][a-z0-9_-]{0,63}$`)
287
+ and a non-blank `title` (up to 80 characters), with optional `default: true`,
288
+ optional kebab-case Lucide `icon`, and optional `badge` (non-blank text up to 20
289
+ characters or a finite non-negative integer). A count can also set `badgeTone`
290
+ to `neutral`, `info`, `success`, `warning`, or `danger`; without it, the count
291
+ keeps its neutral appearance. At most one tab may set `default: true`; if none
292
+ is specified, the first tab defaults to active.
293
+
294
+ Older hosts that do not recognize `badgeTone` ignore it and display the count
295
+ with the neutral appearance.
296
+
297
+ The host negotiates `protocols.tabs: [1]` and owns selection and URL state.
298
+ Registration uses `ui.tabs.set`, which assigns a `registrationRequestId` and
299
+ acknowledges the initial `selectedTabId` without firing `onChange`. Host-to-Space
300
+ selection changes are delivered via canonical `SPACE_UI_TABS_SELECTION_CHANGED` with
301
+ `{ registrationRequestId, selectedTabId }` and routed to `onChange`. Events for
302
+ superseded registrations are dropped immediately.
303
+
304
+ Programmatic selection uses `ui.tabs.select`, sending `{ registrationRequestId, tabId }`.
305
+ Selecting the already-active tab resolves immediately without wire traffic.
306
+ Selecting an inactive declared tab resolves after host acknowledgement and reaches
307
+ the `onChange` callback once, deduplicating the response and event. Both methods fail
308
+ with structured `SpaceProtocolError` code `'unavailable'` outside a record Space or
309
+ when the tabs capability was not negotiated.
310
+
311
+ ### Open a platform page
312
+
313
+ Ask the host to open a host-relative platform path from any Space:
314
+
315
+ ```ts
316
+ simple.navigation.open({ path: '/om/<application>/<table>/<record>' })
317
+ simple.navigation.open({ path: '/tasks/<task>', target: 'new-tab' })
318
+ ```
319
+
320
+ `'same-tab'` opens the path in the platform tab the Space is shown in (a Space
321
+ cannot navigate its own frame); `'new-tab'` opens it in a new browser tab. The
322
+ target defaults to `'same-tab'`.
323
+ These are the platform's own names, not the browser's `_self` and `_blank`:
324
+ the platform's navigation message already carried them, and they leave room
325
+ for platform targets a browser has no name for.
326
+ `open()` returns `void` as soon as the request is posted. The host gives no
327
+ confirmation, and a host without the navigation handler ignores the message.
73
328
 
74
329
  ### Space context
75
330
 
@@ -93,17 +348,28 @@ switch (simple.context.kind) {
93
348
  The two exact context forms are `{ kind: 'standalone' }` and
94
349
  `{ kind: 'record', applicationId, tableName, recordId }`. There is no
95
350
  `unknown` context variant. A missing or malformed context rejects
96
- `connectSpace()` with `SpaceProtocolError` code `invalid_response`.
351
+ `connect({ targetOrigin })` with `SpaceProtocolError` code `invalid_response`.
352
+
353
+ `connect({ targetOrigin })` works in any embedded Space, including standalone dashboards
354
+ and tools. In a non-record Space, `simple.data` remains available and
355
+ `simple.records.open()` succeeds whenever the records capability was negotiated,
356
+ while `simple.records.current()` rejects with `SpaceProtocolError` code
357
+ `unavailable` and explains that the current record requires a record view.
358
+ In an older host, `records.current()` can remain available through the `record`
359
+ capability while `records.open()` requires the newer `records` capability.
97
360
 
98
- `connectSpace()` works in any embedded Space, including standalone dashboards
99
- and tools. In a non-record Space, `simple.data` remains available while
100
- `simple.records.current()` rejects with `SpaceProtocolError` code `unavailable`
101
- and explains that the Space must be configured as a record view.
361
+ When `connect()` runs in the Space document, it disables vertical root
362
+ overscroll bounce. Normal scrolling inside the Space remains enabled.
102
363
 
103
364
  Each capability beyond `simple.data` is negotiated with the host when the Space
104
365
  connects. A capability the host did not negotiate rejects with
105
366
  `SpaceProtocolError` code `unavailable` when it is called, and sends nothing.
106
367
 
368
+ The same `connect({ targetOrigin })` and `simple.records.current()` vocabulary is
369
+ reserved for future publicly hosted Spaces. That transport and its
370
+ authentication model are not implemented yet; authors should not add
371
+ portal-specific connection code now.
372
+
107
373
  ### Space data access
108
374
 
109
375
  Use `simple.data` for application data that is not the record form currently
@@ -131,9 +397,21 @@ const result = await simple.data.mutate<{ insert_demo__note: { id: string } }>(
131
397
  ```
132
398
 
133
399
  Use `record.update()` and `record.submit()` for writes to the current record.
134
- Those commands preserve Record Behaviors, validation, documents, and the shared
135
- record state used by the platform header. `simple.data.mutate()` is for other
136
- authorized application data; it must not be used to bypass a record workflow.
400
+ Those commands preserve Record Behaviors, validation, permissions, and the
401
+ shared record state used by the platform. The managed `RecordForm` coordinates
402
+ its specialized document-field workflow through Simple's private host adapter.
403
+ For a customer-owned upload workflow, stage a file through the public document
404
+ API:
405
+
406
+ ```ts
407
+ const { handle } = await simple.documents.stage({ file })
408
+ ```
409
+
410
+ The returned handle describes a staged upload; staging does not attach the file
411
+ to a record. The managed `RecordForm` continues to own its specialized
412
+ document-field workflow through Simple's private host adapter.
413
+ `simple.data.mutate()` is for other authorized application data and must not
414
+ bypass the record workflow.
137
415
 
138
416
  ### Space tasks
139
417
 
@@ -281,28 +559,57 @@ refused `reply()` arrives the same way, with the service's own code in
281
559
  `reply()` again with the same arguments resends the kept message rather than
282
560
  posting it twice.
283
561
 
284
- ### Space documents
562
+ #### Starting a task after other tasks
285
563
 
286
- `simple.documents.stage()` stores a file without attaching it to any record and
287
- returns its handle. The host uploads it, so a large file never travels inside
288
- an action request. The file's bytes are transferred to the host, not copied.
564
+ To make a task wait for others, create the others first, then list them under
565
+ `_metadata.start_after` in the new task's `input`:
289
566
 
290
567
  ```typescript
291
- const picker = document.querySelector<HTMLInputElement>('#packet')!
292
- const { handle } = await simple.documents.stage({ file: picker.files![0] })
293
-
294
- // A plain Blob has no name of its own, so it needs one.
295
- await simple.documents.stage({
296
- file: new Blob([csv]),
297
- mimeType: 'text/csv',
298
- name: 'quantities.csv',
568
+ const terms = await simple.tasks.create({ input: { packet: 'DOC000001' }, taskTypeId: 'TTY000003', title: 'Read the terms' })
569
+ const parties = await simple.tasks.create({ input: { packet: 'DOC000001' }, taskTypeId: 'TTY000004', title: 'Read the parties' })
570
+
571
+ const { task: summary } = await simple.tasks.create({
572
+ input: {
573
+ _metadata: {
574
+ start_after: [
575
+ { task_id: terms.task.id }, // Waits until this task has completed.
576
+ { on: ['approved', 'declined'], task_id: parties.task.id }, // Waits until it is in either state.
577
+ ],
578
+ },
579
+ packet: 'DOC000001',
580
+ },
581
+ taskTypeId: 'TTY000009',
582
+ title: 'Summarise the packet',
299
583
  })
300
584
  ```
301
585
 
302
- The handle is `{ file_hash, filename, mime_type, size, storage_path, scope? }`.
303
- `name` defaults to a `File`'s own name, and `mimeType` to the file's type, then
304
- to `application/octet-stream`. A staged document is not attached to anything
305
- yet; attach its handle through the workflow that owns the record.
586
+ - `_metadata` is reserved. The platform owns it, its shape is fixed, and a member
587
+ it does not know is refused. A task type's input schema must not declare it:
588
+ the rest of `input` is checked against that schema as if `_metadata` were not
589
+ there. It counts toward the 32,768-byte limit.
590
+ - `start_after` is a list of entries `{ task_id, on }`. `task_id` names an
591
+ existing task, and each task may be listed once. `on` is optional and names
592
+ states of the listed task's own task type that end it (a state that maps to
593
+ `completed`, `cancelled`, or `failed`). Left out, it means the states that map
594
+ to `completed`.
595
+ - The new task is created `queued`, and nothing runs for it and no model is
596
+ called until every listed task has ended in a state its entry allows. There
597
+ is no time limit. A listed task that has only stopped and is `waiting` keeps
598
+ the new task waiting; reply to that task to carry it on.
599
+ - If a listed task ends in a state its entry does not allow, or no longer
600
+ exists, the platform cancels the new task. Create another one.
601
+ - When the new task runs, its doer, the AI that does the work, is given the
602
+ `read-task-output` tool. The tool reads a listed task's status and output,
603
+ and only for the listed tasks. The platform adds it by itself; the task type
604
+ does not need to declare it.
605
+ - A create the platform refuses rejects as described above, with
606
+ `error.code` `task_rejected` and `details.code` `TASK_INPUT_INVALID`.
607
+ `details.pointers` points at the member: `/input/_metadata/start_after/1/task_id`
608
+ for a task that does not exist, or `/input/_metadata/start_after/1/on/0` for a
609
+ name that is not an end state of that task's type.
610
+ - A platform release that predates this does not know the key: a task type with
611
+ a closed input schema refuses it, and one with an open schema starts the task
612
+ at once.
306
613
 
307
614
  ### Space actions
308
615
 
@@ -446,6 +753,13 @@ an editor with TSDoc support recognizes it instead of flagging it as unknown.
446
753
 
447
754
  The AI module provides powerful capabilities for working with unstructured data.
448
755
 
756
+ The `transcription` option on `extract`, `summarize`, `transcribe`, and `transcribePages` selects the reader for scanned pages; omission or `'standard'` preserves the default behavior.
757
+ `'precise'` costs more and is for pages where exact characters matter (codes, part numbers); text pages are unaffected.
758
+
759
+ ```typescript
760
+ const read = await transcribePages(documentHandle, { transcription: 'precise' }, request.context)
761
+ ```
762
+
449
763
  #### Extract Structured Data
450
764
 
451
765
  Extract structured information from documents, text, or images using AI:
@@ -718,6 +1032,34 @@ console.log(config.api_key) // "sk_live_..."
718
1032
  console.log(config.max_retries) // 3
719
1033
  ```
720
1034
 
1035
+ ### Tasks Module
1036
+
1037
+ Create a task from a server action. It is assigned to the user the action runs
1038
+ as. The platform makes the task and first-message ids. If an action must not
1039
+ start the same work twice, check its own record before creating the task.
1040
+
1041
+ On refusal, the task service's message begins with its code, such as
1042
+ `TASK_INPUT_INVALID: /title`. The SDK surfaces the full host error message.
1043
+ **What is not yet true.** Not every service refusal keeps its internal code.
1044
+ Input/schema (`TASK_INPUT_INVALID`, `TASK_INPUT_TOO_LARGE`), assignee
1045
+ (`TASK_ASSIGNEE_INVALID`), and other public refusals retain their codes.
1046
+ Unlisted internal refusals, including an unknown task type
1047
+ (`TASK_RELATION_NOT_FOUND`), arrive as `TASK_RUNTIME_REMOTE_FAILURE`, just as
1048
+ on the page path. A malformed successful reply throws an ordinary `Error`.
1049
+
1050
+ ```typescript
1051
+ import * as tasks from '@simpleplatform/sdk/tasks'
1052
+
1053
+ const { task } = await tasks.create({
1054
+ input: { invoice_id: 'INV000017' },
1055
+ taskTypeId: 'TTY000003',
1056
+ title: 'Review the invoice'
1057
+ }, request.context)
1058
+ ```
1059
+
1060
+ The result is `{ task: { id: 'TASK000042', revision: 0, status: 'queued' } }`.
1061
+ A new task starts at revision 0, also returned by the page's `tasks.create`.
1062
+
721
1063
  ### Storage Module
722
1064
 
723
1065
  Upload files from external sources to the platform's content-addressable storage:
package/dist/ai.d.ts CHANGED
@@ -159,6 +159,11 @@ export interface AICommonOptions {
159
159
  * If this timeout is exceeded, the promise will reject. Defaults to 30,000ms.
160
160
  */
161
161
  timeout?: number;
162
+ /**
163
+ * Selects the reader for scanned pages; omission or `standard` preserves the default.
164
+ * `precise` costs more and suits exact characters (codes, part numbers); text pages are unaffected.
165
+ */
166
+ transcription?: 'standard' | 'precise';
162
167
  }
163
168
  /**
164
169
  * The configuration options for an AI `extract` operation.
@@ -229,6 +234,11 @@ export interface AITranscribePagesOptions {
229
234
  regenerate?: boolean;
230
235
  /** (Optional) The maximum time in milliseconds to wait for the operation. */
231
236
  timeout?: number;
237
+ /**
238
+ * Selects the reader for scanned pages; omission or `standard` preserves the default.
239
+ * `precise` costs more and suits exact characters (codes, part numbers); text pages are unaffected.
240
+ */
241
+ transcription?: 'standard' | 'precise';
232
242
  }
233
243
  /**
234
244
  * One page's transcription, or why it has none. Pages are numbered in the
package/dist/ai.js CHANGED
@@ -51,10 +51,14 @@ async function _uploadPendingFiles(obj, context) {
51
51
  * @internal
52
52
  */
53
53
  async function _executeAIOperation(operation, input, options, context) {
54
- const { model, prompt, reasoning = true, reasoningBudget, regenerate = false, systemPrompt, temperature, timeout, } = options;
54
+ const { model, prompt, reasoning = true, reasoningBudget, regenerate = false, systemPrompt, temperature, timeout, transcription, } = options;
55
+ if (transcription !== undefined && transcription !== 'standard' && transcription !== 'precise') {
56
+ throw new Error('The `transcription` option must be "standard" or "precise".');
57
+ }
55
58
  const processedInput = await _uploadPendingFiles(input, context);
56
59
  // 1. Construct the universal options payload for caching and execution.
57
60
  const universalOptions = {
61
+ ...(transcription !== undefined && { transcription }),
58
62
  ...(temperature !== undefined && { temperature }),
59
63
  ...(reasoningBudget !== undefined && { reasoningBudget }),
60
64
  ...({ reasoning }),
@@ -0,0 +1,59 @@
1
+ import type { ProtocolRequest, SpaceTransport } from './protocol.js';
2
+ import type { JsonValue } from './tasks.js';
3
+ import { requestWithin } from './protocol.js';
4
+ export { requestWithin };
5
+ export interface ActionRunOptions {
6
+ /**
7
+ * How long the host waits for the action before it stops and answers
8
+ * `timeout`, in milliseconds. The host uses 60,000 when it is left out and
9
+ * accepts 1,000 to 1,200,000.
10
+ */
11
+ timeoutMs?: number;
12
+ }
13
+ /** The `details` of a `SpaceProtocolError` whose code is `action_failed`. */
14
+ export interface ActionFailedDetails {
15
+ /** The action's response body as parsed JSON, or `null` when it was not JSON. */
16
+ body: JsonValue;
17
+ /**
18
+ * The HTTP status the server answered with. An action the host ran in the
19
+ * browser (declared `client` or `both`) carries 200, the status the server
20
+ * gives the same failure, and its `body` has the same `{ error: [...] }` shape.
21
+ */
22
+ status: number;
23
+ }
24
+ export interface SimpleActionsClient {
25
+ /**
26
+ * Runs an action of this Space's own app where the app declares it runs
27
+ * (on the server, or in the browser for a `client` or `both` action), as
28
+ * the signed-in user, and returns its JSON result as the action returned it. The host
29
+ * adds the app, so `action` is the name alone, such as `document-attach`.
30
+ */
31
+ run: <TResult = unknown>(action: string, input: unknown, options?: ActionRunOptions) => Promise<TResult>;
32
+ }
33
+ export interface ActionRunRequest extends ProtocolRequest<{
34
+ /** The action's name within the Space's own app; the host adds the app. */
35
+ action: string;
36
+ input: JsonValue;
37
+ timeoutMs?: number;
38
+ }> {
39
+ operation: 'action.run';
40
+ }
41
+ /**
42
+ * How long a run waits for the host. The host answers `timeout` itself at the
43
+ * timeout, so this wait only ends a run whose answer never comes, as when the
44
+ * host has closed its port. A timeout the host refuses is answered at once, so
45
+ * it only needs to give a delay a timer can hold.
46
+ */
47
+ export declare function actionWaitMs(timeoutMs: number | undefined): number;
48
+ /**
49
+ * Checks an action run before it is sent. The timeout's range is the host's to
50
+ * enforce, so only its type is checked here, and it is sent only when given.
51
+ */
52
+ export declare function readActionRunPayload(action: string, input: unknown, options: ActionRunOptions | undefined): ActionRunRequest['payload'];
53
+ /**
54
+ * The host binds the Space's own app to every action it runs, so a Space names
55
+ * only the action and cannot reach another app's. Actions are not tied to a
56
+ * page record, so they are available in any Space whose host negotiated the
57
+ * action protocol, standalone or record.
58
+ */
59
+ export declare function createActionsClient(transport: SpaceTransport | undefined, nextRequestId: () => string): SimpleActionsClient;