@flipstream/sdk 0.8.0 → 0.10.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.
Files changed (104) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/README.md +707 -66
  3. package/dist/api/backend.d.ts +182 -0
  4. package/dist/api/backend.js +314 -0
  5. package/dist/api/backend.js.map +1 -0
  6. package/dist/api/created.d.ts +5 -0
  7. package/dist/api/created.js +15 -0
  8. package/dist/api/created.js.map +1 -0
  9. package/dist/api/credentials.d.ts +36 -0
  10. package/dist/api/credentials.js +94 -0
  11. package/dist/api/credentials.js.map +1 -0
  12. package/dist/api/datasets.d.ts +94 -0
  13. package/dist/api/datasets.js +212 -0
  14. package/dist/api/datasets.js.map +1 -0
  15. package/dist/api/handoff.d.ts +34 -0
  16. package/dist/api/handoff.js +52 -0
  17. package/dist/api/handoff.js.map +1 -0
  18. package/dist/api/ids.d.ts +7 -0
  19. package/dist/api/ids.js +27 -0
  20. package/dist/api/ids.js.map +1 -0
  21. package/dist/api/index.d.ts +9 -1
  22. package/dist/api/log.d.ts +95 -0
  23. package/dist/api/log.js +213 -0
  24. package/dist/api/log.js.map +1 -0
  25. package/dist/api/me.d.ts +58 -0
  26. package/dist/api/me.js +64 -0
  27. package/dist/api/me.js.map +1 -0
  28. package/dist/api/members.d.ts +48 -0
  29. package/dist/api/members.js +102 -0
  30. package/dist/api/members.js.map +1 -0
  31. package/dist/api/organization.d.ts +11 -0
  32. package/dist/api/organization.js +15 -0
  33. package/dist/api/organization.js.map +1 -0
  34. package/dist/api/page.d.ts +33 -0
  35. package/dist/api/page.js +38 -0
  36. package/dist/api/page.js.map +1 -0
  37. package/dist/api/time.d.ts +3 -0
  38. package/dist/api/time.js +49 -0
  39. package/dist/api/time.js.map +1 -0
  40. package/dist/api/unsent.d.ts +6 -0
  41. package/dist/api/unsent.js +9 -0
  42. package/dist/api/unsent.js.map +1 -0
  43. package/dist/api/wallet.d.ts +45 -0
  44. package/dist/api/wallet.js +102 -0
  45. package/dist/api/wallet.js.map +1 -0
  46. package/dist/api/workspaces.d.ts +70 -0
  47. package/dist/api/workspaces.js +108 -0
  48. package/dist/api/workspaces.js.map +1 -0
  49. package/dist/auth/discovery.js +1 -1
  50. package/dist/auth/discovery.js.map +1 -1
  51. package/dist/auth/signIn.js +7 -2
  52. package/dist/auth/signIn.js.map +1 -1
  53. package/dist/core/body.js +23 -5
  54. package/dist/core/body.js.map +1 -1
  55. package/dist/core/call.d.ts +6 -0
  56. package/dist/core/call.js +1 -1
  57. package/dist/core/call.js.map +1 -1
  58. package/dist/core/fetch.d.ts +5 -0
  59. package/dist/core/fetch.js +7 -1
  60. package/dist/core/fetch.js.map +1 -1
  61. package/dist/core/identify.d.ts +63 -0
  62. package/dist/core/identify.js +122 -0
  63. package/dist/core/identify.js.map +1 -0
  64. package/dist/core/names.d.ts +100 -0
  65. package/dist/core/names.js +114 -0
  66. package/dist/core/names.js.map +1 -0
  67. package/dist/core/read.d.ts +1 -1
  68. package/dist/core/read.js +15 -6
  69. package/dist/core/read.js.map +1 -1
  70. package/dist/core/result.d.ts +67 -6
  71. package/dist/core/result.js +39 -6
  72. package/dist/core/result.js.map +1 -1
  73. package/dist/core/secrets.d.ts +2 -0
  74. package/dist/core/secrets.js +33 -0
  75. package/dist/core/secrets.js.map +1 -0
  76. package/dist/core/transport.d.ts +12 -4
  77. package/dist/flipstream.d.ts +341 -5
  78. package/dist/flipstream.js +203 -13
  79. package/dist/flipstream.js.map +1 -1
  80. package/dist/index.d.ts +2 -2
  81. package/dist/index.js +1 -1
  82. package/dist/index.js.map +1 -1
  83. package/dist/node/clientSecret.js +2 -1
  84. package/dist/node/clientSecret.js.map +1 -1
  85. package/dist/node/index.d.ts +1 -0
  86. package/dist/node/index.js +1 -0
  87. package/dist/node/index.js.map +1 -1
  88. package/dist/node/keychainChild.js +10 -6
  89. package/dist/node/keychainChild.js.map +1 -1
  90. package/dist/node/keychainStore.d.ts +6 -3
  91. package/dist/node/keychainStore.js +6 -3
  92. package/dist/node/keychainStore.js.map +1 -1
  93. package/dist/node/session.d.ts +78 -29
  94. package/dist/node/session.js +74 -52
  95. package/dist/node/session.js.map +1 -1
  96. package/dist/node/store.d.ts +11 -1
  97. package/dist/node/store.js +14 -1
  98. package/dist/node/store.js.map +1 -1
  99. package/dist/query/query.d.ts +15 -10
  100. package/dist/query/query.js +21 -11
  101. package/dist/query/query.js.map +1 -1
  102. package/dist/version.gen.js +1 -1
  103. package/dist/version.gen.js.map +1 -1
  104. package/package.json +2 -2
package/README.md CHANGED
@@ -26,16 +26,20 @@ npm install @flipstream/sdk
26
26
  ```ts
27
27
  import { createFlipstream, orThrow } from '@flipstream/sdk'
28
28
 
29
- // Asked before every attempt: return the current access token.
30
- const fs = createFlipstream({ token: async () => '<your token>' })
29
+ const flipstream = createFlipstream({
30
+ // Required: every request says which app sent it (see "Which app sent a request").
31
+ app: { name: 'my-app', version: '1.0.0' },
32
+ // Asked before every attempt: return the current access token.
33
+ token: async () => '<your token>',
34
+ })
31
35
 
32
- const catalog = await fs.catalog.list()
36
+ const catalog = await flipstream.catalog.list()
33
37
  if (!catalog.ok) console.error(catalog.error.kind) // 'unauthorized', 'unavailable', …
34
38
 
35
39
  const answer = orThrow(
36
- await fs.query({
40
+ await flipstream.query({
37
41
  source: '<source>',
38
- connection_id: '<connection id>',
42
+ dataset_id: '<dataset id>',
39
43
  dimensions: ['<dimension>'],
40
44
  metrics: ['<metric>'],
41
45
  }),
@@ -43,8 +47,8 @@ const answer = orThrow(
43
47
  console.log(answer.rows, answer.lastRow)
44
48
  ```
45
49
 
46
- The catalogue names each source with its dimensions and metrics. `fs.catalog.get({ source })` gives
47
- one source.
50
+ The catalogue names each source with its dimensions and metrics.
51
+ `flipstream.catalog.get({ source })` gives one source.
48
52
 
49
53
  Each dimension and metric has a `format`, a union on its `type`:
50
54
  - `number`, `currency` and `percentage` carry `decimals`, and a `number` may carry
@@ -79,6 +83,439 @@ function shownAs(format: Format): string {
79
83
  }
80
84
  ```
81
85
 
86
+ ## Who you are
87
+
88
+ `flipstream.me()` answers your organisation, and you in it:
89
+
90
+ ```ts
91
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
92
+
93
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
94
+
95
+ const { organization, user } = orThrow(await flipstream.me())
96
+ console.log(organization.name, user.email, user.role)
97
+ ```
98
+
99
+ - **`organization`** is `{ id, name, slug, access }`. The slug is its short name, as the console's
100
+ addresses spell it.
101
+ - `access` says whether the organisation may use Flipstream, read from its billing settings by
102
+ the console's rules, in the service's own words:
103
+ - `{ status: 'trial', trial_ends_on }`: in trial, with `trial_ends_on` the trial's last day as
104
+ `YYYY-MM-DD`;
105
+ - `{ status: 'active' }`;
106
+ - `{ status: 'expired', trial_ends_on }`: the service's `expired`, which doesn't say why. Today
107
+ it only ever follows a trial. `trial_ends_on` is the trial's end, not necessarily the day
108
+ access ended;
109
+ - `{ status: 'unknown' }`: settings that can't be read, or a status this version doesn't know.
110
+ It's never read as active, and it never fails `me()`.
111
+ - The status is the truth. A trial past its last day stays `trial` until the service says
112
+ otherwise: the SDK never reads the clock for it. A day that isn't a real `YYYY-MM-DD` is `null`.
113
+ - Every role reads the same access, a viewer limited to some workspaces and Flipstream's own
114
+ staff included.
115
+ - **`user`** is `{ id, email, first_name, last_name, role, active, workspace_ids }`: a `Member`, as
116
+ `flipstream.members` answers each person (see "Your organisation's members").
117
+ - `me()` reads the token's own person and doesn't apply `members`' people-only rule. An API key's
118
+ token isn't tested with it yet: service accounts come with pulse-admin#93.
119
+ - `role` is the highest you hold: `'owner'`, `'admin'`, `'editor'` or `'viewer'`. It's `null`
120
+ when you hold none of them, and for Flipstream's own staff (`godmode`, `swapper`), whatever
121
+ else they hold. There's no guest role yet. A role this version doesn't know counts as none of
122
+ ours: it never fails the answer, a known role beside it still wins, and its name is never shown.
123
+ - `active` says whether your account is switched on.
124
+ - `workspace_ids` are the workspaces your account names. For a viewer, they're the workspaces
125
+ you may open, and a viewer with none opens every workspace of the organisation. No other role
126
+ is limited by them.
127
+ - **Nothing else** from the services' answers is in it.
128
+ - **Three reads:** your organisation, and who your token belongs to, then that person. They share
129
+ one deadline, 30 s unless the call sets its own, and the first failure, in that order, is the
130
+ answer.
131
+ - **Renaming your organisation is a person's to do, in the console.**
132
+ `flipstream.organization.rename({ name })` never writes. It reads your organisation, then
133
+ answers `needs_person` with `why`. Where a console can be named (your own `hosts.console`), the
134
+ organisation's settings page is the `url`, with what it shows as `sees`, as `workspaces.rename`
135
+ does. There, Owners and Admins change the name and the short name. The `name` you give is never
136
+ echoed.
137
+
138
+ ## Your organisation's members
139
+
140
+ `flipstream.members` reads the people of your organisation, one page at a time, each as `me()`
141
+ answers you. People, not keys: an API user, a service account, is never listed, counted or
142
+ answered, as the console's People has it. (`me()` doesn't apply that rule: see "Who you are".)
143
+
144
+ ```ts
145
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
146
+
147
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
148
+
149
+ const page = orThrow(await flipstream.members.list({ limit: 50 }))
150
+ for (const member of page.items) console.log(member.email, member.role, member.active)
151
+
152
+ const member = orThrow(await flipstream.members.get({ member_id: page.items[0]?.id ?? '<member id>' }))
153
+ console.log(member.first_name, member.workspace_ids.length)
154
+ ```
155
+
156
+ - **A member** is `{ id, email, first_name, last_name, role, active, workspace_ids }`, and nothing
157
+ else, with `role` and `workspace_ids` by `me()`'s rules (see "Who you are"): the highest role
158
+ they hold, or `null` for none and for Flipstream's own staff. A role this version doesn't know
159
+ counts as none of ours, and its name is never shown.
160
+ - **An open invitation is in the list:** someone invited who hasn't joined yet has an empty
161
+ `first_name`, as the console tells them apart.
162
+ - **Keys are left out by the service itself,** so `total` counts people.
163
+ - **A list is one page:** `{ items, total, limit, offset }`, where `total` counts every member.
164
+ - The limit is 100 unless you set one, and at most 1,000.
165
+ - A limit or offset that isn't a whole number in range rejects, with nothing sent.
166
+ - **The order is the service's own:** by email. Pages read at different times can overlap, or skip
167
+ a person, when people are added or removed, or an email changes, in between. A changed `total`
168
+ shows some of that, but an unchanged one doesn't prove nothing moved. For a complete, stable
169
+ list, read it in one page: up to 1,000.
170
+ - **Each call reads your organisation beside the people,** under one deadline for both reads, and
171
+ its failure is the answer. In a list, a person of another organisation makes the answer
172
+ `invalid`; they're never shown or dropped.
173
+ - **What `get` answers,** for an id:
174
+ - **the person,** when they're one of your organisation's people;
175
+ - **`not_found`** when there's no such person for you: pulse-auth has none by that id, or your
176
+ role can't read them (it answers 404), or the id is one of your organisation's API keys, which
177
+ `get` answers as an id nobody has;
178
+ - **`forbidden`** when pulse-auth refuses the read (403);
179
+ - **`invalid`** when the answer is another organisation's person or API key, which only a staff
180
+ token reaches, such as Flipstream's staff acting through a swap token. The organisation is
181
+ checked before the key, so another organisation's key is `invalid` too. So is an answer that
182
+ is someone else than the person asked for.
183
+
184
+ ## Workspaces
185
+
186
+ `flipstream.workspaces` reads your organisation's workspaces, one page at a time:
187
+
188
+ ```ts
189
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
190
+
191
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
192
+
193
+ const page = orThrow(await flipstream.workspaces.list({ limit: 50 }))
194
+ console.log(page.total, page.items.map((workspace) => workspace.name))
195
+
196
+ const workspace = orThrow(await flipstream.workspaces.get({ workspace_id: page.items[0]?.id ?? '<workspace id>' }))
197
+ console.log(workspace.slug)
198
+ ```
199
+
200
+ - **A workspace** is `{ id, name, slug }`. Nothing else the service sends is in it.
201
+ - **A page** is `{ items, total, limit, offset }`. `total` counts every workspace, and `limit` and
202
+ `offset` say what was read. `limit` is 100 when left out and at most 1,000, and a larger one is
203
+ read as 1,000. A limit or offset that isn't a whole number in range rejects with a `TypeError`,
204
+ with nothing sent.
205
+ - **The order is the service's own:** by name alone, for workspaces. Pages read at different times
206
+ can overlap, or skip a workspace, when workspaces are added, removed or renamed in between, or
207
+ when two have the same name. A changed `total` shows some of that, but an unchanged one doesn't
208
+ prove nothing moved. For a complete, stable list, read it in one page: up to 1,000.
209
+ - **Each call reads your organisation first,** under one deadline for both reads, and its failure
210
+ is the answer. A workspace of another organisation makes the answer `invalid`; it's never shown
211
+ or dropped.
212
+ - **Creating a workspace:** `flipstream.workspaces.create({ name })` makes one in your organisation
213
+ and answers it as a `Workspace`.
214
+
215
+ ```ts
216
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
217
+
218
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
219
+
220
+ const made = orThrow(await flipstream.workspaces.create({ name: 'Acme NL' }))
221
+ console.log(made.id, made.slug) // the short name the service chose, such as 'acme-nl-2'
222
+ ```
223
+
224
+ - It sends the name alone, with your organisation. The service makes the short name, unique in
225
+ your organisation, so read `slug` from the answer.
226
+ - **A request with any key but `name` is `refused`** (`reason: 'fields'`, naming them), with
227
+ nothing sent: a `slug` or an `organization_id` it dropped would look set. A `name` that isn't a
228
+ non-empty string, or is only spaces, rejects with a `TypeError`, with nothing sent.
229
+ - Who may create one is the service's rule, not the SDK's: Owners and Admins. pulse-admin#181
230
+ aligns the service with it; until then an Editor still succeeds. Anyone it refuses gets
231
+ `forbidden`.
232
+ - **It's never tried again.** Only a refusal (a 4xx kind such as `forbidden`), `refused` or
233
+ `no_token` shows nothing was made. After any other failure (`timeout`, `unavailable`,
234
+ `aborted`, `cancelled`, or `invalid`, which may be the service's answer that it made one) it may
235
+ have been made, so list the workspaces before you create it again. Names needn't be unique, so
236
+ compare that list with one from before you created it.
237
+ - **Renaming or deleting a workspace is a person's to do, in the console.**
238
+ `flipstream.workspaces.rename({ workspace_id, name })` and `delete({ workspace_id })` never write.
239
+ Each reads the workspace (one that isn't yours is `not_found`), then answers `needs_person`:
240
+
241
+ ```ts
242
+ import { createFlipstream } from '@flipstream/sdk'
243
+
244
+ const flipstream = createFlipstream({
245
+ app: { name: 'my-app', version: '1.0.0' },
246
+ token: async () => '<your token>',
247
+ hosts: { console: 'http://localhost:5173' },
248
+ })
249
+
250
+ const result = await flipstream.workspaces.rename({ workspace_id: '<workspace id>', name: 'New name' })
251
+ if (!result.ok && result.error.kind === 'needs_person') {
252
+ console.log(result.error.why) // tell the person what to do, and why
253
+ if (result.error.url !== undefined) console.log(result.error.url, result.error.sees)
254
+ }
255
+ ```
256
+
257
+ - `why` is the SDK's own words, never a value you gave, so it's safe to show.
258
+ - `url` and `sees` name the workspace's settings page, and are there only when a console can be
259
+ named: set `hosts.console` (for example `http://localhost:5173`, while developing). It must be
260
+ https, or http on this machine, with no query, fragment or credentials, or `createFlipstream`
261
+ throws a `TypeError`.
262
+ - `orThrow` throws it as an `ApiFailure` whose message gives `why`.
263
+
264
+ ## A workspace's logbook
265
+
266
+ `flipstream.log` reads and writes a workspace's logbook: its notes on time ranges, such as a launch
267
+ or a site migration.
268
+
269
+ ```ts
270
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
271
+
272
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
273
+
274
+ const page = orThrow(await flipstream.log.list({ workspace_id: '<workspace id>', limit: 50 }))
275
+ for (const entry of page.items) console.log(entry.start_date, entry.end_date, entry.description)
276
+ console.log(`${page.items.length} of ${page.total}`)
277
+
278
+ const entry = orThrow(await flipstream.log.get({ log_id: '<log entry id>' }))
279
+ ```
280
+
281
+ - **An entry** is `{ id, description, start_date, end_date, workspace_id, created_on, created_by_id }`,
282
+ and nothing else.
283
+ - `start_date` and `end_date` are ISO 8601 instants in UTC, such as `2026-10-05T00:00:00.000Z`.
284
+ - A point in time starts and ends at once.
285
+ - `created_on` is when it was written, in the same form, and `created_by_id` the person who wrote
286
+ it. Either is `null` when the service holds none.
287
+ - `flipstream.members.get({ member_id: created_by_id })` names the writer. When it doesn't answer
288
+ ok (see "Your organisation's members"), show the writer as unknown, for example for an entry
289
+ Flipstream staff wrote through a swap token.
290
+ - **A list is one page:** `{ items, total, limit, offset }`, where `total` counts every entry.
291
+ - The limit is 100 unless you set one, and at most 1,000.
292
+ - A limit or offset that isn't a whole number in range rejects, with nothing sent.
293
+ - **The order is newest written first:** the logbook's own, since the SDK asks for no other.
294
+ - When an entry was written never changes, so editing an entry doesn't move it.
295
+ - Pages read at different times can still overlap or skip an entry, when one is written or
296
+ removed in between.
297
+ - Entries written at the same moment have no fixed order among themselves.
298
+ - A changed `total` shows that something was added or removed; an unchanged one doesn't prove
299
+ nothing was.
300
+ - **The workspace is read beside the list,** with your organisation, under one deadline: one
301
+ nobody has is `not_found`, and another organisation's is `invalid`, never an empty page. Their
302
+ failure, then the list's, is the answer.
303
+ - **An entry of another workspace or organisation** in the list makes the answer `invalid`; it's
304
+ never dropped.
305
+ - **A missing entry:** `get` answers `not_found`. `get` reads your organisation beside the entry, and
306
+ an answer that is another entry than the one asked for, or another organisation's, is `invalid`.
307
+
308
+ **Writing to it:** `add`, `update` and `remove`.
309
+
310
+ ```ts
311
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
312
+
313
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
314
+
315
+ const added = orThrow(
316
+ await flipstream.log.add({ workspace_id: '<workspace id>', description: 'Site migration', start_date: '2026-10-05T00:00:00Z', end_date: '2026-10-06T00:00:00Z' }),
317
+ )
318
+ orThrow(await flipstream.log.update({ log_id: added.id, description: 'Site migration, phase 1' }))
319
+ orThrow(await flipstream.log.remove({ log_id: added.id })) // null
320
+ ```
321
+
322
+ - **What each takes,** before anything is sent:
323
+ - a key it doesn't send is `refused` (`reason: 'fields'`, naming them);
324
+ - a description that isn't a non-blank string, a time not written as `2026-10-05T00:00:00Z`, or a
325
+ start after the end rejects with a `TypeError`. A fraction may follow the seconds, and an offset
326
+ such as `+02:00`, or none, may take the place of the `Z`. A time with no offset is read as UTC,
327
+ and every time is sent as a UTC instant.
328
+ - **Each write reads first.** `add` reads the workspace: one nobody has is `not_found`, and another
329
+ organisation's is `invalid`, with nothing written. `update` and `remove` read the entry, held to
330
+ your organisation the same way.
331
+ - **`update` changes what you give,** at least one of `description`, `start_date` and `end_date`,
332
+ and sends the rest back exactly as stored. When you give a time, a start after the stored end
333
+ (or an end before the stored start) rejects with a `TypeError`, with nothing written. Since the
334
+ whole entry goes back, a change someone else made between `update`'s read and its write is
335
+ overwritten.
336
+ - **`remove` answers `null`.** A log entry's remove is direct; it's not handed to a person.
337
+ - **Who may write is the service's rule, not the SDK's:** Owners, Admins and Editors add; an Editor
338
+ changes or removes only their own entries, and Owners and Admins any. Until the service enforces
339
+ it (pulse-admin#161, for Editors), a Viewer can also add, change and remove entries, and an Editor
340
+ can change anyone's. Anyone it refuses gets `forbidden`.
341
+ - **A write is never tried again.** Only a refusal (a 4xx kind such as `forbidden`), `refused` or
342
+ `no_token` shows nothing was written. After any other failure it may have been, so list the
343
+ logbook before you write again.
344
+
345
+ ## A workspace's datasets
346
+
347
+ `flipstream.datasets` reads a workspace's datasets, its uploads and connected accounts, and pauses
348
+ and resumes them. `flipstream.datasetTypes` lists the types of dataset this version knows.
349
+
350
+ ```ts
351
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
352
+
353
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
354
+
355
+ const page = orThrow(await flipstream.datasets.list({ workspace_id: '<workspace id>', limit: 50 }))
356
+ for (const dataset of page.items) console.log(dataset.name, dataset.type, dataset.active)
357
+
358
+ const dataset = orThrow(await flipstream.datasets.get({ dataset_id: '<dataset id>' }))
359
+ const types = orThrow(await flipstream.datasetTypes.list())
360
+ console.log(dataset.name, types.length)
361
+ ```
362
+
363
+ - **A dataset** is `{ id, name, workspace_id, type, active, created_on, created_by_id, history }`,
364
+ and nothing else: never a credential, a setting or its parameters. The service's answer embeds the dataset's
365
+ sign-in, so a body that isn't the service's JSON is never kept either: a failure of the dataset's
366
+ own read or write gives its kind and status, with no `text`. The reads of your organisation and
367
+ the workspace beside it keep theirs.
368
+ - `type` is one of the types `datasetTypes.list()` gives, such as `'google_search_console'`, or
369
+ a type this version doesn't know yet, kept as it came, so a new kind of dataset never makes the
370
+ list unreadable. It's `null` when the service holds no type for it.
371
+ - `active` says whether it's switched on.
372
+ - `created_on` is when it was made, an ISO 8601 instant in UTC, and `created_by_id` the person who
373
+ made it. Either is `null` when the service holds none.
374
+ - `flipstream.members.get({ member_id: created_by_id })` names the maker. When it doesn't answer
375
+ ok (see "Your organisation's members"), show the maker as unknown, for example for a dataset
376
+ Flipstream staff made through a swap token.
377
+ - `history` says how much of its history is in the warehouse, a `DatasetHistory`, in the
378
+ service's own values (the SDK renames fields, never values):
379
+ - `'not_available'`: no history is loaded for its kind of dataset;
380
+ - `'todo'`: its history hasn't started loading. Every new dataset starts here, and the
381
+ pipeline sets `'not_available'` only when it first runs for one, so `'todo'` may never start
382
+ for a type that loads no history;
383
+ - `'started'`: its history is loading, from the first load until it's in; a load that keeps
384
+ failing stays `'started'`;
385
+ - `'done'`: its history is in.
386
+
387
+ Merge them as your app needs: the console shows `'todo'` and `'started'` alike as "coming in".
388
+ It's `null` when it's unknown, because the service holds none or a value this version doesn't
389
+ know: show "Not available yet" then, never a value of your own.
390
+ - **A list is one page:** `{ items, total, limit, offset }`, where `total` counts every dataset.
391
+ - The limit is 100 unless you set one, and at most 1,000.
392
+ - A limit or offset that isn't a whole number in range rejects, with nothing sent.
393
+ - **The order is the service's own:** by name alone. Pages read at different times can overlap, or
394
+ skip a dataset, when datasets are added, removed or renamed in between, or when two have the same
395
+ name. A changed `total` shows some of that, but an unchanged one doesn't prove nothing moved. For
396
+ a complete, stable list, read it in one page: up to 1,000.
397
+ - **Each call reads your organisation beside the datasets,** and a list reads its workspace too,
398
+ under one deadline for every read. The organisation's failure, then the workspace's, is the
399
+ answer. A dataset of another organisation, or in the list one of another workspace, makes the
400
+ answer `invalid`; it's never shown or dropped.
401
+ - **A workspace nobody has** is `not_found`, and another organisation's is `invalid`: never an empty
402
+ page, which would say it has no datasets.
403
+ - **A missing dataset:** `get` answers `not_found`. An answer that is another dataset than the one
404
+ asked for is `invalid`.
405
+ - **`datasetTypes.list()`** sends nothing: the types are the SDK's own list, since the service has
406
+ no route for them yet. Each call gives you a list of your own.
407
+
408
+ **Pausing and resuming:** `pause` and `resume`.
409
+
410
+ ```ts
411
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
412
+
413
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
414
+
415
+ const paused = orThrow(await flipstream.datasets.pause({ dataset_id: '<dataset id>' }))
416
+ console.log(paused.active) // false
417
+ orThrow(await flipstream.datasets.resume({ dataset_id: '<dataset id>' })) // active: true
418
+ ```
419
+
420
+ - **Each answers the `Dataset`,** with `active` as asked. Pausing a paused dataset sends the same
421
+ write and answers the same, so calling either twice is the same as once.
422
+ - **What each takes,** before anything is sent: `dataset_id` alone. Any other key is `refused`
423
+ (`reason: 'fields'`, naming them), and an id that isn't a string rejects with a `TypeError`.
424
+ - **Each reads first:** the dataset, fresh, beside your organisation. One nobody has is
425
+ `not_found`, and another organisation's is `invalid`, with nothing written. Then `active` alone
426
+ is sent, so a rename made in between stays.
427
+ - **Each reads again after the write,** fresh, and answers that read. One whose `active` isn't the
428
+ one asked for is `invalid`, since the write may not have been stored, as is one of another
429
+ dataset, workspace or organisation. That read comes after the write was sent, so its failure
430
+ is never answered as a refusal: a 4xx kind, `refused` or `no_token` there is `invalid`, naming
431
+ its kind. A `timeout`, `aborted`, `cancelled`, `unavailable` or `invalid` there keeps its kind,
432
+ since it already says the write may have been made.
433
+ - **Who may is the service's rule:** Owners, Admins and Editors pause and resume, and a Viewer
434
+ doesn't. Anyone it refuses gets `forbidden`.
435
+ - **A write is never tried again.** Only a refusal (a 4xx kind such as `forbidden`), `refused` or
436
+ `no_token` shows nothing was written. After any other failure it may have been; calling it
437
+ again is safe, since it's the same write.
438
+
439
+ **Deleting a dataset is a person's to do, in the console.** It removes the dataset's data for good,
440
+ and the console can't delete a dataset yet. `flipstream.datasets.delete({ dataset_id })` never
441
+ writes. It reads the dataset first: one nobody has is `not_found`, and another organisation's is
442
+ `invalid`. Then it answers `needs_person` with `why`, and, where a console can be named (your own
443
+ `hosts.console`), the dataset's page as `url`, with what it shows as `sees`, as
444
+ `workspaces.delete` does.
445
+
446
+ ## Sign-ins to your sources
447
+
448
+ `flipstream.credentials` lists the provider sign-ins your organisation holds, such as a Google
449
+ account a dataset reads with, as metadata only. The SDK has no call that reads a sign-in's value.
450
+
451
+ ```ts
452
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
453
+
454
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
455
+
456
+ const page = orThrow(await flipstream.credentials.list({ limit: 50 }))
457
+ for (const credential of page.items) console.log(credential.name, credential.type, credential.datasource_types)
458
+ ```
459
+
460
+ - **A credential** is `{ id, name, type, datasource_types, created_on }`, and nothing else.
461
+ - `name` is the provider account it signs in as: for a Google sign-in, that account's email
462
+ address.
463
+ - `type` is what kind of sign-in it is, such as `'oauth2'` or `'service_account'`. A kind this
464
+ version doesn't know is kept as it came, and it's `null` when the service holds none.
465
+ - `datasource_types` lists the kinds of dataset it serves, such as `'google_search_console'`.
466
+ - `created_on` is an ISO 8601 instant in UTC.
467
+ - **Never a value.** The service doesn't mask a sign-in, so the SDK checks every answer itself. An
468
+ answer holding what may be a sign-in's value (a `data` that isn't empty, or a key such as
469
+ `refresh_token`, `apiKey`, `auth_values` or `password`, at any depth, however it's spelt) is
470
+ `invalid`. Its issues name the place, never the value, and nothing is answered at all. A body
471
+ that isn't the service's JSON is never kept either: a failure of the sign-ins' own reads gives
472
+ its kind and status, with no `text`. The read of your organisation beside them keeps its.
473
+ - **A list is one page:** `{ items, total, limit, offset }`, as every list is. The limit is 100
474
+ unless you set one, and at most 1,000.
475
+ - **It reads your organisation first,** for its id, and its failure is the answer. A sign-in of
476
+ another organisation makes the answer `invalid`.
477
+ - **Who may list them is the service's rule:** today Owners, Admins, Editors and Viewers. Anyone
478
+ it refuses gets `forbidden`.
479
+ - **Revoking or deleting a sign-in is a person's to do, in the console.** Either breaks every
480
+ dataset that reads with it. `flipstream.credentials.revoke({ credential_id })` and
481
+ `delete({ credential_id })` never write. Each reads the sign-in first: one nobody has is
482
+ `not_found`, and another organisation's is `invalid`. Then it answers `needs_person` with `why`.
483
+ There's no `url` yet: no console page names a sign-in.
484
+
485
+ ## Wallet
486
+
487
+ `flipstream.wallet` reads your organisation's prepaid wallet. It only reads: adding credit is done
488
+ by a person, in the console.
489
+
490
+ ```ts
491
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
492
+
493
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
494
+
495
+ const balance = orThrow(await flipstream.wallet.balance())
496
+ if (balance !== null) console.log(balance.balance_micro / balance.micro_per_euro, 'euros')
497
+
498
+ const ledger = orThrow(await flipstream.wallet.transactions())
499
+ console.log(ledger.items.length, 'rows')
500
+ ```
501
+
502
+ - **Amounts are whole numbers of micro,** and each answer says how many make a euro, in
503
+ `micro_per_euro`. Divide by it, never by a number of your own: the basis can change.
504
+ - **`balance()`** is `{ balance_micro, micro_per_euro }`, or `null` when your organisation has no
505
+ wallet. No wallet is a real state, so it's not an error, and it's never a zero balance: €0.00
506
+ would claim a wallet that holds nothing.
507
+ - **`transactions()`** is the whole ledger, in one answer, with no paging: `{ items, micro_per_euro }`.
508
+ The ledger's rows don't name their wallet, so the balance is read beside it, and the ledger is
509
+ answered only when that's your organisation's wallet. Each row
510
+ is `{ id, type, dataset_id, description, amount_micro, quantity, unit_price_micro, created_on }`.
511
+ A row that charged no dataset, such as a credit, has `dataset_id: null`, whether the wallet
512
+ wrote its `connection_id` empty or null. `created_on` is an
513
+ ISO 8601 instant in UTC, such as `2026-10-31T13:08:25.312Z`, as the logbook's times are. A type
514
+ this version doesn't know is kept as it came.
515
+ - **Who may read it is the wallet's rule, not the SDK's.** Today that's Owners and Admins, and
516
+ Editors too once pulse-wallet#15 lands. Anyone the wallet refuses gets `forbidden`, never an
517
+ empty ledger.
518
+
82
519
  ## Signing in from Node and the CLI
83
520
 
84
521
  For an app that runs on the person's own machine, or in their terminal: a CLI, a script, a local
@@ -119,7 +556,7 @@ const signedIn = await signInWithLoopback({
119
556
  })
120
557
  if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
121
558
 
122
- const fs = createFlipstream({ token: () => signedIn.data.accessToken })
559
+ const flipstream = createFlipstream({ app: { name: 'my-cli', version: '1.0.0' }, token: () => signedIn.data.accessToken })
123
560
  ```
124
561
 
125
562
  - **The SDK opens nothing and writes nothing to the terminal.** `open` does that, once the port is
@@ -263,11 +700,19 @@ if (saved === null) {
263
700
 
264
701
  // The session discovers the server itself, only when a refresh or a sign-out needs it.
265
702
  const session = createSession({ issuer, clientId: '<your client id>', ...store })
266
- const fs = createFlipstream({ token: session.token })
703
+ const flipstream = createFlipstream({ app: { name: 'my-cli', version: '1.0.0' }, token: session.token })
267
704
 
268
- // Signing out ends the session at the server, and clears the store through onTokens.
705
+ // Signing out ends the session at the server, then clears the store through onTokens, and says
706
+ // how each went.
269
707
  const signedOut = await session.revoke()
270
708
  console.log(signedOut.kind)
709
+ if (signedOut.cleared === 'failed') {
710
+ // Where the store failed (read, lock or clear), and its own error: a KeychainError says why.
711
+ const { step, cause } = signedOut.failure
712
+ console.error(`the tokens may still be stored: the ${step} failed (${cause instanceof Error ? cause.message : String(cause)})`)
713
+ } else if (signedOut.cleared !== 'cleared' && signedOut.cleared !== 'kept') {
714
+ console.error(`the tokens may still be stored (${signedOut.cleared}): sign out again`)
715
+ }
271
716
  ```
272
717
 
273
718
  - **`issuer`,** as above, discovers the server itself, only when a refresh or a sign-out needs it,
@@ -305,10 +750,12 @@ console.log(signedOut.kind)
305
750
  Linux (GNOME Keyring, KWallet). It needs the optional package `@napi-rs/keyring`
306
751
  (`npm install @napi-rs/keyring`).
307
752
  - **Every failure of the keychain or its helper is a `KeychainError`,** which is also the
308
- `cause` of a session's `store_failed`. Two failures are the store's own, not the keychain's:
309
- `save` rejects tokens with no access token as a `TypeError` before any step, and an item
310
- holding something other than tokens fails its read with a plain `Error` that never quotes
311
- it. A `KeychainError`'s `failure.kind` says why:
753
+ `cause` of a session's `store_failed`. Three failures are the store's own, not the
754
+ keychain's: `save` rejects tokens with no access token as a `TypeError` before any step; an
755
+ item holding something other than tokens fails its read with a plain `Error` that never
756
+ quotes it; and an update for tokens the item no longer holds is refused with a
757
+ `StoreMovedOnError`, which a sign-out reads as `kept` and a refresh reports as `store_failed`
758
+ (`save`). A `KeychainError`'s `failure.kind` says why:
312
759
  - `unavailable`: there's no keychain on this machine, as on Linux with no Secret Service or no
313
760
  D-Bus session (most servers and containers). It's the only kind after which a file may
314
761
  stand in, if your app or the person chooses it;
@@ -328,7 +775,9 @@ console.log(signedOut.kind)
328
775
  warm while your app runs (about 57 MB), so a step after that takes a keychain call, not a
329
776
  process start. A step that takes longer than 30 s (`timeoutMs`) ends it, so a keychain prompt
330
777
  that nobody answers can't hold up your app, and the next step starts another. A Ctrl-C in
331
- the terminal reaches the helper too, and it ignores it. When your app ends, the helper ends
778
+ the terminal reaches the helper too, and it ignores it, from before its own code loads. Not
779
+ during Node's own start-up, though, or any preload in `NODE_OPTIONS`: a Ctrl-C then still
780
+ ends a helper that is just starting. When your app ends, the helper ends
332
781
  too: at once if it's idle or reading, or once it has finished the save or delete it's on, so
333
782
  a refresh's save isn't lost to a Ctrl-C. It gives that step 1 s more at most, less than the
334
783
  soonest `fileLock` lets another process take the lock your app held: at the soonest about
@@ -360,6 +809,26 @@ console.log(signedOut.kind)
360
809
  until the person logs in at the machine once, or runs `security unlock-keychain`.
361
810
  - On macOS, a script run by the same Node can read the item without a prompt, much as with a
362
811
  file only the person can read.
812
+ - **After a Node upgrade, macOS may ask for the login password.** It knows a Node signed ad hoc,
813
+ as Homebrew's Node and a Node built from source are, only by its code's hash, which every
814
+ build changes. So after `brew upgrade node`, the item the old Node saved is, to macOS, another
815
+ program's. Each of the new Node's keychain steps on it then shows a dialog: a read, a
816
+ refresh's save, and a sign-out's clear.
817
+ - "Allow" answers that one step, and the next step asks again;
818
+ - "Always Allow" trusts that Node build with the item, until the next upgrade;
819
+ - nothing is refused: a sign-out still clears the tokens, after its dialogs.
820
+ - **Each dialog must be answered within the call's limits:** `session.token()`'s wait, 15 s
821
+ unless you pass `waitMs` (see "Through `session.token()`" above; #233's first read took
822
+ 18.6 s); each keychain step's `timeoutMs`, 30 s by default; and a sign-out's 10 s for its
823
+ revocation, which its first read's dialog counts against. So after an upgrade, a sign-out
824
+ whose first dialog is slow still clears the tokens, but ends `unconfirmed`, without
825
+ revoking them at the server.
826
+
827
+ nodejs.org's builds are signed with the Node.js Foundation's Developer ID, so they keep their
828
+ identity across versions, and an upgrade shouldn't ask. Checked on macOS 26 with a copy of
829
+ Homebrew's Node 26.12.1 re-signed ad hoc, standing in for an upgrade
830
+ (`scripts/live/keychain-upgrade.mjs`, #233). Not run: a real upgrade of either kind, and
831
+ "Always Allow".
363
832
  - It's tested on macOS. Windows and Linux aren't tested yet.
364
833
  - **One session per store,** shared by everything that uses it, or pass `lock`, a lock every
365
834
  process takes, which settles only once its work has settled. Two sessions on one store refresh as
@@ -375,7 +844,7 @@ console.log(signedOut.kind)
375
844
  - **`unavailable` comes at the caller's wait,** the store's read included: 15 s unless you pass
376
845
  `createSession({ waitMs })`. Give a store that can wait on a person, such as a keychain asking
377
846
  for access, as long as they may take: 120 s when interactive, say. Only this wait changes. A
378
- refresh still waits at most 60 s for its answer, and a sign-out answers at its 10 s.
847
+ refresh still waits at most 60 s for its answer, and a sign-out sends nothing after its 10 s.
379
848
  - **Before your process exits, `await session.settled()`.** It resolves once the session has no
380
849
  refresh, save or sign-out in flight. `unavailable` comes while a refresh may still be saving the
381
850
  token it got, and an exit then loses it. It never rejects and starts nothing.
@@ -383,26 +852,51 @@ console.log(signedOut.kind)
383
852
  a save holds it, and so does a lock that ignores its signal. A sign-out's store call still
384
853
  running after 60 s isn't waited for.
385
854
  - **The SDK's own stores answer every call.** A `keychainStore` save or clear is two steps of up
386
- to its `timeoutMs` each, so keep `timeoutMs` at 30 s or under, or a sign-out's clear can be cut.
855
+ to its `timeoutMs` each, so keep `timeoutMs` at 30 s or under, or a sign-out's clear can be cut,
856
+ which it reports as `cut`.
387
857
  - **Stop making calls before you await it:** calls that keep coming keep it waiting.
388
- - **`session.revoke()`** gives `revoked`, or `unconfirmed` with the reason. It ends the session the
389
- store holds when its turn comes, and, whatever the result, clears it through `onTokens`
390
- (`cleared`), once, in the same hold of the lock, so a refresh can't bring it back. A sign-in saved
391
- after that is kept. A refresh token the session holds only because saving it failed goes too,
392
- after the stored session, even once the store has moved on, and the session then lets it go. It waits for the clear at most 10 s. After `timeout` or `aborted`, the clear
393
- may still be on its way: once it reaches the lock, it waits at most 60 s for the lock and for each
394
- of its three store calls, so up to about four minutes. A lock held longer than its 60 s by another
395
- process, or a store call that doesn't answer within its 60 s, leaves the store as it was.
858
+ - **`session.revoke()`** ends the session the store holds when its turn comes, then, whatever the
859
+ server said, clears it through `onTokens` (`cleared`), once, in the same hold of the lock, so a
860
+ refresh can't bring it back. A sign-in saved after that is kept. A refresh token the session holds
861
+ only because saving it failed goes too, after the stored session, even once the store has moved
862
+ on, and the session then lets it go.
863
+ - **It answers once both are done:** `kind` is `revoked`, or `unconfirmed` with the reason, and
864
+ `cleared` says what became of the store:
865
+ - `cleared`: it was cleared;
866
+ - `kept`: there was nothing to clear: nothing stored, or the store moved on meanwhile, to a
867
+ newer sign-in, which is kept, or to another sign-out's clear;
868
+ - `failed`: the store failed, and `failure` says where and how: its `step` is `read`, `lock`
869
+ or `clear`, and its `cause` is what the store threw, unchanged, whether it's an `Error` or
870
+ not: a `KeychainError`, for instance, whose `failure.kind` and message say why. A clear it
871
+ refuses with anything but `StoreMovedOnError` counts as failed, at `clear`;
872
+ - `cut`: the lock or a store call took longer than its 60 s;
873
+ - `pending`: your `signal` answered first, and the clear goes on, unless the signal had already
874
+ fired when you called, when nothing runs at all.
875
+
876
+ After anything but `cleared` and `kept`, the tokens may still be stored: tell the person, so
877
+ they can sign out again.
878
+ - **It can take minutes on a stalled store, and longer behind one.** It sends nothing after its
879
+ 10 s, but it waits for the clear. First it waits for any turn ahead of it, for as long as that
880
+ takes: a refresh that is still saving, or a lock that ignores its signal. Then it waits at most
881
+ 60 s for the lock and for each of its three store calls, so up to about four minutes. It used to
882
+ answer within 10 s while the clear went on behind it. A lock held longer than its 60 s by
883
+ another process, or a store call that doesn't answer within its 60 s, leaves the store as it
884
+ was, unless that call finishes later on its own.
885
+ - **Pass a `signal` to stop waiting:** it answers at once, with `cleared: 'pending'`, and the
886
+ clear goes on. Await `session.settled()` before the process exits. A signal that has already
887
+ fired when you call runs nothing at all, and answers `pending` too.
396
888
 
397
889
  **Writing your own store:** give `tokens` and `onTokens` instead, and keep the same two rules.
398
890
  `tokens()` returns only what `onTokens` has durably saved: write first, show second. `onTokens`
399
- writes only while the store's key is still `update.replaces`, and throws when it refuses. The key is
400
- the stored refresh token, or the access token when it has none or an empty one
401
- (`refreshToken || accessToken`). Here in memory:
891
+ writes only while the store's key is still `update.replaces`, and when it refuses, throws a
892
+ `StoreMovedOnError`, as the ready-made stores do. A sign-out whose clear is refused that way says
893
+ `kept`: the store holds a newer sign-in, or nothing. Any other throw is read as the store failing,
894
+ and the sign-out says `failed`. The key is the stored refresh token, or the access token when it has
895
+ none or an empty one (`refreshToken || accessToken`). Here in memory:
402
896
 
403
897
  ```ts
404
898
  import { discover } from '@flipstream/sdk'
405
- import { createSession, type SessionTokens, type TokenUpdate } from '@flipstream/sdk/node'
899
+ import { createSession, StoreMovedOnError, type SessionTokens, type TokenUpdate } from '@flipstream/sdk/node'
406
900
 
407
901
  const server = await discover('https://auth.flipstream.io')
408
902
  if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
@@ -415,7 +909,7 @@ const session = createSession({
415
909
  tokens: () => stored,
416
910
  onTokens: (update: TokenUpdate) => {
417
911
  // Compare and set: only while the store's key is still the one this update replaces.
418
- if (stored === null || (stored.refreshToken || stored.accessToken) !== update.replaces) throw new Error('the store moved on')
912
+ if (stored === null || (stored.refreshToken || stored.accessToken) !== update.replaces) throw new StoreMovedOnError()
419
913
  if (update.kind === 'cleared') {
420
914
  stored = null
421
915
  return
@@ -477,16 +971,17 @@ await session.revoke()
477
971
  nothing.
478
972
  - **A process that dies holding it** holds the others off for about 10 s: a holder touches the file
479
973
  every second, and a waiter takes a file over once nobody has touched it for 10 s and it has
480
- watched it for 3 s. A sign-out, which has 10 s in all, takes over a file left 10 s or more before
481
- within about 3 s.
974
+ watched it for 3 s. A sign-out, which sends nothing after its 10 s, takes over a file left 10 s or
975
+ more before within about 3 s.
482
976
  - **On Ctrl-C,** Node ends the process without letting a held lock go, and the next process waits
483
977
  up to 10 s for it. An app that wants it gone sooner can handle SIGINT itself, and exit only once
484
978
  every hold of its lock has settled, as below: a hold still waiting for the file gives up at once,
485
- and one running its work finishes it. Waiting for the session's calls isn't enough:
486
- `token()` and `revoke()` can answer before their hold ends. Await `session.settled()` too, so the
487
- session's own work has finished before the exit. The keychain store's own helper ignores the
488
- Ctrl-C and finishes the step it's on, within that step's 30 s and at most 1 s after the app has
489
- gone; the lock file goes when that work settles, as long as the app waits for it, as below.
979
+ and one running its work finishes it. Waiting for the session's calls isn't enough: `token()` can
980
+ answer before its hold ends, and so can `revoke()` at its `signal`. Await `session.settled()`
981
+ too, so the session's own work has finished before the exit. The keychain store's own helper
982
+ ignores the Ctrl-C and finishes the step it's on, within that step's 30 s and at most 1 s after
983
+ the app has gone; the lock file goes when that work settles, as long as the app waits for it, as
984
+ below.
490
985
 
491
986
  ```ts
492
987
  import { homedir } from 'node:os'
@@ -566,7 +1061,11 @@ await session.revoke()
566
1061
  your saves on `store.lock`, and `{ lock, ...store }` swaps yours out without a word. Either way a
567
1062
  sign-in can land between a refresh's compare and its write.
568
1063
  - **Never call the session inside `store.lock`:** the lock isn't reentrant, so the call waits for
569
- the hold it's in, and fails at its own limit (`token()` at its `waitMs`, `revoke()` at 10 s).
1064
+ the hold it's in, and fails at its own limit (`token()` at its `waitMs`, `revoke()` once its turn
1065
+ gives up on the lock, 60 s on, with `cut`).
1066
+ - **Nor from your own `tokens` or `onTokens`,** if you wrap the store's: they run inside the
1067
+ session's own turn. A `revoke()` there waits for that turn for ever, answering only at its
1068
+ `signal`, and a `token()` answers only at its `waitMs`.
570
1069
 
571
1070
  ## In a browser
572
1071
 
@@ -577,6 +1076,9 @@ The main entry, `@flipstream/sdk`, runs in browsers with no Node polyfills. Only
577
1076
  in a browser.
578
1077
  - **The API must allow your page's origin (CORS).** The query API doesn't allow other origins yet,
579
1078
  so until it does, call it from a server.
1079
+ - **A browser sends no identification yet.** `app`, `agent` and `conversationId` are still
1080
+ required and checked, but none of "Which app sent a request"'s headers go from a page until the
1081
+ hosts' CORS allows them (query-planner#48); a page can't set `User-Agent` anyway.
580
1082
  - **Signing in from a page** uses the same two halves as the paste-back above:
581
1083
  - `startSignIn` gives the URL to send the person to, and a `pending` to keep, for instance in
582
1084
  `sessionStorage`;
@@ -638,30 +1140,53 @@ if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
638
1140
 
639
1141
  ## Results, not exceptions
640
1142
 
641
- Every call settles into a result: `{ ok: true, data }` or `{ ok: false, error }`. A call rejects
642
- only on a programming error. For instance, a request that can't be sent as JSON (a `BigInt`, a
643
- cycle) rejects with the `TypeError`, and nothing is sent. `orThrow(result)` gives the data, or
644
- throws the failure as an `ApiFailure` carrying its `error`, for callers who'd rather catch.
645
-
646
- - **`fs.catalog.list()`** gives a `Catalog`.
647
- - **`fs.catalog.get({ source })`** gives a `CatalogSource`: a source plus `catalogVersion`.
648
- - **`fs.query(request)`** gives a `QueryResponse`, with `rows` and `lastRow`, and sometimes
649
- `totals` and `timings`. Only the request's declared fields are sent: `source`, `connection_id`,
650
- `dimensions`, `metrics`, `filters`, `sort`, `offset` and `rows`. A request with any other key,
651
- `table` included, is `refused` with nothing sent, and `error.fields` names each one, so a
652
- misspelt field never quietly changes the numbers.
1143
+ Every call settles into a result: `{ ok: true, data }` or `{ ok: false, error }`, each with the
1144
+ call's `traceId` when a request went out (see "Finding a request in Logs"). A call rejects only on a
1145
+ programming error. For instance, a request that can't be sent as JSON (a `BigInt`, a cycle) rejects
1146
+ with the `TypeError`, and nothing is sent. `orThrow(result)` gives the data, or throws the failure
1147
+ as an `ApiFailure` carrying its `error`, for callers who'd rather catch.
1148
+
1149
+ - **`flipstream.catalog.list()`** gives a `Catalog`.
1150
+ - **`flipstream.catalog.get({ source })`** gives a `CatalogSource`: a source plus `catalogVersion`.
1151
+ - **`flipstream.query(request)`** gives a `QueryResponse`, with `rows` and `lastRow`, and sometimes
1152
+ `totals` and `timings`. Only the request's declared fields are sent: `source`, `dataset_id`,
1153
+ `dimensions`, `metrics`, `filters`, `sort`, `offset` and `rows`. The query API names the dataset
1154
+ `connection_id`, so `dataset_id` goes as that, and the API's own errors may say so. A request
1155
+ with any other key, `table` and `connection_id` included, is `refused` with nothing sent, and
1156
+ `error.fields` names each one, so a misspelt field never quietly changes the numbers.
653
1157
  - **`refusedQueryFields(request)`** runs that check on its own, with no client and nothing
654
- sent. It gives the same names, sorted, or `[]` for a request `fs.query` would send. So an
655
- app can refuse a request before anything else it does: a CLI given a raw JSON body, for
1158
+ sent. It gives the same names, sorted, or `[]` for a request `flipstream.query` would send.
1159
+ So an app can refuse a request before anything else it does: a CLI given a raw JSON body, for
656
1160
  instance, before its other calls. It reads only the keys; a missing `source` is still the
657
1161
  API's to refuse.
658
- - **`fs.health()`** gives the planner's answer to `GET /health`, an object of strings
1162
+ - **`flipstream.health()`** gives the planner's answer to `GET /health`, an object of strings
659
1163
  (`{ status: 'ok' }` today). It works signed out: no token is asked for or sent, so it tells "the
660
1164
  service is down" from "the sign-in is wrong".
1165
+ - **`flipstream.me()`** gives a `Me`: your organisation and you in it, and
1166
+ **`flipstream.organization.rename()`** answers `needs_person` (see "Who you are").
1167
+ - **`flipstream.workspaces.list({ limit, offset })`** gives a `Page<Workspace>`, and
1168
+ **`flipstream.workspaces.get({ workspace_id })`** and **`create({ name })`** a `Workspace` (see
1169
+ "Workspaces").
1170
+ - **`flipstream.log.list()`** gives a `Page<LogEntry>`, **`flipstream.log.get()`**, **`add()`** and
1171
+ **`update()`** a `LogEntry`, and **`remove()`** `null` (see "A workspace's logbook").
1172
+ - **`flipstream.datasets.list()`** gives a `Page<Dataset>`, **`flipstream.datasets.get()`**,
1173
+ **`pause()`** and **`resume()`** a `Dataset`, **`delete()`** answers `needs_person`, and
1174
+ **`flipstream.datasetTypes.list()`** gives the `DatasetType`s this version knows (see "A
1175
+ workspace's datasets").
1176
+ - **`flipstream.credentials.list({ limit, offset })`** gives a `Page<Credential>`, and
1177
+ **`revoke()`** and **`delete()`** answer `needs_person` (see "Sign-ins to your sources").
1178
+ - **`flipstream.wallet.balance()`** gives a `Balance` or `null`, and
1179
+ **`flipstream.wallet.transactions()`** a `Ledger` (see "Wallet").
1180
+ - **`flipstream.members.list({ limit, offset })`** gives a `Page<Member>`, and
1181
+ **`flipstream.members.get({ member_id })`** a `Member` (see "Your organisation's members").
661
1182
 
662
1183
  **Every answer is checked against the API's spec.** An answer that doesn't match, with a missing
663
1184
  field or a value of the wrong type, is an `invalid` failure that names the field. It never comes
664
- back as data. A field the SDK doesn't know yet is kept.
1185
+ back as data. Some of a dataset's fields are read more leniently, so one new or missing backend
1186
+ value never makes a workspace's datasets unreadable: a `type` this version doesn't know is kept as
1187
+ it came, `created_on` and `created_by_id` are `null` when missing, and `history` is `null` when
1188
+ missing or when it holds a value this version doesn't know (see "A workspace's datasets"). A field the SDK doesn't know yet is kept, except in the answers of `me()`,
1189
+ `workspaces`, `log`, `datasets`, `wallet` and `members`, which hold only the fields their types name.
665
1190
 
666
1191
  ## Typed errors
667
1192
 
@@ -674,18 +1199,37 @@ back as data. A field the SDK doesn't know yet is kept.
674
1199
  | `invalid` | Outside the contract: an answer that isn't JSON or doesn't match its type, or a status no API sends |
675
1200
  | `timeout` | The call's own deadline passed |
676
1201
  | `aborted` | The caller's `signal` fired |
677
- | `refused` | Nothing was sent, by rule: a destination that isn't one of the configured hosts over https, a `source` of `''`, `.` or `..`, or a query with keys it doesn't send, named in `fields` |
1202
+ | `refused` | Nothing was sent, by rule, and `reason` says which (below) |
678
1203
  | `no_token` | The token function failed, or gave no token. `cause` is what it threw |
679
1204
  | `cancelled` | The app's own transport cancelled the call, because the session it was made for moved on |
1205
+ | `needs_person` | A person does it, in the console: `action`, `why`, and `url` and `sees` where a console can be named. Nothing was changed |
680
1206
 
681
1207
  **A failure the API answered keeps its `status`.**
682
1208
  - It keeps the API's `code` and `message` when the body is an error body, or its `text` when it
683
- isn't (a proxy's `Bad gateway`).
1209
+ isn't (a proxy's `Bad gateway`). The sign-ins' and the datasets' own reads and writes keep no
1210
+ `text`, since a body there may hold a sign-in's value (see "Sign-ins to your sources" and "A
1211
+ workspace's datasets"). The reads of your organisation and a workspace beside them keep theirs.
684
1212
  - `isPlannerCode(error.code)` narrows the code to the ones the query API documents
685
1213
  (`PlannerErrorCode`), so a switch over them can be exhaustive. A code added since is kept as it
686
1214
  came.
687
1215
  - When the API asked the caller to wait, the failure keeps that as `retryAfterMs`.
688
1216
 
1217
+ **A `refused` call says why, in `reason`** (`RefusedReason`), and `orThrow`'s message names it,
1218
+ never the value:
1219
+
1220
+ | `reason` | When |
1221
+ |---|---|
1222
+ | `destination` | Not an allowed host: a configured one, or for sign-in the issuer's own, over https, or over http on this machine with `allowLocalhostHttp`, for the client as for sign-in |
1223
+ | `identification` | A value identifying the app, its agent or the conversation holds the access token (see "Which app sent a request") |
1224
+ | `path` | A `source` of `''`, `.` or `..`, which can't stay one path segment |
1225
+ | `conversation-id` | A call's own `conversationId` that breaks its rule |
1226
+ | `fields` | A query, or a write (`workspaces.create`, `log.add`, `update` or `remove`, `datasets.pause` or `resume`), with keys it doesn't send, each named in `fields` |
1227
+ | `pending` | Sign-in: a `pending` that isn't one, wasn't started by this app at this server, or whose token endpoint breaks its issuer's rule |
1228
+ | `callback` | Sign-in: a callback URL that can't be read |
1229
+
1230
+ Every refusal the SDK returns has a `reason`. The type leaves it optional, so an error your own
1231
+ code builds, such as a test double, may leave it out.
1232
+
689
1233
  ```ts
690
1234
  import { isPlannerCode, type ApiError } from '@flipstream/sdk'
691
1235
 
@@ -708,9 +1252,11 @@ function explain(error: ApiError): string {
708
1252
  case 'cancelled':
709
1253
  return 'Stopped.'
710
1254
  case 'refused':
711
- return error.fields === undefined ? 'Not sent.' : `Not sent: unknown field ${error.fields.join(', ')}`
1255
+ return error.fields === undefined ? `Not sent: ${error.reason ?? 'refused'}.` : `Not sent: unknown field ${error.fields.join(', ')}`
712
1256
  case 'no_token':
713
1257
  return 'No token to send.'
1258
+ case 'needs_person':
1259
+ return error.url === undefined ? error.why : `${error.why} ${error.url}`
714
1260
  default: {
715
1261
  const unhandled: never = error
716
1262
  return unhandled
@@ -729,8 +1275,9 @@ function explain(error: ApiError): string {
729
1275
  redirect (`parsePastedRedirect`, or `signInWithLoopback`'s `readPasted`).
730
1276
 
731
1277
  There, `refused` also covers an issuer that isn't https (unless it's http on this machine, with
732
- `allowLocalhostHttp`), and a `pending` that isn't one (from storage the app couldn't read back).
733
- Nothing is sent for either.
1278
+ `allowLocalhostHttp`), with `reason: 'destination'`; a `pending` that isn't one (from storage the
1279
+ app couldn't read back), with `reason: 'pending'`; and a callback URL that can't be read, with
1280
+ `reason: 'callback'`. Nothing is sent for any of them.
734
1281
 
735
1282
  ## Options
736
1283
 
@@ -739,16 +1286,21 @@ import { createFlipstream } from '@flipstream/sdk'
739
1286
 
740
1287
  declare const session: { accessToken(rejected?: string): Promise<string> }
741
1288
 
742
- const fs = createFlipstream({
1289
+ const flipstream = createFlipstream({
1290
+ app: { name: 'my-cli', version: '1.0.0' }, // required: see "Which app sent a request"
1291
+ agent: { name: 'claude-code', version: '2.1.0' }, // optional: the agent running the app
1292
+ conversationId: 'c-123', // optional: the conversation or run the calls belong to
743
1293
  // Asked before every attempt; after a 401, asked once more with the token the API refused.
744
1294
  token: ({ rejected }) => session.accessToken(rejected),
745
1295
  fetch: globalThis.fetch, // optional: every request goes through it
746
- hosts: { query: 'https://query.flipstream.io' }, // optional: the default
1296
+ hosts: { query: 'https://query.flipstream.io' }, // optional: the default; also auth, admin, wallet and console
747
1297
  onWarning: (message) => process.stderr.write(`${message}\n`), // optional: console.warn by default
748
1298
  })
749
1299
 
750
1300
  const controller = new AbortController()
751
- await fs.catalog.list({ signal: controller.signal, deadlineMs: 10_000 })
1301
+ await flipstream.catalog.list({ signal: controller.signal, deadlineMs: 10_000 })
1302
+ // A call may name its own conversation, and carry on the caller's W3C trace context.
1303
+ await flipstream.catalog.list({ conversationId: 'c-456', traceparent: '00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01' })
752
1304
  ```
753
1305
 
754
1306
  - **The token function** is asked before every attempt, so a renewed token is always the one sent.
@@ -758,14 +1310,16 @@ await fs.catalog.list({ signal: controller.signal, deadlineMs: 10_000 })
758
1310
  cookies are sent. Plain http to a loopback host needs `allowLocalhostHttp: true`, for development
759
1311
  only.
760
1312
  - **Retries:**
761
- - A read (`catalog`, `health`) is tried again after a 408, 429, 502, 503 or 504, or a
762
- connection that failed, at most twice. It waits as long as `Retry-After` asks, in seconds, or
1313
+ - A read (`catalog`, `health`, each of `me`'s) is tried again after a 408, 429, 502, 503 or
1314
+ 504, or a connection that failed, at most twice. It waits as long as `Retry-After` asks, in seconds, or
763
1315
  500 ms, then 1 s.
764
1316
  - `query` is never tried again: a timeout at the gateway may already have run on the warehouse.
1317
+ - `workspaces.create` is never tried again either: it writes, and an answer that never came may
1318
+ still have made the workspace.
765
1319
  - `no_token` and `refused` are never tried again.
766
1320
  - A wait that wouldn't end before the deadline isn't started.
767
- - **Deadlines:** 60 s for `query`, 10 s for `health` and 30 s for the rest, every attempt and
768
- wait included. `deadlineMs` sets one call's.
1321
+ - **Deadlines:** 60 s for `query`, 10 s for `health` and 30 s for the rest (for `me`, its three
1322
+ reads together), every attempt and wait included. `deadlineMs` sets one call's.
769
1323
  - **Abort:** `signal` ends a call at once, also while it waits for a token or to try again.
770
1324
  - **Warnings:** the SDK's warnings go to `onWarning`, or to `console.warn` without it; `() => {}`
771
1325
  silences them. Today there is one kind: a catalogue format type this version doesn't know,
@@ -776,6 +1330,93 @@ await fs.catalog.list({ signal: controller.signal, deadlineMs: 10_000 })
776
1330
  it never goes through your transport: it goes to the query host, over https, with the global
777
1331
  `fetch`.
778
1332
 
1333
+ ## Which app sent a request
1334
+
1335
+ Every signed-in request says which app sent it, and, when you name them, which agent and
1336
+ conversation, so a later query log can show who asked what. It reports nothing beyond the request:
1337
+ the SDK has no telemetry. In Node, each signed-in request to an API host carries:
1338
+
1339
+ | Header | Value | Standard |
1340
+ |---|---|---|
1341
+ | `User-Agent` | `<app>/<version> flipstream-sdk/<version> node/<version>` | RFC 9110 product tokens |
1342
+ | `traceparent` | one trace-id per call, kept across its retries and shared by all of a call's requests, with a new parent-id for each request | W3C Trace Context |
1343
+ | `baggage` | `gen_ai.agent.name`, `gen_ai.agent.version` and `gen_ai.conversation.id`, percent-encoded, only those given | W3C Baggage, with OpenTelemetry's GenAI names (not stable yet) |
1344
+
1345
+ - **`app` is required;** `agent` and `conversationId` are optional, and a call's own
1346
+ `conversationId` replaces the client's for that call.
1347
+ - **Strict values:** names and versions are 1 to 64 of RFC 9110's token characters (letters,
1348
+ digits and ``!#$%&'*+-.^_`|~``); `conversationId` is 1 to 128 of A-Z, a-z, 0-9, `.`, `_`, `:`
1349
+ and `-`. Anything else is a TypeError at creation, which names the option but not its value. A
1350
+ call's `conversationId` that breaks the rule is `refused`, with nothing sent.
1351
+ - **Never the token:** a call whose `app`, `agent` or `conversationId` holds the access token is
1352
+ `refused`, with nothing sent. A token of 16 characters or more is looked for anywhere in a value.
1353
+ A shorter one, which only tests and local servers use, counts only when a value equals it, so it
1354
+ can't refuse an ordinary value that happens to contain it. With your own transport, the SDK never
1355
+ sees the token, so that check is your transport's.
1356
+ - **`health` says only who the SDK is.** It's signed out and asks for no token, so it sends
1357
+ `User-Agent: flipstream-sdk/<version> node/<version>` and a `traceparent`, and none of `app`,
1358
+ `agent` or `conversationId`: nothing could check them there.
1359
+ - **Your trace:** pass `traceparent` on a call to carry on your own trace. The call keeps its
1360
+ trace-id and flags, with its own parent-id for each request. One that isn't a valid version-00
1361
+ traceparent is dropped, as W3C Trace Context says, and the call starts its own trace, sampled
1362
+ (`01`).
1363
+ - **Only to the API hosts.** The auth server never gets them: `discover`, sign-in, refresh and
1364
+ revoke send none.
1365
+ - **Not from a browser yet:** see "In a browser".
1366
+
1367
+ ## Finding a request in Logs
1368
+
1369
+ Every result says which trace its call's requests carried, as `traceId`, so a person can find them
1370
+ in Logs:
1371
+
1372
+ ```ts
1373
+ import { createFlipstream } from '@flipstream/sdk'
1374
+
1375
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
1376
+
1377
+ const result = await flipstream.catalog.list()
1378
+ if (!result.ok) console.error(`${result.error.kind} (request ${result.traceId ?? 'not sent'})`)
1379
+ ```
1380
+
1381
+ - **On both arms:** `{ ok: true, data, traceId }` and `{ ok: false, error, traceId }`. It's the
1382
+ W3C trace-id the call's `traceparent` carried: 32 lowercase hex digits.
1383
+ - **One call, one trace:** a call that makes several requests, such as `me()`'s reads or
1384
+ `workspaces.list()`'s two, sends them all under one trace-id, each with its own parent-id. So
1385
+ does a retry, and the resend after a 401.
1386
+ - **Your trace:** a call given your own `traceparent` keeps it, and `traceId` is its trace-id.
1387
+ - **Nothing sent, no `traceId`:** a call `refused` before anything is sent (a path, fields,
1388
+ identification, the conversation's id, the destination) has none, and neither does a `no_token`
1389
+ from the first ask for a token.
1390
+ - **Once a request went out, the call has one,** whatever comes after: a `no_token` when the token
1391
+ function fails after a 401 (the refused request is the one to look up), or a `timeout` while a
1392
+ request is on its way. "Went out" means the SDK handed it to `fetch`: a host that was never
1393
+ reached (refused, or not found by DNS) gives `unavailable` with a `traceId` that no host logged.
1394
+ - **`orThrow`'s message ends with `(request <traceId>)`** when there is one, so a CLI or an app
1395
+ that prints the error carries the id with no code of its own. The `ApiFailure` it throws has the
1396
+ id as `traceId` too, for a log field or an error tracker's tag:
1397
+
1398
+ ```ts
1399
+ import { ApiFailure, createFlipstream, orThrow } from '@flipstream/sdk'
1400
+
1401
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
1402
+
1403
+ try {
1404
+ orThrow(await flipstream.catalog.list())
1405
+ } catch (error) {
1406
+ if (error instanceof ApiFailure) console.error(error.error.kind, error.traceId ?? 'not sent')
1407
+ }
1408
+ ```
1409
+
1410
+ It's there only when the result had one, and only as a W3C trace-id.
1411
+ - **Only what reaches the API hosts is in it:** the auth server gets no `traceparent`, so a read
1412
+ made there, such as `me()`'s userinfo and person, isn't in the call's trace.
1413
+ - **With your own transport,** the SDK can't see the request leave, so a result has `traceId` once
1414
+ an answer came back.
1415
+ - **Not from a browser yet:** a browser sends no `traceparent` (see "In a browser"), so its results
1416
+ have no `traceId`.
1417
+ - **The service's side:** finding the id needs the API hosts to log it, and Logs to index it. Until
1418
+ then, the id is still the one to quote.
1419
+
779
1420
  ## Which version is running
780
1421
 
781
1422
  ```ts