@macro-inc/sdk 0.0.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/README.md +628 -21
  2. package/dist/{chunk-5HAKQN23.js → chunk-7LVVPVNT.js} +70 -57
  3. package/dist/{chunk-JXIQT5TH.js → chunk-7YJ6Y7HJ.js} +234 -16
  4. package/dist/chunk-LMJW65ML.js +836 -0
  5. package/dist/{chunk-SGAHIERJ.js → chunk-OGE7WXJE.js} +16 -0
  6. package/dist/chunk-PRUFPW3B.js +943 -0
  7. package/dist/{chunk-CTKR64MY.js → chunk-QVBNNMQS.js} +242 -367
  8. package/dist/{chunk-QNUS5BC5.js → chunk-SUINKDXF.js} +30 -84
  9. package/dist/{chunk-77EI4LSQ.js → chunk-ZQXOHNDB.js} +1518 -386
  10. package/dist/generated/agent-harness/index.d.ts +1 -1
  11. package/dist/generated/agent-harness/index.js +1 -1
  12. package/dist/generated/agent-harness/sdk.gen.d.ts +174 -4
  13. package/dist/generated/agent-harness/types.gen.d.ts +2511 -189
  14. package/dist/generated/auth/index.d.ts +1 -1
  15. package/dist/generated/auth/index.js +1 -1
  16. package/dist/generated/auth/sdk.gen.d.ts +106 -8
  17. package/dist/generated/auth/types.gen.d.ts +1473 -116
  18. package/dist/generated/calendar/client/client.gen.d.ts +2 -0
  19. package/dist/generated/calendar/client/index.d.ts +10 -0
  20. package/dist/generated/calendar/client/types.gen.d.ts +120 -0
  21. package/dist/generated/calendar/client/utils.gen.d.ts +37 -0
  22. package/dist/generated/calendar/client.gen.d.ts +12 -0
  23. package/dist/generated/calendar/core/auth.gen.d.ts +25 -0
  24. package/dist/generated/calendar/core/bodySerializer.gen.d.ts +25 -0
  25. package/dist/generated/calendar/core/params.gen.d.ts +43 -0
  26. package/dist/generated/calendar/core/pathSerializer.gen.d.ts +33 -0
  27. package/dist/generated/calendar/core/queryKeySerializer.gen.d.ts +18 -0
  28. package/dist/generated/calendar/core/serverSentEvents.gen.d.ts +71 -0
  29. package/dist/generated/calendar/core/types.gen.d.ts +83 -0
  30. package/dist/generated/calendar/core/utils.gen.d.ts +19 -0
  31. package/dist/generated/calendar/index.d.ts +2 -0
  32. package/dist/generated/calendar/index.js +6 -0
  33. package/dist/generated/calendar/sdk.gen.d.ts +95 -0
  34. package/dist/generated/calendar/types.gen.d.ts +1091 -0
  35. package/dist/generated/cognition/index.d.ts +1 -1
  36. package/dist/generated/cognition/index.js +1 -1
  37. package/dist/generated/cognition/sdk.gen.d.ts +6 -1
  38. package/dist/generated/cognition/types.gen.d.ts +304 -36
  39. package/dist/generated/connection/types.gen.d.ts +1 -1
  40. package/dist/generated/email/index.d.ts +1 -1
  41. package/dist/generated/email/index.js +1 -1
  42. package/dist/generated/email/sdk.gen.d.ts +32 -27
  43. package/dist/generated/email/types.gen.d.ts +586 -409
  44. package/dist/generated/notification/index.d.ts +1 -1
  45. package/dist/generated/notification/types.gen.d.ts +384 -19
  46. package/dist/generated/properties/types.gen.d.ts +8 -5
  47. package/dist/generated/scheduled-action/index.d.ts +1 -1
  48. package/dist/generated/scheduled-action/index.js +3 -842
  49. package/dist/generated/scheduled-action/sdk.gen.d.ts +3 -1
  50. package/dist/generated/scheduled-action/types.gen.d.ts +277 -41
  51. package/dist/generated/search/index.d.ts +1 -1
  52. package/dist/generated/search/types.gen.d.ts +262 -43
  53. package/dist/generated/storage/index.d.ts +1 -1
  54. package/dist/generated/storage/index.js +1 -1
  55. package/dist/generated/storage/sdk.gen.d.ts +678 -107
  56. package/dist/generated/storage/types.gen.d.ts +14827 -5995
  57. package/dist/generated/unfurl/index.d.ts +1 -1
  58. package/dist/generated/unfurl/index.js +3 -832
  59. package/dist/generated/unfurl/types.gen.d.ts +20 -0
  60. package/dist/src/config.d.ts +33 -13
  61. package/dist/src/entities/agent-sessions/agent-session.d.ts +150 -6
  62. package/dist/src/entities/agent-sessions/code-execution.d.ts +43 -0
  63. package/dist/src/entities/agent-sessions/conversation.d.ts +54 -0
  64. package/dist/src/entities/agent-sessions/namespace.d.ts +23 -5
  65. package/dist/src/entities/agent-sessions/queued-action.d.ts +46 -0
  66. package/dist/src/entities/agent-sessions/review.d.ts +107 -0
  67. package/dist/src/entities/agent-sessions/tool-approval.d.ts +21 -0
  68. package/dist/src/entities/agents/agent.d.ts +47 -0
  69. package/dist/src/entities/agents/namespace.d.ts +13 -0
  70. package/dist/src/entities/ai/namespace.d.ts +24 -0
  71. package/dist/src/entities/api-keys/api-key.d.ts +17 -0
  72. package/dist/src/entities/api-keys/namespace.d.ts +18 -0
  73. package/dist/src/entities/calendar/calendar.d.ts +35 -0
  74. package/dist/src/entities/calendar/event.d.ts +123 -0
  75. package/dist/src/entities/calendar/event.test.d.ts +1 -0
  76. package/dist/src/entities/calendar/namespace.d.ts +111 -0
  77. package/dist/src/entities/calendar/replacement.d.ts +15 -0
  78. package/dist/src/entities/calls/call-record.d.ts +62 -6
  79. package/dist/src/entities/calls/message.d.ts +33 -0
  80. package/dist/src/entities/channels/activity.d.ts +24 -0
  81. package/dist/src/entities/channels/channel.d.ts +44 -3
  82. package/dist/src/entities/channels/labels.d.ts +39 -0
  83. package/dist/src/entities/channels/message.d.ts +9 -17
  84. package/dist/src/entities/channels/namespace.d.ts +6 -0
  85. package/dist/src/entities/channels/picture.d.ts +11 -0
  86. package/dist/src/entities/channels/post.d.ts +1 -1
  87. package/dist/src/entities/channels/thread.d.ts +5 -0
  88. package/dist/src/entities/chats/chat.d.ts +11 -1
  89. package/dist/src/entities/chats/generation.d.ts +46 -0
  90. package/dist/src/entities/crm/comment.d.ts +55 -34
  91. package/dist/src/entities/crm/company.d.ts +42 -10
  92. package/dist/src/entities/crm/contact.d.ts +42 -10
  93. package/dist/src/entities/crm/namespace.d.ts +18 -1
  94. package/dist/src/entities/crm/pipeline.d.ts +122 -0
  95. package/dist/src/entities/crm/pipelines.d.ts +14 -0
  96. package/dist/src/entities/databases/column.d.ts +75 -0
  97. package/dist/src/entities/databases/database.d.ts +272 -0
  98. package/dist/src/entities/databases/namespace.d.ts +21 -0
  99. package/dist/src/entities/databases/query.d.ts +86 -0
  100. package/dist/src/entities/databases/row.d.ts +27 -0
  101. package/dist/src/entities/databases/table.d.ts +61 -0
  102. package/dist/src/entities/databases/view.d.ts +40 -0
  103. package/dist/src/entities/databases/webhook.d.ts +32 -0
  104. package/dist/src/entities/documents/anchor.d.ts +29 -0
  105. package/dist/src/entities/documents/comment.d.ts +25 -22
  106. package/dist/src/entities/documents/document.d.ts +60 -12
  107. package/dist/src/entities/documents/namespace.d.ts +30 -0
  108. package/dist/src/entities/documents/version.d.ts +22 -0
  109. package/dist/src/entities/email/draft.d.ts +79 -0
  110. package/dist/src/entities/email/filter.d.ts +34 -0
  111. package/dist/src/entities/email/link.d.ts +6 -4
  112. package/dist/src/entities/email/message.d.ts +12 -1
  113. package/dist/src/entities/email/namespace.d.ts +34 -1
  114. package/dist/src/entities/email/thread.d.ts +23 -1
  115. package/dist/src/entities/entity-mentions/mention.d.ts +16 -0
  116. package/dist/src/entities/entity-mentions/namespace.d.ts +12 -0
  117. package/dist/src/entities/entity.d.ts +7 -0
  118. package/dist/src/entities/favorites/namespace.d.ts +14 -2
  119. package/dist/src/entities/foreign/foreign-entity.d.ts +2 -0
  120. package/dist/src/entities/foreign/namespace.d.ts +40 -0
  121. package/dist/src/entities/forms/form.d.ts +227 -0
  122. package/dist/src/entities/forms/namespace.d.ts +18 -0
  123. package/dist/src/entities/forms/question.d.ts +37 -0
  124. package/dist/src/entities/forms/response.d.ts +32 -0
  125. package/dist/src/entities/forms/section.d.ts +19 -0
  126. package/dist/src/entities/github-pull-requests/namespace.d.ts +12 -0
  127. package/dist/src/entities/github-pull-requests/pull-request.d.ts +52 -0
  128. package/dist/src/entities/harnesses/harness.d.ts +19 -0
  129. package/dist/src/entities/harnesses/namespace.d.ts +33 -0
  130. package/dist/src/entities/harnesses/pairing.d.ts +39 -0
  131. package/dist/src/entities/initiatives/initiative.d.ts +50 -0
  132. package/dist/src/entities/initiatives/namespace.d.ts +13 -0
  133. package/dist/src/entities/meetings/meeting.d.ts +38 -0
  134. package/dist/src/entities/meetings/namespace.d.ts +18 -0
  135. package/dist/src/entities/messages/thread.d.ts +101 -0
  136. package/dist/src/entities/notifications/notification.d.ts +6 -3
  137. package/dist/src/entities/notifications/notification.test.d.ts +1 -0
  138. package/dist/src/entities/projects/project.d.ts +7 -0
  139. package/dist/src/entities/reference.d.ts +82 -0
  140. package/dist/src/entities/routines/namespace.d.ts +15 -0
  141. package/dist/src/entities/routines/routine.d.ts +115 -0
  142. package/dist/src/entities/sharing/access.d.ts +65 -0
  143. package/dist/src/entities/sharing/permissions.d.ts +13 -0
  144. package/dist/src/entities/tasks/namespace.d.ts +4 -0
  145. package/dist/src/entities/tasks/task.d.ts +6 -0
  146. package/dist/src/entities/unfurls/namespace.d.ts +10 -0
  147. package/dist/src/entities/webhooks/webhook.d.ts +3 -1
  148. package/dist/src/entities/workspace/items.d.ts +7 -0
  149. package/dist/src/entities/workspace/namespace.d.ts +83 -0
  150. package/dist/src/entities/workspace/query.d.ts +12 -0
  151. package/dist/src/entities/workspace/types.d.ts +96 -0
  152. package/dist/src/events/hydrate/agentSession.d.ts +192 -0
  153. package/dist/src/events/hydrate/channel.d.ts +2 -39
  154. package/dist/src/events/hydrate/message.d.ts +70 -0
  155. package/dist/src/events/receiver.d.ts +57 -19
  156. package/dist/src/events/types.d.ts +3 -1
  157. package/dist/src/macro.d.ts +80 -3
  158. package/dist/src/macro.js +8832 -2784
  159. package/dist/src/utils/activity.d.ts +11 -0
  160. package/dist/src/utils/activity.test.d.ts +1 -0
  161. package/dist/src/utils/client.d.ts +10 -1
  162. package/dist/src/utils/concurrency.d.ts +5 -0
  163. package/dist/src/utils/index.d.ts +1 -0
  164. package/dist/src/utils/pagination.d.ts +9 -4
  165. package/package.json +11 -3
package/README.md CHANGED
@@ -1,9 +1,17 @@
1
1
  Macro's SDK: a Typescript library for harnessing the power of Macro
2
2
 
3
+ **[Read the SDK documentation](https://sdk.macro.com)** — a quick start,
4
+ plain-English entity guide, and complete API reference, served by the SDK docs Worker.
5
+
3
6
  - **`generated/`**: generated Typescript types and a HeyAPI client from Macro's
4
7
  OpenAPI specs.
5
8
  - **`src/`**: a hand-written ergonomic SDK layer that provides an "orm"-y API.
6
9
 
10
+ The [SDK reference build](../sdk-docs/README.md) uses TypeDoc to generate linked
11
+ Markdown and HTML from these sources. The [generated Markdown](../sdk-docs/reference/README.md)
12
+ is checked in alongside SDK changes; the HTML can be served with the included
13
+ static docs Worker.
14
+
7
15
  ## Usage
8
16
 
9
17
  ### Getting started
@@ -18,27 +26,69 @@ const macro = new Macro({ }); // uses MACRO_API_KEY env var
18
26
 
19
27
  ### Authenticating
20
28
 
21
- The SDK can authenticate as a **user** (a Macro API token, sent as an
22
- `Authorization` bearer) or as a **bot** (an `mbot_` API key, created under
23
- Settings → Bots in the web app). With no explicit `auth`, the SDK falls back
24
- to the `MACRO_API_KEY` (user) or `MACRO_BOT_TOKEN` (bot) env var.
29
+ Every request the SDK sends carries exactly one Macro credential. There are three kinds.
30
+
31
+ | Credential | Minted in | Prefix | Acts as |
32
+ | --- | --- | --- | --- |
33
+ | API key | Settings → API Keys | `mak_` | the user who minted it |
34
+ | Bot token | Settings → Bots | `mbot_` | the bot, optionally on behalf of a user |
35
+ | Bearer token | a signed-in session | none (JWT) | the signed-in user |
36
+
37
+ #### API key
38
+
39
+ The default for scripts and integrations. Put the key in `MACRO_API_KEY` and construct with no options.
40
+
41
+ ```ts
42
+ import { Macro } from '@macro-inc/sdk';
43
+
44
+ const macro = new Macro({});
45
+ const me = await macro.users.me();
46
+ ```
47
+
48
+ Or pass it in code. `token` accepts an API key or a bearer token. The SDK picks the header from the prefix.
49
+
50
+ ```ts
51
+ const macro = new Macro({ token: process.env.MACRO_API_KEY });
52
+ ```
53
+
54
+ The explicit form names the credential kind. Use it when the key is not from an env var, or when it predates the `mak_` prefix.
25
55
 
26
56
  ```ts
27
- const asUser = new Macro({ auth: { type: 'user', token: myApiToken } });
28
- const asBot = new Macro({ auth: { type: 'bot', token: myBotKey } });
57
+ const macro = new Macro({
58
+ auth: { type: 'user', apiKey: process.env.MACRO_API_KEY },
59
+ });
29
60
  ```
30
61
 
31
- A bot can act on behalf of a user it's authorized for (its owner, or a member
32
- of its owning team):
62
+ An API key always acts as the user who minted it. `requestedAs` is bot-only.
63
+
64
+ #### Bot token
33
65
 
34
66
  ```ts
67
+ const asBot = new Macro({ auth: { type: 'bot', token: process.env.MACRO_BOT_TOKEN } });
35
68
  const asWolf = asBot.requestedAs('macro|wolf@macro.com');
36
69
  ```
37
70
 
38
- Bot requests carry an access scope: `user` (the requested-as user's access —
39
- the default whenever `requestedAs` is used) or `team` (the owning team's
40
- access, for team-owned bots — the default otherwise). Pass
41
- `auth: { type: 'bot', token, scope: ... }` to override.
71
+ Bot requests carry an access scope. `user` uses the requested-as user's access, and is the default when `requestedAs` is set. `team` uses the owning team's access, for team-owned bots, and is the default otherwise. Pass `auth: { type: 'bot', token, scope: ... }` to override.
72
+
73
+ #### Bearer token
74
+
75
+ A session token, for code running with a signed-in user. Sent as `Authorization: Bearer`. The function form refreshes it.
76
+
77
+ ```ts
78
+ const macro = new Macro({ auth: { type: 'user', token: () => session.accessToken() } });
79
+ ```
80
+
81
+ #### Which header goes out
82
+
83
+ The backend rejects a request carrying two credentials with `400 ambiguous credentials`. The SDK sets exactly one.
84
+
85
+ | You passed | Header sent |
86
+ | --- | --- |
87
+ | `apiKey: '…'` | `x-macro-user-api-key: …` |
88
+ | `token: 'mak_…'` or `MACRO_API_KEY=mak_…` | `x-macro-user-api-key: mak_…` |
89
+ | `token: '<jwt>'` or `MACRO_API_KEY=<jwt>` | `Authorization: Bearer <jwt>` |
90
+ | `token: 'mbot_…'` | throws. Use `auth: { type: 'bot', token }` or `MACRO_BOT_TOKEN`. |
91
+ | `type: 'bot'` | `x-macro-bot-token` plus `x-macro-bot-scope` |
42
92
 
43
93
  ### Accessing our API
44
94
 
@@ -54,6 +104,36 @@ const owner = await doc.owner();
54
104
  const email = await owner.email();
55
105
  ```
56
106
 
107
+ ### Forms
108
+
109
+ Forms collect answers into a table. Respondents can read questions and submit
110
+ without permission to read the response database.
111
+
112
+ ```ts
113
+ const form = await macro.forms.create({ name: 'Workshop registration' });
114
+ const table = await form.table();
115
+ const name = await table.addColumn({ name: 'Name', type: { type: 'text' } });
116
+ await form.replaceLayout([
117
+ {
118
+ kind: 'questions',
119
+ title: 'About you',
120
+ questions: [{ column: name, required: true }],
121
+ },
122
+ ]);
123
+ const [question] = await form.questions();
124
+ if (!question) throw new Error('The form has no questions');
125
+ const receipt = await form.submit([
126
+ { question, value: { type: 'text', value: 'Ada' } },
127
+ ]);
128
+ ```
129
+
130
+ Pass `table` to `macro.forms.create` to ask about an existing table's columns.
131
+ `editResponse` replaces the caller's answers while the form is open;
132
+ `myResponse` reads only that caller's receipt. Editors use `responseSummary`,
133
+ and `tally` is available to viewers when the owner enables `tallyVisible`.
134
+ Use `sharePermissions` and `updateSharePermissions` for sharing grants, and
135
+ `update({ audience: 'public' })` to allow anonymous responses.
136
+
57
137
  ### Creating, mutating, and deleting
58
138
 
59
139
  ```ts
@@ -100,6 +180,150 @@ await doc.setProperty(macro.properties.byId('prop_status'), {
100
180
  const props = await doc.properties();
101
181
  ```
102
182
 
183
+ ### Databases
184
+
185
+ Databases are collections of tables. Tables, columns, and views are parts of
186
+ a database, not entities of their own, so they come back as handles that
187
+ resolve through the database's schema.
188
+
189
+ SQL is available through `database.query(sql)` or
190
+ `macro.databases.query(sql, { database })`. The scoped database resolves
191
+ unqualified names; joins can reach any other database the caller can view.
192
+ Results contain discriminated cell values, typed source rows and table-version
193
+ handles. SQL can also write; a statement executes once without automatic retries.
194
+
195
+ ```ts
196
+ const database = macro.databases.byId('database-id');
197
+ const result = await database.query('SELECT "Name" FROM "Guests"');
198
+ console.log(result.result?.rows);
199
+ await database.query(`UPDATE "Guests" SET "Status" = 'Going' WHERE "Name" = 'Sam'`, {
200
+ baseVersions: result.readVersions,
201
+ });
202
+ ```
203
+
204
+ `baseVersions` guards written tables atomically. Check `truncatedTables`:
205
+ nonempty means a read hit the row cap and aggregates may be partial. SQL schemas
206
+ are dynamic, so result cells use a generated tagged union rather than an inferred
207
+ TypeScript interface for each table. The HTTP route is `POST /databases/query`.
208
+
209
+ The SDK's schema methods write typed ops through one endpoint,
210
+ `POST /databases/{id}/ops`. The methods below each send a one-op batch: the
211
+ SDK mints the new table, column, and option ids (UUIDv7) itself and builds the
212
+ handle it returns from the op's result.
213
+
214
+ ```ts
215
+ const database = await macro.databases.create({ name: 'Events' });
216
+ const guests = await database.createTable({ name: 'Guests' });
217
+ const email = await guests.addColumn({ name: 'Email', type: { type: 'text' } });
218
+
219
+ // A select column only accepts labels you give it, at creation or later.
220
+ const rsvp = await guests.addColumn({
221
+ name: 'RSVP',
222
+ type: { type: 'select', multi: false },
223
+ options: ['Yes', 'No'],
224
+ after: email,
225
+ });
226
+ await rsvp.addOptions(['Maybe']); // labels it already has are skipped
227
+
228
+ await guests.rename('Attendees');
229
+ await rsvp.rename('Response');
230
+
231
+ // A relation column holds rows of another table, named by handle.
232
+ const hosts = await database.createTable({ name: 'Hosts' });
233
+ await guests.addColumn({
234
+ name: 'Host',
235
+ type: { type: 'relation', table: hosts },
236
+ });
237
+
238
+ // See what each type change would do to the existing values first.
239
+ const casts = await rsvp.casts();
240
+ await rsvp.changeType({ to: { type: 'select', multi: true } });
241
+
242
+ // A type change converts every value or refuses, naming the misfits. To keep
243
+ // the original, add a column of the new type after it, filled with the values
244
+ // that convert ("Response (Text)" unless you pass a name).
245
+ await rsvp.convertIntoNewColumn({ to: { type: 'text' } });
246
+
247
+ // Tabs: a new database starts with a "Table 1". Reorder by naming every
248
+ // table once, or delete one; a database keeps at least one.
249
+ const tables = await database.tables();
250
+ await database.reorderTables(tables.toReversed());
251
+ await (await database.table('Table 1'))?.delete();
252
+ ```
253
+
254
+ Changing a column's type, reordering columns, and deleting a column send the
255
+ table version last read as the batch's base version: if the table changed
256
+ since, the server refuses with a 409 and nothing is written.
257
+ `convertIntoNewColumn` is the exception to one op per call: it reads the
258
+ conversion (`POST …/columns/{c}/conversion`, which changes nothing), then sends
259
+ one batch that creates the column and fills it, at the version that read saw.
260
+
261
+ To do several things at once, send the ops yourself. They apply in order in
262
+ one transaction, later ops see what earlier ones did, and a refused op leaves
263
+ the whole batch unwritten. Each op names the resource it changes (a `table`,
264
+ `column`, `rows`, or `view`) and what `change` it makes; each result answers
265
+ with the same `kind` and what happened as its own `change`. Ids for new
266
+ tables, columns, options, and views are yours to mint, so a later op of the
267
+ batch can name them:
268
+
269
+ ```ts
270
+ import { v7 as uuidv7 } from 'uuid';
271
+
272
+ const notes = uuidv7();
273
+ const results = await database.applyOps(
274
+ [
275
+ {
276
+ kind: 'column',
277
+ table: guests.id,
278
+ column: notes,
279
+ change: {
280
+ kind: 'create',
281
+ definition: { source: 'new', name: 'Notes', type: { type: 'text' } },
282
+ },
283
+ },
284
+ {
285
+ kind: 'rows',
286
+ table: guests.id,
287
+ change: {
288
+ kind: 'insert',
289
+ rows: [
290
+ [
291
+ { column: email.id, value: { type: 'text', value: 'ada@example.com' } },
292
+ { column: notes, value: { type: 'text', value: 'Vegetarian' } },
293
+ ],
294
+ ],
295
+ },
296
+ },
297
+ ],
298
+ { baseVersions: [{ table: guests, version: await guests.version() }] },
299
+ );
300
+ // results[1] is { kind: 'rows', table, tableVersion, change: { kind: 'inserted', rows: [rowId] } }
301
+ ```
302
+
303
+ A refusal throws `MacroOpRefusedError`, naming the op at fault (`op`, and
304
+ `row` / `column` when one is) and, when the batch minted an id that already
305
+ names something, that id as `taken` (`{ kind: 'table' | 'column' | 'option' |
306
+ 'view', id }`). A retried batch whose first attempt committed refuses this way.
307
+
308
+ ```ts
309
+ import { MacroOpRefusedError } from '@macro-inc/sdk';
310
+
311
+ try {
312
+ await database.createTable({ name: 'Guests' });
313
+ } catch (error) {
314
+ if (error instanceof MacroOpRefusedError) console.log(error.op, error.taken);
315
+ }
316
+ ```
317
+
318
+ A table's views are handles too. A board view reads where its cards sit:
319
+
320
+ ```ts
321
+ for (const view of await guests.views()) {
322
+ const layout = await view.layout();
323
+ if (layout.kind === 'board') console.log(await view.positions());
324
+ }
325
+ ```
326
+
103
327
  ### Rich message helper
104
328
 
105
329
  Use the `msg` tagged template to build rich message bodies for channel messages
@@ -130,33 +354,304 @@ await macro.channels
130
354
  .send(msg`Deploy ${sha} finished. ${here}`);
131
355
  ```
132
356
 
133
- # Webhook Events
357
+ ### Routines
358
+
359
+ Create scheduled or event-triggered agent tasks through `macro.routines`.
360
+ Routine configuration takes typed agent and event resource handles:
361
+
362
+ ```ts
363
+ const routine = await macro.routines.create({
364
+ name: 'Daily summary',
365
+ prompt: 'Summarize my open tasks.',
366
+ userPrompt: 'A daily task summary',
367
+ trigger: { type: 'cron', schedule: '0 9 * * *', timezone: 'America/New_York' },
368
+ });
369
+ await routine.setEnabled(false);
370
+ const transcript = await routine.execute(); // Chat or AgentSession, if available
371
+ const executions = await routine.history(); // Each retains its parent routine
372
+ ```
373
+
374
+ Event triggers use `{ type: 'events', filters: [{ events, entities, condition }] }`;
375
+ `entities` takes typed references such as `{ type: 'document', entity: doc }`.
376
+ Use `{ type: 'multiple', triggers: [...] }` to combine schedules and events.
377
+ `routine.update(options)` replaces task and trigger settings; `delete()` removes it.
378
+
379
+ ### Agents, conversations and hosts
380
+
381
+ `macro.agents.list/create/byId` manage agent configuration. `AgentOptions` takes
382
+ channel, team and host handles. Updates replace the configuration.
383
+ `channel.agentConversations()` returns conversations with session and turn handles;
384
+ `conversation.startFresh(session)` and `turn.retry(actionId)` expose explicit
385
+ conversation controls. `session.toolApprovalById(id).answer(answer)` answers a
386
+ permission request scoped to that session.
387
+
388
+ `macro.harnesses.list/me/byId` manages agent hosts. `createPairing(options)` returns
389
+ separate pairing and device handles plus a device secret. Approve through
390
+ `pairing.approve(...)`, then `device.claim(deviceSecret)`; a pending claim returns
391
+ `undefined`. Host tokens and device secrets are never stored in entity handles.
392
+ Self-host operations (`me`, `agents`, `sessions`, `deleteSelf`) require the backend's
393
+ host authentication; ordinary user or bot credentials do not grant those rights.
394
+
395
+ ### Drafts, filters and follow-ups
396
+
397
+ ```ts
398
+ const inbox = (await macro.email.links())[0];
399
+ const draft = await macro.email.createDraft({
400
+ subject: 'Follow-up',
401
+ to: [{ email: 'ada@example.com' }],
402
+ bodyHtml: '<p>Thanks for meeting.</p>',
403
+ }, inbox);
404
+ await draft.update({ subject: 'Follow-up notes', bodyText: 'Thanks for meeting.' });
405
+ const upload = await draft.addAttachment({ fileName: 'notes.txt', sha, size });
406
+ // Upload bytes to upload.uploadUrl, then verify before sending:
407
+ await upload.attachment.complete();
408
+ await draft.schedule('2026-11-01T09:00:00Z');
409
+ await draft.unschedule();
410
+ ```
134
411
 
135
- Pass a `webhookSecret` (or set `MACRO_WEBHOOK_SECRET`) to receive events. You
136
- should use a framework like Hono or Express to handle the webhook request and
137
- pass it to the SDK which will handle verification and dispatching.
412
+ HTML input is UTF-8 encoded for the wire contract. Draft writes retain the draft's
413
+ inbox selection, including delegated inboxes. `update` replaces content; omitted
414
+ recipients and body fields follow the server's replacement semantics.
415
+ `draft.forwardAttachment(attachment)` returns a draft-scoped attachment handle.
416
+ Use its `remove()` method to detach it. `email.scheduled({ inbox, pageSize })`
417
+ automatically pages; breaking iteration stops further requests.
418
+
419
+ `email.filters(inbox)` and `email.upsertFilter(options, inbox)` return filter handles
420
+ with `setImportant` and `delete`. Omit the inbox to select the caller's primary.
421
+ `email.contacts()` returns the service's address/interaction buckets.
422
+ `thread.calendarInvitations()` reads resolved invitations. `thread.followup()` and
423
+ `thread.setFollowup(command)` expose revision-aware reminder state; commands require
424
+ caller-persisted operation IDs. `email.reminders({ inboxes })` auto-paginates and
425
+ returns thread handles alongside reminder snapshots.
426
+
427
+ ### CRM pipelines and initiatives
428
+
429
+ `macro.crm.pipelines.create/list/byId` returns pipeline handles. Rename, sharing,
430
+ permissions and trash operations live on the pipeline. `pipeline.table()` returns
431
+ its table handle, with column and row handles. `rows()` and `queryRows({ rows, query })`
432
+ fetch through the pipeline's authorization boundary and auto-paginate.
433
+ `pipeline.applyOps(ops, { baseVersions: [{ table, version }] })` accepts the generated
434
+ atomic database operation contract, including batch-local UUIDs, like
435
+ `Database.applyOps`. Table and column reads share a schema cache invalidated by
436
+ successful batches. Call `row.refresh()` to reload a row after a batch changes it.
437
+
438
+ `macro.initiatives.create/list/byId` groups tasks and members. Relations return user
439
+ and task handles; `initiative.update({ name, members, sharePermission })` and
440
+ `delete()` manage it.
441
+
442
+ ### Access requests and message threads
443
+
444
+ Documents, chats, projects, initiatives, databases, calls, email threads and agent
445
+ sessions expose `.access`. `access.state()` returns review rights, typed requests,
446
+ and an optional continuation offset. `submit(level)`, `cancel(revision)`,
447
+ `request.resolve(level)`, `direct()`, `grant(user, level)`, and `remove(user)` use
448
+ server authorization and optimistic request revisions. Omit the level on
449
+ `request.resolve()` to decline. Resolved request handles retain their result even
450
+ after they leave the pending listing.
451
+
452
+ New sharing updates use `SharePermissionOptions`: channel grants name a channel
453
+ handle, operation (`add`, `replace`, `remove`) and optional access level.
454
+
455
+ Channels, documents, CRM companies/contacts and calls expose
456
+ `messageThreadById(id)` for thread resolution, anchor detachment and deletion.
457
+ `timelinePage({ messages, around, cursor, limit })` returns a mixed timeline with
458
+ seeded message handles and typed activity actors. Selectors must belong to the same
459
+ parent. Cursors are opaque; pass the returned cursor on the next request.
460
+ `channel.recordActivity(type)` records a view or interaction; `channels.activity()`
461
+ reads activity handles. `ChannelPicture.byId(uploadId)` references an uploaded
462
+ picture for `channel.setPicture(picture)`; omit it to clear the picture.
463
+
464
+ ### Meetings and calendar browsing
465
+
466
+ `macro.meetings.create/list/active/lookup` returns meeting handles. `list()` contains
467
+ the caller's newest 100 standalone meetings; use `lookup(invitationToken)` for
468
+ channel meetings and other invitations. A seeded meeting retains its lookup token
469
+ when mutations invalidate metadata. `update`, `cancel`, `invite(email)`,
470
+ `inviteUsers(users)`, `invitePermissions` and `webUrl` live on the meeting.
471
+ `call.meeting()` creates or reads its shareable meeting; calls also expose
472
+ `editTranscript(assignments)` and `toggleTeamShare()`.
473
+
474
+ `calendar.occurrences(viewport)` auto-paginates and seeds event handles.
475
+ `calendar.teamPage(viewport)` includes the roster and an optional next cursor;
476
+ `teamOutOfOffice(viewport)` reports `hasMore` when its bounded results are truncated.
477
+ `availabilityCalendars`, `calendar.setContributesToAvailability`, `teamSharing` and
478
+ `setTeamSharing` manage availability and sharing preferences.
479
+
480
+ ### Document lifecycle and other resources
481
+
482
+ `documents.createUpload(options)` reserves a binary document and returns upload
483
+ instructions. `document.prepareSave(parts)`, `save(options)` and `simpleSave()` expose
484
+ the existing content lifecycle; upload bytes before committing. Version handles
485
+ come from `document.version(number)`. PDF highlights and comment anchors are scoped
486
+ handles from `anchors()` / `createHighlight(options)`, with kind-checked edits and
487
+ deletion. `documents.byTeamSlug('ENG-42')` resolves a task reference.
488
+ `sharePermissions`, `permissionsToken` and `documents.validatePermissionsToken`
489
+ expose document access contracts.
490
+
491
+ `macro.githubPullRequests.byId(foreignEntityId)` reads stored GitHub snapshots;
492
+ `changes()` returns a changeset handle with `patch()`. `macro.entityMentions.create`
493
+ takes typed source/target references and returns a deletable mention handle.
494
+ `macro.unfurls.get(url)` and `bulk(urls)` read URL preview metadata.
495
+
496
+ `macro.apiKeys.create(name)` returns `{ key, secret }`. Save the secret immediately;
497
+ the handle only retains metadata. `list()` and `key.delete()` manage keys.
498
+ `tokenForEmail(email)` exchanges credentials subject to ordinary server authorization.
499
+
500
+ `chat.send({ content, model, attachments, toolset })` starts a generation and returns
501
+ its chat, response message and cancellable stream handle. Use
502
+ `generation.message.refresh()` after it changes; reading an unfinished response
503
+ may report that it is not yet available. Tools can perform writes unless disabled.
504
+ `macro.ai.usage({ from, until, users, features })` reads AI usage.
505
+
506
+ # Events
507
+
508
+ `macro.events` is always available. The default transport is a live SSE
509
+ stream — no public URL, persisted webhook, or signing secret required.
138
510
 
139
511
  ```ts
140
512
  const macro = new Macro({
141
513
  token: process.env.MACRO_API_KEY,
142
- webhookSecret: process.env.MACRO_WEBHOOK_SECRET,
143
514
  });
144
515
 
145
516
  const me = await macro.users.me();
146
517
 
147
- macro.events.on('channel.message_posted', async ({ metadata, message }) => {
518
+ macro.events.on('message.posted', async ({ metadata, target }) => {
148
519
  if (metadata.sender === me.id) return; // don't reply to ourselves
149
- await message.reply('hi!');
520
+ if (target.type === 'channel') await target.message.reply('hi!');
521
+ else await target.comment.reply('hi!');
522
+ });
523
+
524
+ const stop = await macro.events.listen();
525
+ // later: stop();
526
+ ```
527
+
528
+ `listen()` opens `GET /webhook/events/stream` with the same `WebhookFilters`
529
+ model as persisted webhooks. If you omit `filters`, it derives one filter from
530
+ the event names already registered with `.on()`. Pass `scope: 'team'` for a
531
+ team workspace (defaults to `'user'`). Delivery is best-effort: there is no
532
+ replay if you disconnect.
533
+
534
+ Handlers receive the same hydrated payloads as webhook deliveries — ORM
535
+ handles for every entity the event names.
536
+
537
+ Four families are delivered: `document.*`, `channel.*`, `message.*`, and
538
+ `agent_session.*`. Message events (`posted`, `patched`, `deleted`, `mentioned`,
539
+ `attachment_created`, `attachment_removed`) cover channel messages and document
540
+ comments alike: `metadata.parent` names the channel or document, and the
541
+ hydrated `target` carries a `Channel` plus `Message` (and the `Thread` for a
542
+ reply) or a `Document` plus `Comment`. `macro.events.onSelfMention` subscribes to
543
+ `message.mentioned` deliveries that name the caller.
544
+ Agent-session events describe a coding agent's life: `opened`, `turn_started`,
545
+ `turn_ended`, `settled` (a turn ended with nothing queued behind it),
546
+ `waiting_for_input` (the agent asked its owner a question), `input_received`,
547
+ `mentioned` (a prompt named other users who can see the session), `stopped`,
548
+ `renamed`, and `deleted`. Each carries the session's identity and
549
+ hydrates to an `AgentSession` handle, the owner `User`, and, for a session
550
+ opened from a channel thread, the `Channel`, `Thread`, and magic-chip
551
+ `Message` the turn renders into.
552
+
553
+ ```ts
554
+ macro.events.on('agent_session.settled', async ({ metadata, session, thread }) => {
555
+ console.log(`${metadata.identity.bot_name} finished: ${metadata.last_turn?.excerpt}`);
556
+ await thread?.reply(msg`Done — see ${session}`);
557
+ });
558
+ ```
559
+
560
+ ### Persisted webhooks
561
+
562
+ To receive the same events as HTTPS POSTs instead of (or in addition to) SSE,
563
+ register a webhook and pass a `webhookSecret` (or set `MACRO_WEBHOOK_SECRET`).
564
+ Use a framework like Hono or Express to handle the request; the SDK verifies
565
+ the signature and dispatches.
566
+
567
+ ```ts
568
+ const macro = new Macro({
569
+ token: process.env.MACRO_API_KEY,
570
+ webhookSecret: process.env.MACRO_WEBHOOK_SECRET,
571
+ });
572
+
573
+ macro.events.on('message.posted', async ({ metadata, target }) => {
574
+ if (metadata.sender === me.id || target.type !== 'channel') return;
575
+ await target.message.reply('hi!');
150
576
  });
151
577
 
152
578
  // Hono
153
579
  app.post('/webhook', (c) => macro.events.webhook()(c.req.raw));
154
580
  ```
155
581
 
582
+ Call chat events have `event.target.type === 'call'`, with a `CallRecord` in
583
+ `event.target.call` and a `CallMessage` in `event.target.message`. Read with
584
+ `content()`, or call `reply(body)`, `edit(body)`, and `delete()`. Replies always
585
+ join the call's single chat thread, even when responding to another reply.
586
+ `macro.calls.byId(callId).message(messageId)` creates the same lazy message handle.
587
+
588
+ # Upgrading to 0.2
589
+
590
+ Channel messages, document comments, and CRM company and contact comments share
591
+ one API, `/messages/{parent_type}/{parent_id}`, and the SDK entities follow it.
592
+ The old channel message, document comment, and CRM comment routes are removed
593
+ from the server in the same release, so 0.1 clients stop working against it.
594
+ The public `Channel`, `Message`, `Thread`, `Document`, `Company`, and `Contact`
595
+ methods keep their names; these details changed:
596
+
597
+ - `Channel.messages()` and `Channel.messagesAfter()` page with the structured
598
+ `MessageCursor` and yield `Message` handles seeded from the shared message
599
+ record (`mentions` are now populated from list reads too).
600
+ - `Channel.typing(action)` takes `'start' | 'stop'` and posts to
601
+ `/messages/channel/{id}/typing`.
602
+ - `Message.from(client, channelId, record)` replaces `Message.from(client, record)`,
603
+ `Message.fromReply`, and `Message.received`.
604
+ - `Comment` ids are message UUIDs: `Comment.commentId` is gone, `Comment.threadId()`
605
+ is async and returns the root comment id, `Comment.edit` accepts a rich body, and
606
+ `Comment.reply` exists. `Document.comment(body, { threadId })` takes a string
607
+ thread id and a rich body; `Document.comments()` returns `{ thread: ThreadState,
608
+ comments }` per live thread.
609
+ - `CrmComment` is a message-backed comment on its company or contact
610
+ (`parent: { type: 'crm_company' | 'crm_contact', id }`). Its ids are message
611
+ UUIDs (imported comments kept their old ids); `text`, `createdAt`,
612
+ `updatedAt`, and `deletedAt` are lazy accessors; `threadId()` and `author()`
613
+ are async; `edit` accepts a rich body; and `reply` exists. `owner`, `sender`,
614
+ `order`, and `metadata` are gone. `Company.comments()` and
615
+ `Contact.comments()` return `{ thread: ThreadState, comments }` per live
616
+ thread; `comment(body, { threadId })` replaces `comment({ text, threadId })`;
617
+ `commentById(id)` returns a handle; `editComment` and `deleteComment` are
618
+ replaced by `CrmComment.edit` and `CrmComment.delete`. Deleting a thread's
619
+ root keeps its replies, as it does for channel and document threads.
620
+ - Webhook and SSE events `channel.message_posted`, `channel.mentioned`,
621
+ `channel.message_patched`, `channel.message_deleted`,
622
+ `channel.message_attachment_created`, and `channel.message_attachment_removed`
623
+ are replaced by `message.posted`, `message.mentioned`, `message.patched`,
624
+ `message.deleted`, `message.attachment_created`, and
625
+ `message.attachment_removed`. Their metadata carries `parent` instead of
626
+ `channel_id`, and handlers receive `target` (see Events above) instead of
627
+ `channel`/`message`/`thread`. `onSelfMention` handlers now receive
628
+ `message.mentioned` events. Update persisted webhook filters accordingly.
629
+
630
+ Removed storage operations and their replacements: `getChannelMessages` →
631
+ `messageTimeline`; `getChannelMessagesCatchUp` → `messageTimeline` with
632
+ `activity_after`; `getThreadReplies` → `entityMessageGetThread`;
633
+ `getMessageWithContext` → `entityMessageGetMessage` / `messageTimeline` with
634
+ `around`; `postMessage` → `entityMessageCreate`; `patchMessage` →
635
+ `entityMessageEdit`; `deleteMessage` → `entityMessageDeleteMessage`;
636
+ `postReaction` → `entityMessageReact`; `postTyping` → `entityMessageTyping`;
637
+ `getDocumentComments` → `messageTimeline` + `entityMessageGetThread` on a
638
+ document parent; `createComment` → `entityMessageCreate`; `editComment` →
639
+ `entityMessageEdit`; `deleteComment` → `entityMessageDeleteMessage`;
640
+ `listCrmComments` → `messageTimeline` + `entityMessageGetThread` on a
641
+ `crm_company` or `crm_contact` parent; `createCrmComment` →
642
+ `entityMessageCreate`; `editCrmComment` → `entityMessageEdit`;
643
+ `deleteCrmComment` → `entityMessageDeleteMessage`.
644
+
156
645
  # Developing
157
646
 
158
647
  This section is just if you are contributing to the SDK.
159
648
 
649
+ ## Releases
650
+
651
+ See [Releasing the SDK](RELEASING.md) for patch version bumps, npm setup,
652
+ and tag-triggered publishing. Agents can use the
653
+ [`release-sdk`](../../.agents/skills/release-sdk/SKILL.md) skill.
654
+
160
655
  ## Coverage checking
161
656
 
162
657
  We have a coverage checker. It reads every generated function and ensures that
@@ -170,8 +665,120 @@ support by adding a wrapper to the appropriate model. There is CI to ensure that
170
665
  we don't forget to add coverage or explicitly skip coverage for new generated
171
666
  functions (endpoints).
172
667
 
173
- ## Webhook events
668
+ ## Events
174
669
 
175
670
  Event names and payloads are **generated from the backend**: the Rust webhook
176
671
  crate exposes a `WebhookEvent` union in the storage OpenAPI spec, and
177
- `src/events/types.ts` derives `EventName` / `EventPayload` from it.
672
+ `src/events/types.ts` derives `EventName` / `EventPayload` from it. SSE
673
+ (`listen()`) and persisted webhooks (`webhook()`) dispatch the same union.
674
+
675
+ ### AI generation and decisions
676
+
677
+ Shared cognition endpoints are available through `macro.ai`. They use the
678
+ authenticated user's model access and AI allowance. For generation using only
679
+ supplied context, explicitly set `toolset: { type: 'none' }`:
680
+
681
+ ```ts
682
+ const answer = await macro.ai.structuredCompletion({
683
+ prompt: 'Summarize these supplied notes: ...',
684
+ model: 'google/gemini-3.8-flash',
685
+ toolset: { type: 'none' },
686
+ output_schema: {
687
+ name: 'Summary',
688
+ schema: {
689
+ type: 'object',
690
+ properties: { summary: { type: 'string' } },
691
+ required: ['summary'],
692
+ },
693
+ },
694
+ });
695
+ const decision = await macro.ai.decide({
696
+ input: { subject: 'Invoice due tomorrow', body: 'Please pay by Friday.' },
697
+ questions: { needsAction: 'Does this ask the recipient to take action?' },
698
+ });
699
+ console.log(answer.outcome, decision.probabilities.needsAction);
700
+ ```
701
+
702
+ Decision probabilities estimate yes independently for each named question; they
703
+ do not authorize any action. Structured completions with tools enabled can modify
704
+ data, so inspect `outcome` and `toolActivity` even when generation is interrupted.
705
+
706
+ ### Workspace browsing
707
+
708
+ Use `macro.workspace.page(options)` for a bounded page or
709
+ `macro.workspace.list(options)` for lazy automatic pagination. Results include
710
+ existing entity handles plus generated API snapshots, so metadata does not
711
+ require a second request:
712
+
713
+ ```ts
714
+ const page = await macro.workspace.page({
715
+ includeTypes: ['document'],
716
+ sortBy: 'recently_updated',
717
+ limit: 5,
718
+ });
719
+ for (const item of page.items) {
720
+ if (item.type === 'document') console.log(item.id, item.name);
721
+ }
722
+ console.log({ hasMore: page.hasMore, nextCursor: page.nextCursor });
723
+ ```
724
+
725
+ The namespace supports documents (including tasks), AI chats, projects, email,
726
+ channels, channel threads, call records, calendar events and foreign entities.
727
+ Options preserve source scope through server-side type, time, property, task,
728
+ favorites, tag and inbox filters. Tags accept personal/team scopes and any/all
729
+ matching; ambiguous all-matches and unknown labels fail explicitly. Inbox names
730
+ resolve against all accessible inboxes, including delegated inboxes. `limit`
731
+ controls page size (default 50, maximum 500); break a `for await` loop to stop
732
+ without fetching another page. The TypeDoc namespace reference includes task,
733
+ date-window, signal-email and scoped-tag examples.
734
+
735
+ ### Saved code executions
736
+
737
+ An execution is a lazy entity handle scoped to its agent session. Construct it
738
+ with the execution ID from an `ExecuteCode` receipt, then read fields on the handle:
739
+
740
+ ```ts
741
+ const session = macro.agentSessions.byId(sessionId);
742
+ const execution = session.codeExecutions.byId(executionId);
743
+ const status = await execution.status();
744
+ const source = await execution.source();
745
+ const result = await execution.result();
746
+ const calls = await execution.calls();
747
+ await execution.refresh(); // Reload after a running execution changes.
748
+ ```
749
+
750
+ Constructing the handle makes no request. Field reads share a cached record;
751
+ `refresh()` reloads it. `execution.session()` returns the parent session handle.
752
+ Every read remains authorized and scoped by both session and execution identity.
753
+
754
+ ### Persistent code-execution reviews
755
+
756
+ A code execution can prepare a saved UI review and finish immediately. The review
757
+ is presented immediately through the ordinary ACP tool-call stream and remains
758
+ editable after the execution exits. `session.reviews.create(...)` uses the same
759
+ presentation without requiring a code execution. The session owner can
760
+ send one email, send all remaining emails, create a reviewed calendar event, or
761
+ answer a question. External actions only happen on submission.
762
+
763
+ ```js
764
+ const execution = macro.agentSessions.byId(sessionId)
765
+ .codeExecutions.byId(executionId);
766
+ const review = await execution.reviews.create({
767
+ kind: 'email',
768
+ title: 'Follow-up emails',
769
+ drafts: people.map((person) => ({
770
+ subject: 'Following up',
771
+ body: `Hello ${person.name},\n\nThanks for joining us.`,
772
+ to: [{ email: person.email, name: person.name }],
773
+ })),
774
+ });
775
+ return { data: { prepared: people.length }, reviews: [await review.reference()] };
776
+ ```
777
+
778
+ `execution.reviews.list()` returns fresh `SessionReview` handles.
779
+ `session.reviews.byId(id)` constructs a lazy handle; `review.items()` returns item
780
+ handles with `edit(draft)`, `submit()`, and `dismiss()` methods. `submitAll()` and
781
+ `dismissAll()` act on the pending items. Writes use the saved revision. After a
782
+ conflict, refresh and inspect the review; never automatically retry a send whose
783
+ outcome is unknown. These SDK methods have the same user authorization as the
784
+ ordinary API: review cards offer a user workflow, not a separate security grant.