@north-light/cli 0.3.472 → 0.3.474

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 (86) hide show
  1. package/dist/api/dto/nodes.d.ts +1 -1
  2. package/dist/builtin-memory/crouter-sdk/README.md +4 -47
  3. package/dist/builtin-memory/crouter-sdk/client.md +2 -231
  4. package/dist/builtin-memory/crouter-sdk/errors.md +9 -50
  5. package/dist/builtin-memory/crouter-sdk/getting-started.md +3 -65
  6. package/dist/builtin-memory/crouter-sdk/guides/README.md +1 -3
  7. package/dist/builtin-memory/crouter-sdk/guides/typed-extraction.md +1 -1
  8. package/dist/builtin-memory/crouter-sdk/nodes.md +1 -1
  9. package/dist/builtin-memory/crouter-sdk/release-notes.md +20 -20
  10. package/dist/builtin-memory/crouter-sdk/streaming.md +1 -70
  11. package/dist/builtin-memory/northlight-apps/INDEX.md +15 -0
  12. package/dist/builtin-memory/northlight-apps/cli.md +41 -0
  13. package/dist/builtin-memory/northlight-apps/coding-agents.md +75 -0
  14. package/dist/builtin-memory/northlight-apps/concepts/apps-and-sign-in.md +109 -0
  15. package/dist/builtin-memory/northlight-apps/concepts/connections.md +109 -0
  16. package/dist/builtin-memory/northlight-apps/concepts/providers.md +76 -0
  17. package/dist/builtin-memory/northlight-apps/concepts/runs.md +101 -0
  18. package/dist/builtin-memory/northlight-apps/concepts/scopes-and-grants.md +64 -0
  19. package/dist/builtin-memory/northlight-apps/concepts/testing-mode.md +54 -0
  20. package/dist/builtin-memory/northlight-apps/errors.md +119 -0
  21. package/dist/builtin-memory/northlight-apps/guides/background-runs.md +80 -0
  22. package/dist/builtin-memory/northlight-apps/guides/files-and-documents.md +61 -0
  23. package/dist/builtin-memory/northlight-apps/guides/go-live.md +39 -0
  24. package/dist/builtin-memory/northlight-apps/guides/grant-changes.md +100 -0
  25. package/dist/builtin-memory/northlight-apps/guides/manage-your-app.md +77 -0
  26. package/dist/builtin-memory/northlight-apps/guides/many-users.md +63 -0
  27. package/dist/builtin-memory/northlight-apps/guides/stream-a-run.md +84 -0
  28. package/dist/builtin-memory/{crouter-sdk/testing.md → northlight-apps/guides/test-your-app.md} +6 -6
  29. package/dist/builtin-memory/northlight-apps/guides/typed-results.md +99 -0
  30. package/dist/builtin-memory/northlight-apps/how-it-fits.md +49 -0
  31. package/dist/builtin-memory/northlight-apps/providers/README.md +39 -0
  32. package/dist/builtin-memory/northlight-apps/providers/context.md +34 -0
  33. package/dist/builtin-memory/northlight-apps/providers/device.md +28 -0
  34. package/dist/builtin-memory/northlight-apps/providers/integrations.md +28 -0
  35. package/dist/builtin-memory/northlight-apps/providers/search.md +31 -0
  36. package/dist/builtin-memory/northlight-apps/providers/sms.md +39 -0
  37. package/dist/builtin-memory/northlight-apps/quickstart.md +210 -0
  38. package/dist/commands/node/create.js +2 -2
  39. package/docs/apps/cli.md +40 -0
  40. package/docs/apps/coding-agents.md +72 -0
  41. package/docs/apps/concepts/apps-and-sign-in.md +82 -0
  42. package/docs/apps/concepts/connections.md +106 -0
  43. package/docs/apps/concepts/providers.md +59 -0
  44. package/docs/apps/concepts/runs.md +94 -0
  45. package/docs/apps/concepts/scopes-and-grants.md +62 -0
  46. package/docs/apps/concepts/testing-mode.md +36 -0
  47. package/docs/apps/errors.md +117 -0
  48. package/docs/apps/guides/background-runs.md +78 -0
  49. package/docs/apps/guides/files-and-documents.md +59 -0
  50. package/docs/apps/guides/go-live.md +37 -0
  51. package/docs/apps/guides/grant-changes.md +98 -0
  52. package/docs/apps/guides/manage-your-app.md +75 -0
  53. package/docs/apps/guides/many-users.md +61 -0
  54. package/docs/apps/guides/stream-a-run.md +82 -0
  55. package/docs/{sdk/testing.md → apps/guides/test-your-app.md} +5 -5
  56. package/docs/apps/guides/typed-results.md +72 -0
  57. package/docs/apps/how-it-fits.md +46 -0
  58. package/docs/apps/providers/README.md +26 -0
  59. package/docs/apps/providers/context.md +32 -0
  60. package/docs/apps/providers/device.md +26 -0
  61. package/docs/apps/providers/integrations.md +26 -0
  62. package/docs/apps/providers/search.md +29 -0
  63. package/docs/apps/providers/sms.md +37 -0
  64. package/docs/apps/quickstart.md +120 -2
  65. package/docs/cli/README.md +1 -0
  66. package/docs/cli/join-northlight.md +58 -0
  67. package/docs/sdk/README.md +4 -47
  68. package/docs/sdk/client.md +2 -231
  69. package/docs/sdk/errors.md +8 -49
  70. package/docs/sdk/getting-started.md +3 -65
  71. package/docs/sdk/guides/README.md +1 -3
  72. package/docs/sdk/guides/typed-extraction.md +1 -1
  73. package/docs/sdk/nodes.md +1 -1
  74. package/docs/sdk/release-notes.md +20 -20
  75. package/docs/sdk/streaming.md +1 -70
  76. package/package.json +2 -2
  77. package/packages/crouter-identity/package.json +1 -1
  78. package/runtime.lock.json +12 -12
  79. package/dist/builtin-memory/crouter-sdk/error-envelope.md +0 -38
  80. package/dist/builtin-memory/crouter-sdk/guides/apps-on-northlight.md +0 -423
  81. package/dist/builtin-memory/crouter-sdk/guides/apps-with-many-users.md +0 -61
  82. package/dist/builtin-memory/crouter-sdk/memory.md +0 -49
  83. package/docs/sdk/error-envelope.md +0 -36
  84. package/docs/sdk/guides/apps-on-northlight.md +0 -419
  85. package/docs/sdk/guides/apps-with-many-users.md +0 -59
  86. package/docs/sdk/memory.md +0 -47
@@ -0,0 +1,61 @@
1
+ ---
2
+ kind: knowledge
3
+ when-and-why-to-read: When you need Files and documents, this knowledge should
4
+ be read because Download a file from a person's runtime with files.download,
5
+ and read the person's public documents with memory.list and memory.get.
6
+ ---
7
+
8
+ # Files and documents
9
+
10
+ ## Download a file
11
+
12
+ `runtime.files.download(path, options?)` returns the file's raw bytes as a Fetch `Response` (200, or 206 for a `range`) with `Content-Type`, `Content-Length` and `Content-Range`, so you can pipe its body on. `path` is an absolute path on the person's runtime that your app's grant lets it read. Options: `range` (one `Range` header value such as `bytes=0-0` or `bytes=-500`) and `signal`.
13
+
14
+ ```ts
15
+ const response = await runtime.files.download('/apps/<your client id>/files/report.pdf');
16
+ res.setHeader('content-type', response.headers.get('content-type') ?? 'application/octet-stream');
17
+ await pipeline(Readable.fromWeb(response.body!), res);
18
+ ```
19
+
20
+ A non-2xx answer is thrown as an `APIError`, never returned as bytes. A bad `range` is `416`, `invalid_request` with `param: 'range'`. A body cut short mid-stream means the file could not be read to the end. What a path may reach depends on the grant: see [[northlight-apps/concepts/scopes-and-grants]]. The client your app gets from `oauth.client(userId)` exposes only `download` from `files`; reading, writing and listing are not available to apps.
21
+
22
+ ## Read the person's public documents
23
+
24
+ `runtime.memory` is a read-only view of the `knowledge` and `preference` documents the person owns (`memory` and the `/v1/memory` routes are the API's names for this). An app reads the person's `public` documents with `memory.list` and `memory.get`, and needs no scope to do it. It never sees a `friends` or `private` document and cannot tell one from a document that does not exist: both answer `404 not_found`. The list is what the app's agents can read about the person, so an app can show the person exactly which of their documents it draws on.
25
+
26
+ ```ts
27
+ const page = await runtime.memory.list({store: 'user'});
28
+ for (const item of page.items) console.log(item.name, item.preview);
29
+
30
+ const doc = await runtime.memory.get({store: 'user', name: page.items[0].name});
31
+ console.log(doc.body);
32
+ ```
33
+
34
+ `store` is `'user'` in this release; any other value answers `400 invalid_request` with `param: "store"`. An app whose grant holds `crtr:memory:manage:user` (a first-party app) sees every privacy level. Reading records nothing: no watch, no `read` event, no audit row. Both methods are `GET` requests and follow the SDK's retry rule for safe requests.
35
+
36
+ ### List
37
+
38
+ `list({store, path?, kind?, limit?, cursor?}, options?)` sends `GET /v1/memory` and returns `{items, next_cursor}`.
39
+
40
+ | Field | Meaning |
41
+ |---|---|
42
+ | `path` | A folder: lists documents whose name starts with `<path>/`, at any depth |
43
+ | `kind` | `knowledge` or `preference`; both when omitted |
44
+ | `limit` | 1 to 100; default 50 |
45
+ | `cursor` | The previous page's `next_cursor`, with the same `store`, `path` and `kind` |
46
+
47
+ Items are ordered by `name`. Each item is `{name, folder, kind, preview, summary, privacy, revision, created_at, updated_at}`: `name` has no `user/` prefix, `folder` is the name up to its last `/` (`""` at the top level), and `updated_at` is the current revision's time. Folders are not items, and deleted and unlisted documents are left out. `next_cursor` is `null` on the last page.
48
+
49
+ `listAll(params, options?)` takes the same fields without `cursor` and yields every item across pages, fetching the next page only as you iterate:
50
+
51
+ ```ts
52
+ for await (const item of runtime.memory.listAll({store: 'user', path: 'work'})) render(item);
53
+ ```
54
+
55
+ ### Get
56
+
57
+ `get({store, name}, options?)` sends `GET /v1/memory/document` and returns a list item's fields plus `body`, `size`, `truncated` and `grantee`.
58
+
59
+ - `body` is the current markdown as stored; `[[links]]` are not resolved. A body over 1 MiB is cut to its longest whole-character prefix of at most 1 MiB, with `truncated: true`; `size` is always the full length in UTF-8 bytes.
60
+ - `grantee` is `app:<id>` of the app whose agent wrote the first revision, or `null` when the person wrote it.
61
+ - An absent, deleted, `friends` or `private` name rejects with `NotFoundError` (`code: 'not_found'`); a malformed field rejects with `BadRequestError`.
@@ -0,0 +1,39 @@
1
+ ---
2
+ kind: knowledge
3
+ when-and-why-to-read: When you need Go live, this knowledge should be read
4
+ because Move an app from your laptop to a server you choose, and ask
5
+ Northlight to verify it so anyone can sign in.
6
+ ---
7
+
8
+ # Go live
9
+
10
+ Northlight does not host your app's server. Deploy it wherever you like. What changes between your laptop and production is a short list.
11
+
12
+ ## Production checklist
13
+
14
+ - **A persistent connection store.** `MemoryConnectionStore` loses every sign-in on restart and works for one process only. Use a store that survives restarts and locks across processes, such as `PostgresConnectionStore` from `@north-light/sdk/stores/postgres`, and pass it as `store`. Two processes that refresh the same connection with different stores race, and the directory refuses the loser with `refresh_token_reused`. The store holds credentials: restrict database access and encrypt backups.
15
+ - **The key file in a secret manager.** The private key is the app's identity. Keep it out of git and out of images. Mount it where your host keeps secrets, and point `CROUTER_KEY_FILE` at that path (a container might read `/run/secrets/app_key`). The SDK reads no environment: your code loads the values and passes them to `OAuth2Client`.
16
+ - **A production redirect URI and origin.** In the console, add `https://<your domain>/auth/callback` under **Sign-in → Redirect URIs** and set the **Origin URL** on the Profile tab to your domain. Set `APP_ORIGIN` to it on the server. Keep `http://localhost:3000/auth/callback` if you still develop locally.
17
+ - **An exact SDK pin.** `npm i --save-exact @north-light/sdk@<version>`. A compatibility gate protects the wire between the SDK and Northlight's runtimes, not the TypeScript API, so a range or `latest` can pick up a type change on its next install. If a call fails with `426 runtime_version_unsupported`, the SDK is newer than the runtimes: install the previous version or wait. To move on purpose, run `npm view @north-light/sdk dist-tags` and read the [release notes](https://sdk.docs.northlight.ai/docs/release-notes) for the versions in between.
18
+ - **One place for dead connections.** Pass `onRefusal` to `OAuth2Client`, and schedule `oauth.refreshIdleConnections` so offline people stay connected. See [[northlight-apps/guides/many-users]].
19
+ - **Redact sign-in secrets from logs.** An authorization code and a refresh token in a log line is a credential. Keep them out of HTTP logs.
20
+ - **Listing, if you want it.** In **Profile → Marketplace**, set a sign-in start URL and a text welcome, and turn on **Listed in the marketplace**. A testing app stays out of the marketplace.
21
+
22
+ Four variables configure an app built on the SDK:
23
+
24
+ | Variable | Value |
25
+ |---|---|
26
+ | `CROUTER_ISSUER` | `https://account.northlight.ai` |
27
+ | `CROUTER_CLIENT_ID` | The client ID the console shows |
28
+ | `APP_ORIGIN` | Your app's origin. Its redirect URI is `${APP_ORIGIN}/auth/callback` by convention |
29
+ | `CROUTER_KEY_FILE` | Path to the private JWK; `local/app-key.json` by default |
30
+
31
+ ## Let people other than your testers sign in
32
+
33
+ A new app is in testing: only you and up to 100 testers can sign in. To open it to everyone, ask Northlight to verify it by email to support@northlight.ai. Include your app's name and client ID, where it runs, and what it asks for and why. Until then, anyone else is refused with `app_in_testing`. See [[northlight-apps/concepts/testing-mode]].
34
+
35
+ This site does not state how long verification takes or what Northlight checks beyond that email address (not yet checked on production).
36
+
37
+ ## Rotate the key later
38
+
39
+ Add a second key, deploy with it, verify a real sign-in, then retire the old one. Rotation has no downtime. The steps are in [[northlight-apps/guides/manage-your-app]].
@@ -0,0 +1,100 @@
1
+ ---
2
+ kind: knowledge
3
+ when-and-why-to-read: When you need Grant changes, this knowledge should be read
4
+ because Follow a person's grant, wait for a required provider, show their
5
+ month's cost, and link to the app's settings.
6
+ ---
7
+
8
+ # Grant changes
9
+
10
+ What an app reads from `grant.get()` changes while nobody is holding a request: a required provider's setup turns `ready`, the person changes the app's scopes or spend cap, or the grant is revoked.
11
+
12
+ ## Follow grants with `watchGrants`
13
+
14
+ `oauth.watchGrants(...)` returns a `GrantWatcher` that follows the grants of the people you name and hands each change to `onChanged`:
15
+
16
+ ```ts
17
+ const watcher = oauth.watchGrants({
18
+ // Only people whose change the app will act on: here, owners still waiting on Context.
19
+ users: () => db.owners.findMany({where: {connected: true, drafted: false}}).then((rows) => rows.map((row) => row.userId)),
20
+ onChanged: async ({userId, grant}) => {
21
+ // Level-triggered: decide from the grant as it is now, never from "did it just change".
22
+ if (grant.dependencies['context']?.state !== 'ready') return;
23
+ // Idempotent: only a row still waiting moves, so a redelivery or a second instance starts nothing.
24
+ const claimed = await db.owners.updateMany({where: {userId, drafted: false}, data: {drafted: true}});
25
+ if (claimed.count === 1) await startDraft(userId);
26
+ },
27
+ onError: (error, userId) => log.warn({error, userId}, 'grant watcher'),
28
+ });
29
+ await watcher.start();
30
+ // After the app starts waiting on someone:
31
+ watcher.nudge();
32
+ // On shutdown:
33
+ await watcher.stop();
34
+ ```
35
+
36
+ - **`users()`** returns the Northlight user ids whose grant you follow, read from your own rows. It is called at `start()`, every `sweepMs` (default 30 000), after each delivery and on `nudge()`. A user it no longer returns is forgotten. Each followed person holds one request on their runtime per turn, so return only people whose change you will act on.
37
+ - **Each turn** is one `grant.get` on `oauth.client(userId)`. A user whose last reading was delivered reads `grant.get({wait, since: version})` (`wait` integer 1–25, default 25): the runtime holds the read until the grant's `version` changes or `wait` seconds pass. With more users than `concurrency` (default 50), every user still gets a turn in round-robin order.
38
+ - **`onChanged({userId, grant, previous})`** is level-triggered. The first event for a user in a process carries the current grant and `previous: null`, so a restart delivers current state again. Delivery is at least once per `(userId, version)`; make the handler idempotent.
39
+ - **If `onChanged` throws**, the same version is delivered again after 5 s, doubling to 5 min. A transient runtime error backs off the same way. A missing or refused connection drops that user and reports to `onError`; the next sweep decides again from `users()`.
40
+ - For one person without the watcher, `runtime.grant.get({wait: 25, since: grant.version})` holds a single read the same way. `wait` outside 1–25 throws `RangeError` before sending.
41
+
42
+ ## Wait on a provider your app requires
43
+
44
+ An app whose registration `requires` a provider (the console's **What your app requires**) needs that provider set up for the person before the operations that depend on it work. The runtime does not check this for you. `grant.get()` returns `dependencies`: one entry per required provider, keyed by provider id, or `{}` when the app requires none. Read it on each request that needs the provider; do not store it.
45
+
46
+ ```ts
47
+ import type {ProviderDependency} from '@north-light/sdk';
48
+
49
+ // ProviderDependency is { state: 'not_started' | 'pending' | 'ready' | 'failed'; message?: string; next: string }.
50
+ const {dependencies} = await runtime.grant.get();
51
+ const context: ProviderDependency | undefined = dependencies['context'];
52
+ if (context?.state !== 'ready') {
53
+ // Show the provider's own sentence and link its setup page; never hard-code either.
54
+ const setup = context && new URL(context.next);
55
+ setup?.searchParams.set('return_to', 'https://app.example.com'); // your registered redirect origin
56
+ throw new AppError('provider_setup_pending', context?.message ?? 'Finish setting up Context, then try again.', {
57
+ status: 403,
58
+ retryable: false,
59
+ details: {provider: 'context', state: context?.state ?? 'not_started', message: context?.message, next: setup?.href},
60
+ });
61
+ }
62
+ ```
63
+
64
+ `AppError` stands for your app's own typed error ([[northlight-apps/errors]]).
65
+
66
+ - `state` is `not_started` (the person has not done their part), `pending` (the provider is working), `ready` or `failed`.
67
+ - `message` is the provider's own sentence for `pending` and `failed`. It is absent for `not_started` and `ready`, so keep a short fallback.
68
+ - `next` is the absolute URL of the directory's setup page for this provider and your app. Append `return_to` (your app's registered redirect origin) so the person comes back to you.
69
+ - An entry is missing when the runtime has not synced the grant since the app began requiring the provider. Treat it as `not_started`.
70
+
71
+ Refuse the dependent operation with `provider_setup_pending` (403), carrying `state`, `message` and `next` in `details`. To act when the state turns `ready`, use `watchGrants` above instead of polling.
72
+
73
+ ## Show what a person's month has cost
74
+
75
+ A person's grant caps what your app may spend of their AI subscription each UTC month (`grant.spend_cap`). `usage.get()` answers where the month stands:
76
+
77
+ ```ts
78
+ const usage = await runtime.usage.get(); // or {month: '2026-09'}
79
+ // {grantee, month, usd_equivalent, by_model, app_paid, spend_cap, reset_at}
80
+ ```
81
+
82
+ - **`usd_equivalent`** is user-paid spend at list price: model completions and provider receipts. Receipts have no `by_model` row, so it can exceed the sum of `by_model`. A model with no list price reports `usd_equivalent: null` on its row.
83
+ - **`app_paid`** is usage your app pays for. It never counts toward `spend_cap`.
84
+ - **At the cap.** Once `usd_equivalent` reaches `spend_cap`, user-paid model and provider calls answer 402 `cap_exhausted` (`retryable: false`, `userAction: 'raise_cap'`, with `resetAt`) until `reset_at`, the first instant of the next UTC month. A run whose model call is refused ends with outcome reason `cap_exhausted`. The check runs before each call, so the call that crosses the cap completes and the next one is refused. Do not retry; tell the person when the count resets.
85
+ - `spend_cap: null` means the grant is not capped.
86
+
87
+ You set the default cap for your app in the console's **What it asks for** tab (**Monthly spend cap**); the person can change it for themselves.
88
+
89
+ ## Link to the app's settings on Northlight
90
+
91
+ Each person who uses your app has a page on their Northlight account where they change or remove what the app may do. Link to it with the URL the directory advertises. Do not compose the path yourself:
92
+
93
+ ```ts
94
+ const href = await oauth.accountAppUrl(); // e.g. https://<directory>/account/apps/<your client id>
95
+ ```
96
+
97
+ - It is the same URL for every person: the directory shows whoever is signed in their own page for your app, and sends someone without a directory session through sign-in first. Someone without an active grant sees that the app is not connected to their account.
98
+ - It needs no user and no connection, so it serves owners and visitors alike. Its only request is the discovery read that `authorizeUrl`, `verifyIdToken` and `revoke` share.
99
+ - A failure is a `CrouterError` (code `crouter_error`) whose message names the fault, such as a discovery document that advertises no `account_app_uri_template`. A slow discovery read throws `DeadlineExceededError` after `timeoutMs` (default 10 s). A failed read is not kept; a successful one is kept for the client's life.
100
+ - Warm it at startup with `void oauth.accountAppUrl().catch(log)`. A page that must not wait on the directory races it against a short timer and hides the link if the race is lost.
@@ -0,0 +1,77 @@
1
+ ---
2
+ kind: knowledge
3
+ when-and-why-to-read: When you need Manage your app, this knowledge should be
4
+ read because What each tab of the Northlight console does for an app you have
5
+ registered, and the two things the console cannot do yet.
6
+ ---
7
+
8
+ # Manage your app
9
+
10
+ You manage an app in the console at `https://account.northlight.ai/console`. Choose your app in the list to open its page. The tabs are Sign-in, What it asks for, Profile, Sharing, Testers and Provider. (Only the first-party apps use Provider.)
11
+
12
+ Your **client ID** is shown on the app's page. Copy it into `CROUTER_CLIENT_ID`, or write it to `local/app.env` with `npx @north-light/sdk env --client-id <client id>`.
13
+
14
+ ## Sign-in
15
+
16
+ - **Redirect URIs.** Sign-in returns only to a URI listed here, matched exactly: `localhost` and `127.0.0.1` are different URIs, and the port counts. Each sign-in names the URI to return to, so an app can hold several (for example your deployed callback and a localhost one). **Save redirect URIs** replaces the whole list, so keep the ones you still use.
17
+ - **Keys.** An app proves who it is with a signing key. There is no client secret. **Add a key** takes a public JWK; the form refuses a pasted private key. You can instead **Use a JWKS URL**: the directory reads the keys from that URL. An app holds at most 2 active keys. **Retire** stops a key signing in; a retired key can be **Deleted** so it can be added again.
18
+
19
+ ### Rotate a key
20
+
21
+ Rotating has no downtime, because the directory accepts a sign-in signed by either active key.
22
+
23
+ 1. Generate the new key beside the current one: `npx @north-light/sdk keygen --out local/app-key.next.json`. It prints the public JWK.
24
+ 2. In **Sign-in → Keys**, choose **Add a key** and paste the JWK. Both keys are now active.
25
+ 3. Point `CROUTER_KEY_FILE` (or your `privateKey`) at `local/app-key.next.json` and deploy.
26
+ 4. Complete one real sign-in through the callback, or refresh a stored connection. Opening your login route only redirects to the directory and never reaches the token endpoint, so it proves nothing about the key.
27
+ 5. **Retire** the old key, then delete the old key file.
28
+
29
+ Until you retire the old key it is your rollback. After you retire it, a sign-in signed with it fails with `unauthorized`, and the message names the key as retired. An app registered with a JWKS URL rotates the same way through the URL: publish the new key beside the old one, switch, verify, then remove the old one. The directory re-reads the URL within about a minute.
30
+
31
+ ## What it asks for
32
+
33
+ - **What your app asks for.** The scopes people are asked to approve. **Add permissions** searches the catalog; take scope strings from it and from `providers.tools`, and do not invent them. `crtr:act` needs `crtr:llm`. See [[northlight-apps/concepts/scopes-and-grants]].
34
+ - **What your app requires.** Providers the app cannot work without. A person is taken through that provider's setup the first time they sign in. See [[northlight-apps/guides/grant-changes]].
35
+ - **Monthly spend cap.** The most your app may spend of each person's AI subscription per month, in whole US dollars.
36
+
37
+ ## Profile
38
+
39
+ - **How people see your app**: Name, Origin URL, Logo URL, and **Why your app needs access** (quoted on the consent page as your words). **Save details**.
40
+ - **Marketplace**: **Listed in the marketplace**, Price, **Sign-in start URL** and **Text welcome**. Agents can install a listed app for a person by text. A testing app stays out of the marketplace even when listed. The sign-in start URL is where Install sends people; your `/auth/login` route is a valid one, and a `localhost` URL is accepted. The text welcome is one or two plain sentences, at most 120 characters, with no links.
41
+
42
+ ## Testers
43
+
44
+ A new app is in testing: only you and up to 100 testers can sign in. Add a tester by the email or phone number on their Northlight account. An email matches only while it is verified on that account. Nobody gets a message, so tell them. Removing a tester revokes their grant for the app. See [[northlight-apps/concepts/testing-mode]].
45
+
46
+ ## Sharing
47
+
48
+ **What other apps may use** lists parts of your app's space (memory, files, conversations) that other apps may ask for, and at what access (read or read/write). Add a folder to share a part of your app's files.
49
+
50
+ ## Develop beside a live app
51
+
52
+ Once your app is live you can keep developing on your laptop against production while the live app keeps running. There are two ways.
53
+
54
+ **Add your localhost callback to the live app.** This is simplest and fine for most apps. In **Sign-in → Redirect URIs**, list both `https://app.example.com/auth/callback` and `http://localhost:3000/auth/callback`. Give your laptop its own signing key beside the deployed one (an app holds at most 2 active keys), so you never copy the production private key to your laptop. Both servers share the same people, grants, space and scopes. A scope you add while developing changes what the live app asks of everyone. The origin, sign-in start URL and run notice URL each hold one value, so they keep pointing at the deployed app.
55
+
56
+ **Register a separate development app.** Do this when you are changing what the app asks for, or need grants and data that live people never touch. Register another app in the console, for example "Texty (dev)", with a `localhost` origin and redirect URI and its own key. It starts in testing and stays there, so only you and your testers can sign in, and it never appears in the marketplace. Point your laptop's environment file at its client ID.
57
+
58
+ ## Two things the console can't do yet
59
+
60
+ Deleting an app and setting its run notice URL are not in the console today. Both need `crtr`, the Northlight command line, on a machine joined to your Northlight account. Joining is a one-time setup described in [the crouter docs](https://crouter.docs.northlight.ai/docs/cli/join-northlight): install `@north-light/cli`, then run `crtr sys join` with a token from `https://account.northlight.ai/account/machines`. Joining rewrites the local crtr home and has no unjoin, so join from a home you can throw away. These steps are the only part of building an app that needs crtr.
61
+
62
+ ### Delete an app
63
+
64
+ ```bash
65
+ crtr cloud apps delete --app-id <client id> --confirm <client id>
66
+ ```
67
+
68
+ It answers `deleted: true` and `removed_grants`, the number of people's grants it removed. Each person's runtime deletes the app's runs, space and schedules, and the app's next refresh fails with `invalid_grant`. The app's key stops working, its page answers 404 and it disappears from your list. This cannot be undone. You must run it yourself in the terminal of the joined machine: an agent, including your chat agent, is refused with `provider_refused`. If you only want a clean slate for tests, changing the app's redirect URIs and keys is often simpler.
69
+
70
+ ### Set the run notice URL
71
+
72
+ ```bash
73
+ crtr cloud apps set-run-notice-url --app-id <client id> --url https://app.example.com/run-notices
74
+ crtr cloud apps set-run-notice-url --app-id <client id> --clear
75
+ ```
76
+
77
+ The URL must be https (plain http only on localhost in development) and at most 512 characters. What the app does with notices is in [[northlight-apps/guides/background-runs]].
@@ -0,0 +1,63 @@
1
+ ---
2
+ kind: knowledge
3
+ when-and-why-to-read: When you need Many users, this knowledge should be read
4
+ because Keep each person's runtime connection separate when people interact in
5
+ your app, and understand whose action a call records.
6
+ ---
7
+
8
+ # Many users
9
+
10
+ An app can bring people together without putting all of their agents or data on one runtime. **Each person's runtime holds that person's agents, memory, files, conversations, AI subscription, phone and device.** Your server holds its user table keyed by the Northlight `sub`, one stored `Connection` per person in a `ConnectionStore` (runtime URL, rotating refresh token, grant id), in-app roles and settings, and data shared between users. Northlight permissions decide what your app can do on each person's runtime. Your app decides what its users can do to each other.
11
+
12
+ Keep the connection and refresh token on the server, never in a visitor's browser. The server can call `providers.call` on a stored connection outside any run, even when the person is offline. Access tokens last 10 minutes; refresh tokens rotate on each use and expire after 90 days unused.
13
+
14
+ - Give `OAuth2Client` a persistent `ConnectionStore` with a cross-process lock as `store`, and reach each person's runtime with `await oauth.client(userId)`.
15
+ - Schedule `oauth.refreshIdleConnections({olderThanMs: 30 * 24 * 60 * 60 * 1000})` on a timer. It refreshes connections last saved before the cutoff, through the store's lock, and returns `{refreshed, refused, failures}`. The SDK starts no timer itself.
16
+ - Act on a dead connection in one place, `onRefusal`. Delete a person's data only on `grant_removed` (`kind: 'removed'`).
17
+ - Learn when a background run ends with `oauth.watchRuns(...)`: see [[northlight-apps/guides/background-runs]].
18
+
19
+ ## Signing in a visitor
20
+
21
+ A visitor who only needs to be recognized, not connected, signs in with identity only. Request `openid`, adding `email` for their email and `profile` for their name and photo, and no runtime scope. The directory shows one line ("Know who you are on Northlight"), writes no grant, and answers with an ID token and an access token usable only at `/userinfo`: no refresh token, grant or runtime URL. Finish that sign-in with `exchangeIdentity`, not `exchangeCode`:
22
+
23
+ ```ts
24
+ const {url, codeVerifier, state, nonce} = await oauth.authorizeUrl({scopes: ['openid', 'email', 'profile'], state: sessionState});
25
+ // Save codeVerifier, state and nonce in the visitor's session; redirect them to url.
26
+ // On the callback, read them back from the session and finish the sign-in:
27
+ const visitor = await oauth.exchangeIdentity({code: callbackCode, codeVerifier, state: callbackState, expectedState: state, nonce});
28
+ visitor.sub; // 'user:…', the same id a Connection.userId carries for this person
29
+ visitor.email; // present only when 'email' was requested and approved
30
+ visitor.emailVerified; // the directory's email_verified, when email was approved
31
+ visitor.name; // present only when 'profile' was approved and the person has a name (never a phone number)
32
+ visitor.picture; // an https URL, present only when 'profile' was approved and the account has a photo
33
+ ```
34
+
35
+ `exchangeIdentity` returns an `Identity`: `sub`, `email` and `emailVerified` when granted, `name`, `givenName` and `familyName` when `profile` was granted and the person has one, `picture` when `profile` was granted and the account has a photo (only an `https:` URL), and every verified claim in `claims`.
36
+
37
+ The SDK checks the ID token's ES256 signature against the directory's JWKS, its issuer, that `aud` is your client id, that it has not expired, and that its `nonce` equals the one `authorizeUrl` returned. `nonce` is required. Any failure throws `CrouterError` code `id_token_invalid`. If the directory's JWKS can't be fetched or is malformed, that error is thrown as is.
38
+
39
+ An `Identity` is not a connection. Nothing is stored in a `ConnectionStore` and nothing refreshes; your app keeps its own session for the visitor, and the visitor's runtime can't be called on their behalf. To act for the visitor later, send them through `authorizeUrl` again with the runtime scopes you need and finish with `exchangeCode`, which returns a `Connection`. Each call refuses the other's answer with code `oauth_exchange_mismatch`. If `exchangeIdentity` refuses an answer that carries a connection, the directory has already recorded that grant; it shows in the person's approved apps until they or your app revoke it.
40
+
41
+ ## Whose action a call records
42
+
43
+ When visitor A causes your server to call person B's runtime using **B's connection**, the runtime records the app as `grantee` and B as `sub`. It does not know or record that A caused the call. Even a request outside a run, with nobody present, has this attribution. Keep your own record of the app user and action when you need it. Do not send an app-user identity as a runtime principal.
44
+
45
+ A visitor chatting with B's clone starts an app run on **B's runtime and B's AI subscription**, using the app's grant from B. Your app rate-limits visitors; B's per-app spend cap is the platform backstop. Northlight's developer terms allow spending B's connection because of another user's action **only for what B turned on in your app, limited per person**. B can control the app's spend cap or remove the app.
46
+
47
+ ## The app's agent and documents
48
+
49
+ A run your app starts is **your app's agent**, not a continuation of another app's agent. It starts in `/apps/<app>/files`, uses the person's AI under `crtr:llm`, and reaches your app's own documents (owned by `app:<your app>`) without a `crtr:memory` scope. Other people's or apps' data is not shared merely because the app has many users. The grant's resolved permissions govern access to the person's files (`crtr:files:<access>:user:<dir>`), the person's documents (`crtr:memory:<access>:user`), another app's space (only where that app allows it), and another app's conversations (`crtr:conversations:read:app:<B>`).
50
+
51
+ The exception is the person's **public** documents (owned by the person, read through `memory`; see [[northlight-apps/guides/files-and-documents]]): an app with an active grant can read these even without a user-memory scope. A third-party app cannot see `friends` or `private` documents, even with `crtr:memory:read:user`. They look absent from lists, searches, reads and history. Only a holder of `crtr:memory:manage:user` (a first-party app), or the person, reads all three levels. A document without a privacy field reads as `private`. Public read access is not write access.
52
+
53
+ Every run is sandboxed: its shell runs as the app's OS user and sees only the app's space and the folders its permissions name. Normal runs have network access. Start a run with `isolated: true` when the agent should have **no network** and **no `/apps/<app>/files` mount**: its cwd is its own node folder, and all children inherit the restriction. The shell, stored conversation and model calls still work, and the run's `scopes` can narrow its commands. An isolated run cannot turn isolation off in a child or schedule, or use an outside cwd or worktree.
54
+
55
+ **An isolated run can't see, or be seen by, the app's other runs.** Starting one isolated run per visitor conversation keeps visitors apart. Another run's nodes, documents, conversation, trace, events and node folder answer `not_found` to it, and messaging, interrupting, cancelling or deleting another run does too. Each node of an isolated run gets its own home folder, `/apps/<app>/nodes/<node-id>/home`, in place of the shared `/apps/<app>/home`. An isolated run still reads your app's memory and the person's public memory. Your app's server is not confined: `runs.list` and `runs.trace` cover every run, so your server can show the person each visitor's conversation. When a call is refused by scope, a missing-scope error (`scope_missing` or `forbidden`) comes before any `not_found`, so the refusal reveals nothing about the target.
56
+
57
+ ## Messages to a running run
58
+
59
+ `runs.message(runId, message, {start_turn: false})` stores an app-attributed message on an existing run **without starting, reviving or reopening a turn**. The message is delivered at the start of the next turn, before that turn's input, and the trace marks it `custom` / `app_message`. The default `start_turn: true` sends an ordinary follow-up.
60
+
61
+ `runs.message` is safe to retry. The SDK sends an `Idempotency-Key` (one per call, reused across its own retries; pass `idempotencyKey` to choose it) and the runtime delivers a given key once for 24 hours. A replay returns the original result; the same key with different text, `start_turn` or run is refused with `409 idempotency_conflict`. An app that queues sends and may crash between the call and recording success should derive `idempotencyKey` from its own message id.
62
+
63
+ **A run's first prompt is always its first turn's input.** With the default `start_turn: true`, a message sent before the first turn has started queues behind it: the agent answers the `runs.start` prompt in turn one and your message in turn two. To answer a first message in the first turn, pass it with the prompt: `runs.start({prompt, message})` stores `message` with the run, so it joins the first turn as context delivered ahead of the prompt, and one reply covers both. Follow the reply with `runs.reply(runId, sent)`: see [[northlight-apps/guides/stream-a-run]].
@@ -0,0 +1,84 @@
1
+ ---
2
+ kind: knowledge
3
+ when-and-why-to-read: When you need Stream a run, this knowledge should be read
4
+ because Forward a run's events to a browser, follow the reply to one message,
5
+ and resume after a reload.
6
+ ---
7
+
8
+ # Stream a run
9
+
10
+ ## Forward a run to a browser
11
+
12
+ Your server keeps the runtime token and connection. The browser connects only to your server. Call `forwardRunEvents(runtime, runId, {after: cursorFromRequest(request), signal: request.signal})` and return the Fetch `Response`. After a host cuts the browser connection, `EventSource` sends its last SSE id as `Last-Event-ID`; `cursorFromRequest` prefers it over the URL's `after` query parameter.
13
+
14
+ Every forwarded run event is an unnamed SSE record with its `sequence_number` as `id` and the complete event object as `data`. One handler receives all of them:
15
+
16
+ ```ts
17
+ const source = new EventSource(`/api/runs/${runId}/events?after=${cursor}`);
18
+ source.onmessage = ({data}) => {
19
+ const event = JSON.parse(data);
20
+ if (event.type === 'stream.refused') { showRefusal(event.error); source.close(); return; }
21
+ if (event.type === 'stream.reconnecting') { showConnectionFailure(event.error); return; }
22
+ if (event.type === 'stream.reconnected') { clearConnectionFailure(); return; }
23
+ if (event.type === 'stream.idle') { source.close(); markIdle(event.cursor); return; } // reopen on your own trigger
24
+ showRunEvent(event);
25
+ };
26
+ ```
27
+
28
+ The four `stream.*` records are notices from the forwarder, not run events. They have no `sequence_number` or SSE id.
29
+
30
+ - **`stream.idle`** (`{type: 'stream.idle', cursor}`) means the runtime closed the stream after 60 s with no running turn and no new event. The helper writes it and ends the response. Close the `EventSource` on it and reopen with `after=cursor` on your own trigger: the person sends a message, or your server handles a run notice ([[northlight-apps/guides/background-runs]]). Without that, the browser would reconnect at once and keep a hosted runtime awake.
31
+ - **`stream.refused`** carries the full error envelope, including `stream_gap`'s `details.latest_sequence` and `details.earliest_sequence`. The helper ends the response after a refusal. The SDK does not recover a gap by skipping events.
32
+
33
+ ## Resume after a reload or a gap
34
+
35
+ When the page reloads mid-reply, or you get `stream_gap`, read `runs.trace(runId)` through your server and show each node's `in_progress_message` (`{thinking, text}` or `null`) as that node's open message. Then resume `runs.events(runId, {after: trace.latest_sequence})`, or forward with that cursor. Do not use a cursor from a separate `runs.get`.
36
+
37
+ Keep appending new deltas to the open message, but replace its thinking or text with the complete content repeated by `node.thinking.done` or `node.output_text.done`. That shows the message from its beginning without duplicating content. `runs.get` and every `runs.list` entry carry `latest_sequence` and `last_activity_at`; a cursor equal to `latest_sequence` is not a gap even when older events have expired.
38
+
39
+ ## Follow the reply to one message
40
+
41
+ A chat app sends a message and shows the answer to it. `runs.reply(runId, sent, {signal?})` takes what `runs.message` returned and follows only the turn that delivers that message:
42
+
43
+ ```ts
44
+ const sent = await runtime.runs.message(runId, 'What did the report say?');
45
+ for await (const event of runtime.runs.reply(runId, sent)) {
46
+ if (event.type === 'text.delta') append(event.delta);
47
+ if (event.type === 'turn.completed' && event.error) showError(event.error); // {code: 'content_refused' | 'model_error', message}
48
+ }
49
+ // or collect it: text as it streams, then the whole text and how the turn ended
50
+ const {text, ended, error, outcome} = await runtime.runs.reply(runId, sent).collect({onDelta: (delta) => append(delta)});
51
+ // ended: 'completed' | 'error' (error set) | 'waiting_on_user' | 'settled' (outcome set)
52
+ ```
53
+
54
+ | Event | Fields | From |
55
+ |---|---|---|
56
+ | `text.delta` | `delta` | `node.output_text.delta` |
57
+ | `message.done` | `text`, `stop_reason` | `node.output_text.done`, once per assistant message |
58
+ | `turn.completed` | `run_status`, `stop_reason`, `error?`, `message_ids` | `node.turn.completed`; always last |
59
+ | `run.settled` | `outcome` | `node.settled`, when the run settles before the turn completes; always last |
60
+
61
+ Every event also carries its `sequence_number`. The reply ends after `turn.completed` or `run.settled` and closes its stream. `.text()` resolves to the text of the `message.done` events joined with a blank line. A reply can be consumed once.
62
+
63
+ To get a reply to the run's first message, pass it as `runs.start({prompt, message})` and follow `runs.reply(run.run_id, run.message!)`. A message stored with the run always joins the first turn.
64
+
65
+ A refused or failed model call ends the turn with an empty `message.done` (`stop_reason: 'error'`) and `turn.completed.error`; the run stays usable. An interrupt, `runs.cancel` or a closed node ends the turn with `stop_reason: 'aborted'` and no error. An expired cursor throws `APIError` with code `stream_gap`; aborting `signal` rejects with `APIUserAbortError`.
66
+
67
+ ## A quiet run
68
+
69
+ A runtime that sleeps when nothing holds a connection to it ends a run's stream after 60 s with no running turn and no new event. `RunStream` reports that and does not reconnect:
70
+
71
+ ```ts
72
+ const stream = runtime.runs.events(runId, {after: cursor});
73
+ for await (const event of stream) handle(event);
74
+ const end = await stream.whenEnded(); // rejects on a transport failure or abort()
75
+ if (end.reason === 'idle') {
76
+ // the run is quiet and nothing was missed; reopen later with runtime.runs.events(runId, {after: end.cursor})
77
+ }
78
+ ```
79
+
80
+ A settled run ends with `reason: 'settled'`. `runs.reply` reopens through an idle close on its own.
81
+
82
+ ## Typed events
83
+
84
+ `RunEvent` is the union of every run event, discriminated on `type`. `RunEventOf<'node.turn.completed'>` picks one, and `RunStream.on(type, listener)` passes the listener that event. An event type a newer runtime adds and your SDK version does not declare is still delivered as-is.
@@ -1,11 +1,11 @@
1
1
  ---
2
2
  kind: knowledge
3
- when-and-why-to-read: When you need Testing your app, this knowledge should be
4
- read because FakeCloud from @north-light/sdk/testing — a fake directory and
5
- runtime your real OAuth2Client and Crouter talk to through fetch.
3
+ when-and-why-to-read: When you need Test your app, this knowledge should be read
4
+ because FakeCloud from @north-light/sdk/testing, a fake directory and runtime
5
+ your real OAuth2Client talks to through fetch.
6
6
  ---
7
7
 
8
- # Testing your app
8
+ # Test your app
9
9
 
10
10
  `@north-light/sdk/testing` exports `FakeCloud`, a fake Northlight: the directory (discovery, token refresh, JWKS) and each person's runtime (grant, runs, memory, providers, run notices). It answers through `fetch`. Your app's production path — `new OAuth2Client(...)`, `oauth.client(userId)`, `runs`, `memory`, `grant`, `providers`, `watchRuns`, `watchGrants`, `onRefusal`, `forwardRunEvents`, `verifyRunNotice` — runs against it unchanged. The only differences from production are the `fetch` and `issuer` you pass in.
11
11
 
@@ -44,7 +44,7 @@ Options: `new FakeCloud({clientId, issuer = 'https://directory.test', runtimeUrl
44
44
 
45
45
  The fake stands in for a Northlight guest, where the Linux root launcher always exists, so `runs.start({isolated: true})` starts a run by default and `run.params.isolated` is `true`. The checks `startRun` makes without the launcher are mirrored: `isolated` must be a boolean, `cwd` is accepted only with `isolated: true` and must be an absolute path inside the run's root folder, `/apps/<clientId>/nodes/<run id>` (else 400 `invalid_request`, `param: cwd`), and `worktree` is refused. Nothing in the fake enforces the sandbox itself (no network, no `files/` mount).
46
46
 
47
- `isolatedRuns: 'unavailable'` models a runtime without the launcher, such as a local daemon on a Mac: every isolated start answers 503 `isolated_unavailable` (`param: isolated`, retryable, so `runs.start` sends it three times before throwing). Use it to test your app's handling of that refusal.
47
+ `isolatedRuns: 'unavailable'` models a runtime without the launcher, such as a runtime on a machine that cannot launch isolated runs: every isolated start answers 503 `isolated_unavailable` (`param: isolated`, retryable, so `runs.start` sends it three times before throwing). Use it to test your app's handling of that refusal.
48
48
 
49
49
  ## Driving runs
50
50
 
@@ -190,4 +190,4 @@ Build two app instances (two `OAuth2Client`s) on the same `cloud`. They see the
190
190
 
191
191
  FakeCloud is checked against the real runtime on every crouter release: one set of conformance scenarios runs on the fake and on the real app listener (run start and idempotency, messages, reply streams, long-poll, every settle outcome, delete, the event stream's edges, grant holds, memory, providers, run notices). The keyed-write scenarios K1–K8 (equal-key replay, conflict, concurrent equal keys accepted once, the 24h window, replay after cancel, a key bound to its operation, keys scoped to the grantee, concurrent notes) are exported as `@north-light/sdk/testing/conformance` (`keyedWriteScenarios`, `IDEMPOTENCY_WINDOW_MS`) and run on FakeCloud and on the real daemon; an app test double for the runtime should run them against its own target. Two behaviours are fake-only because the runtime cannot be scripted that way: a successful provider call (the real side needs an installed provider), and `setActivity`. An isolated run that starts is checked only against `startRun`'s documented checks: the real listener in the suite runs without the Linux root launcher, so on it the `isolatedRuns: 'unavailable'` refusal is what is conformance-checked.
192
192
 
193
- Not faked: sign-in (`authorizeUrl`, `exchangeCode`, ID tokens — start from `cloud.connect`), token revocation, the owner and local-daemon surface (`nodes`, `canvas`, `crons`, `files`, …), and several apps on one cloud. `trace.get`, `run.rename`, `run.interrupt` and `profile.list` answer the right shape only.
193
+ Not faked: sign-in (`authorizeUrl`, `exchangeCode`, ID tokens — start from `cloud.connect`), token revocation, the owner surface (`nodes`, `canvas`, `crons`, `files`, …), and several apps on one cloud. `trace.get`, `run.rename`, `run.interrupt` and `profile.list` answer the right shape only.
@@ -0,0 +1,99 @@
1
+ ---
2
+ kind: knowledge
3
+ when-and-why-to-read: When you need Typed results, this knowledge should be read
4
+ because Start a run with a schema and get back a value that was checked
5
+ against it.
6
+ ---
7
+
8
+ # Typed results
9
+
10
+ Pass an `output_schema` and call `runs.parse`. The runtime arms the schema on the run's root agent, which must submit a value that validates against it. The run settles with that value, and `runs.parse` returns it as `output_parsed`, typed from your schema.
11
+
12
+ ```ts
13
+ import {z} from 'zod';
14
+ import type {ConnectedCrouter} from '@north-light/sdk';
15
+
16
+ const Profile = z.object({
17
+ display_name: z.string(),
18
+ bio: z.string(),
19
+ facts: z.array(z.string()),
20
+ });
21
+
22
+ /** Start a run on the person's runtime and get a value back that was checked against the schema. */
23
+ export async function draftProfile(runtime: ConnectedCrouter) {
24
+ const outcome = await runtime.runs.parse({
25
+ prompt: 'Draft a public profile for me from my notes.',
26
+ scopes: ['crtr:llm'], // submitting a result needs no other scope
27
+ output_schema: Profile,
28
+ });
29
+
30
+ if (outcome.kind === 'result') return outcome.output_parsed; // {display_name, bio, facts}, typed from Profile
31
+ if (outcome.reason === 'declined') {
32
+ // The agent could not honestly satisfy the schema; outcome.details says why.
33
+ throw new Error(`Declined: ${outcome.details?.reason ?? 'no reason given'}`);
34
+ }
35
+ throw new Error(`The run ended without a result: ${outcome.reason}`); // canceled, deadline_exceeded or runtime_error
36
+ }
37
+ ```
38
+
39
+ The runtime validates the value before it records it. A submission that does not match is refused with its field errors and never appears in `runs.get`, an event or a report, so the agent fixes it and resubmits.
40
+
41
+ - `output_schema` accepts a plain JSON Schema object or anything with `toJSONSchema()`, such as a Zod v4 object. The SDK sends it as JSON and validates nothing itself.
42
+ - A schema that is not an object, or is over 256 KB serialized, is refused with `invalid_request` and `param: 'output_schema'`, and no run is created. A submitted result can be at most 1 MiB.
43
+ - The value is validated exactly as submitted, with no coercion: `"5"` is not turned into `5`.
44
+ - A `$ref` can point only into the schema itself (`#/$defs/x`, `#anchor`) or at another schema document bundled under `$defs` with its own `$id`. Files are never fetched. A `$ref` that resolves nowhere, or a schema that cannot be compiled (a bad `pattern`), is refused with `invalid_request` and `param: 'output_schema'`.
45
+ - The agent submits with its `submit_result` tool, which needs no scope, so a run that only reasons and answers can start with `scopes: ['crtr:llm']`.
46
+ - The same value is in `runs.get(runId).result`, which `runs.wait` returns unchanged.
47
+
48
+ Do not parse assistant text out of `runs.trace` to get data back. `runs.trace` is for showing a person the transcript.
49
+
50
+ ## A run that declines
51
+
52
+ An agent that cannot honestly satisfy the schema declines. A decline, a cancel, a deadline and a runtime error all come back as an outcome. They do not throw. Narrow on `outcome.kind` and `outcome.reason`, as the example does.
53
+
54
+ ## Stopping without a result: `run_idle`
55
+
56
+ `runs.parse` rejects with an `APIError` with code `run_idle` when the agent stopped without submitting. The runtime reminds the agent of the schema up to three times in a row, then leaves the run `idle` with the schema still armed. The run is untouched: send `runs.message` to nudge the agent (this resets the reminders), or end it with `runs.cancel`.
57
+
58
+ A question from the run rejects with `waiting_on_user` unless you pass `onQuestion`. With `onQuestion`, `parse` answers each open question once and keeps waiting.
59
+
60
+ ## Bounding a run
61
+
62
+ No run is bounded in time by default. Pass a `signal` to `runs.parse` or `runs.wait`. When it aborts, the helper rejects with the signal's reason and leaves the run alone. Call `runs.cancel` if you want the run ended:
63
+
64
+ ```ts
65
+ const controller = new AbortController();
66
+ const timer = setTimeout(() => controller.abort(new Error('took too long')), 10 * 60_000);
67
+ let runId: string | undefined;
68
+ try {
69
+ const started = await runtime.runs.start({prompt, output_schema: Profile});
70
+ runId = started.run_id;
71
+ const run = await runtime.runs.wait(runId, {signal: controller.signal});
72
+ // read run.status, run.outcome, run.result
73
+ } catch (error) {
74
+ if (controller.signal.aborted && runId) await runtime.runs.cancel(runId);
75
+ throw error;
76
+ } finally {
77
+ clearTimeout(timer);
78
+ }
79
+ ```
80
+
81
+ ## Showing progress
82
+
83
+ For a run you poll, `runs.get(runId).activity` is `null` unless `status` is `running`, and otherwise says what the root agent is doing:
84
+
85
+ | `phase` | The root agent is |
86
+ |---|---|
87
+ | `starting` | launching; its first turn has not begun |
88
+ | `thinking` | reasoning, or waiting on the model before any output |
89
+ | `tool` | calling a tool: `tool.name`, and `tool.summary` (`null` while the call is still being written) |
90
+ | `submitting_result` | writing or recording its `output_schema` result |
91
+ | `writing` | streaming its answer text |
92
+ | `between_turns` | between turns while the run still works |
93
+
94
+ ```ts
95
+ const run = await runtime.runs.get(runId);
96
+ const badge = run.activity?.phase === 'tool' ? `Running ${run.activity.tool.name}` : run.activity?.phase ?? run.status;
97
+ ```
98
+
99
+ `activity` covers the root agent only, and it is read each time you call `runs.get`, so a phase shorter than your poll interval can be missed. To show text as it streams, follow the events instead: see [[northlight-apps/guides/stream-a-run]]. To be told when a background run ends, see [[northlight-apps/guides/background-runs]].