akanjs 3.2.0-rc.7 → 3.2.0-rc.9

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 (97) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/common/failureCode.ts +18 -0
  3. package/common/index.ts +3 -0
  4. package/common/mcpFailure.ts +9 -0
  5. package/common/restartSchedule.ts +55 -0
  6. package/fetch/client/httpClient.ts +12 -2
  7. package/package.json +1 -1
  8. package/server/akanApp.ts +21 -21
  9. package/server/mcp/McpDispatcher.ts +20 -5
  10. package/server/mcp/McpPages.ts +21 -6
  11. package/server/mcp/McpRouter.ts +51 -22
  12. package/server/rscClient.tsx +62 -76
  13. package/server/rscClientChunks.ts +29 -0
  14. package/server/rscClientFetch.ts +6 -1
  15. package/server/rscInlineStream.ts +34 -0
  16. package/server/rscNavigationState.ts +21 -1
  17. package/server/rscPrefetchCache.ts +27 -17
  18. package/server/rscWorkerHost.ts +9 -13
  19. package/service/documentStoreError.ts +16 -0
  20. package/service/index.ts +3 -0
  21. package/service/injectError.ts +5 -0
  22. package/service/injectInfo.ts +28 -17
  23. package/service/insightQueryError.ts +19 -0
  24. package/service/liveSyncHub.ts +5 -2
  25. package/service/predefinedAdaptor/anthropicLlm.ts +2 -0
  26. package/service/predefinedAdaptor/cache.adaptor.ts +3 -2
  27. package/service/predefinedAdaptor/compress.adaptor.ts +5 -1
  28. package/service/predefinedAdaptor/database.adaptor.ts +3 -1
  29. package/service/predefinedAdaptor/documentTransfer.ts +2 -1
  30. package/service/predefinedAdaptor/insightQuery.ts +35 -11
  31. package/service/predefinedAdaptor/llm.adaptor.ts +2 -0
  32. package/service/predefinedAdaptor/openaiDialect.ts +2 -0
  33. package/service/predefinedAdaptor/searchIndex.ts +5 -1
  34. package/service/predefinedAdaptor/sql/PostgresInsightSession.ts +15 -5
  35. package/service/predefinedAdaptor/sql/QueryCompiler.ts +29 -13
  36. package/service/predefinedAdaptor/sql/RawDocumentTable.ts +20 -8
  37. package/service/predefinedAdaptor/sql/SqlDocumentStore.ts +45 -94
  38. package/service/predefinedAdaptor/sql/SqliteInsightSession.ts +2 -1
  39. package/service/predefinedAdaptor/sql/UpdateCompiler.ts +6 -2
  40. package/service/predefinedAdaptor/sql/fieldValues.ts +74 -0
  41. package/service/predefinedAdaptor/sql/search/fts5.ts +4 -1
  42. package/service/predefinedAdaptor/sql/search/postgres.ts +6 -2
  43. package/service/predefinedAdaptor/sql/values.ts +8 -4
  44. package/service/predefinedAdaptor/storage.adaptor.ts +7 -3
  45. package/service/serve.ts +3 -2
  46. package/service/serviceModule.ts +2 -2
  47. package/signal/SignalFailure.ts +8 -1
  48. package/signal/endpointErrorContract.ts +9 -2
  49. package/signal/endpointInfo.ts +6 -5
  50. package/signal/exception.ts +1 -0
  51. package/signal/index.ts +2 -0
  52. package/signal/internalInfo.ts +6 -4
  53. package/signal/mcp/Msg.ts +23 -10
  54. package/signal/mcp/index.ts +1 -0
  55. package/signal/mcp/promptError.ts +9 -0
  56. package/signal/middleware.ts +5 -5
  57. package/signal/serializer/fetch.serializer.ts +2 -1
  58. package/signal/signalContext.ts +15 -16
  59. package/signal/signalContractError.ts +10 -0
  60. package/signal/signalDeclarationError.ts +13 -0
  61. package/signal/signalRegistry.ts +3 -1
  62. package/signal/slice.ts +2 -1
  63. package/signal/sliceInfo.ts +12 -9
  64. package/types/common/failureCode.d.ts +6 -0
  65. package/types/common/index.d.ts +3 -0
  66. package/types/common/mcpFailure.d.ts +6 -0
  67. package/types/common/restartSchedule.d.ts +16 -0
  68. package/types/server/logging/rotatingLogWriter.d.ts +1 -1
  69. package/types/server/mcp/McpPages.d.ts +2 -1
  70. package/types/server/rscClient.d.ts +0 -5
  71. package/types/server/rscClientChunks.d.ts +6 -0
  72. package/types/server/rscClientFetch.d.ts +1 -1
  73. package/types/server/rscInlineStream.d.ts +9 -0
  74. package/types/server/rscNavigationState.d.ts +8 -3
  75. package/types/server/rscPrefetchCache.d.ts +7 -6
  76. package/types/service/documentStoreError.d.ts +7 -0
  77. package/types/service/index.d.ts +3 -0
  78. package/types/service/injectError.d.ts +4 -0
  79. package/types/service/insightQueryError.d.ts +9 -0
  80. package/types/service/predefinedAdaptor/llm.adaptor.d.ts +2 -0
  81. package/types/service/predefinedAdaptor/sql/SqlDocumentStore.d.ts +0 -5
  82. package/types/service/predefinedAdaptor/sql/fieldValues.d.ts +5 -0
  83. package/types/service/serviceModule.d.ts +1 -1
  84. package/types/signal/SignalFailure.d.ts +1 -0
  85. package/types/signal/exception.d.ts +1 -0
  86. package/types/signal/index.d.ts +2 -0
  87. package/types/signal/mcp/index.d.ts +1 -0
  88. package/types/signal/mcp/promptError.d.ts +5 -0
  89. package/types/signal/signalContractError.d.ts +4 -0
  90. package/types/signal/signalDeclarationError.d.ts +4 -0
  91. package/types/vendor/use-agentic/types.d.ts +5 -0
  92. package/vendor/use-agentic/CHANGELOG.md +24 -0
  93. package/vendor/use-agentic/ToolRunner.ts +18 -3
  94. package/vendor/use-agentic/WIRE.md +5 -0
  95. package/vendor/use-agentic/types.ts +5 -0
  96. package/webkit/McpAppAgent.ts +8 -3
  97. package/webkit/McpAppFetchBridge.ts +9 -5
package/CHANGELOG.md CHANGED
@@ -25,10 +25,71 @@
25
25
  - **Cache writes reported separately.** `LlmUsage.cacheWriteTokens` is the part of `inputTokens` the provider wrote to its cache, which Anthropic bills above its input rate. `inputTokens` still counts the whole prompt.
26
26
  - **`AgentService.runTurn(request, { onDelta, preamble, signal })`.** `preamble` replaces the in-page preamble, and `false` sends none, for a turn with no screen behind it. Passing `onDelta` alone as the second argument still works.
27
27
 
28
+ - dcb7e61: The signal and service facets throw coded failures instead of a bare `Error`. Each one keeps its message, so a test or a log matching the text still matches. Each one carries a `code` that a caller, an agent or an MCP client can branch on, for example `DocumentStoreError.is(error, "invalidQuery")`.
29
+
30
+ | Class | Codes | Status |
31
+ | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------- |
32
+ | `SignalDeclarationError` (`akanjs/signal`) | `handlerAlreadySet`, `nullableLastArg`, `liveAlreadySet`, `invalidArgType`, `invalidErrors`, `baseMismatch`, `missingModel`, `missingSlice` | 500 |
33
+ | `SignalContractError` (`akanjs/signal`) | `undefinedReturn`, `bytesThroughAny`, `wrongTransport`, `notRegistered`, `noHandler` | 500 |
34
+ | `PromptError` (`akanjs/signal`) | `invalidPrompt`, `unmaskedResource` | 500 |
35
+ | | `inlineFailed` | 502 |
36
+ | `InjectError` (`akanjs/service`) | `notRegistered`, `notInitialized`, `invalidInject` | 500 |
37
+ | `DocumentStoreError` (`akanjs/service`) | `invalidQuery`, `invalidSchema`, `invalidDocument`, `tableMissing`, `searchUnavailable`, `searchMisconfigured` | 500 |
38
+ | | `unstorableValue` | 400 |
39
+ | `InsightQueryError` (`akanjs/service`) | `invalidInsightQuery` | 400, forwarded |
40
+ | | `insightTimeout` | 504, forwarded |
41
+ | | `insightUnavailable` | 500 |
42
+ | `AkanError` | `invalidStorageKey` | 400 |
43
+ | | `storageNotShared`, `liveRoomTaken`, `unroutableLiveQuery`, `missingFilterQuery`, `compressorNotInitialized`, `redisUriMissing`, `transferUnsupported` | 500 |
44
+
45
+ The request path answers every one of these except the forwarded ones as `SignalFailure` already does for an `AkanError`. The response carries the status, the status's reason and the code. The message is left out in a production build, since it can name a table, a field, a role or a signed URL. A state that configuration must fix answers 500, and so does a broken declaration. Examples are text search switched off, no insight connection, and local files in a multi-instance deployment.
46
+
47
+ A refused insight statement is forwarded to its author as a fixed sentence or with the author's own keyword or column. When Postgres refuses the role (42501), the sentence carries none of the driver's text. That text stays on the error's `cause`, and the `Logging` middleware's line prints it. A statement Postgres cancels on its `statement_timeout` (57014) answers `insightTimeout`, like the timeout `InsightQuery` races.
48
+
49
+ **Upgrade.** Most of these used to answer `500 Internal Server Error` with no code. Check any caller that branches on the status:
50
+
51
+ - **400**: a string holding U+0000 that the store refuses to save, and a storage key outside the storage root.
52
+ - **502**: a prompt that fails to inline a file.
53
+ - **`InsightQuery`**: a refused statement now reaches its author as a 400 with its message, and a timeout as a 504.
54
+ - **No retry**: `HttpClient` does not retry these 502s and 504s. A body carrying a code is the server's own answer, not a gateway's.
55
+ - **Logging**: `SignalContext` writes its crash entry, with the stack, only from 500 up. So a 400 above gets the `Logging` middleware's one error line, and that line now names the error's `cause`.
56
+
57
+ **A 429 that is not forwarded** is now treated like the rate limit's own:
58
+
59
+ - `SignalFailure` sends its `Retry-After` from `data.seconds`, a finite number only. The new `SignalFailure.headersOf(error, statusCode)` builds the headers for both paths.
60
+ - The `Logging` middleware keeps it at debug level.
61
+ - `HttpClient` restores it under `base.error.tooManyRequests`, with the code it carried and the wait its `Retry-After` names. So it is retried and worded as a forwarded one is. One with no `Retry-After` to read, because none was sent or a cross-origin caller is not exposed to it, stays the refusal it was and is not retried.
62
+
63
+ **`Exception.<Status>.is(error)` type-checks.** `StatusException` now declares `is`, so `Exception.BadRequest.is(error)` narrows `error` to an `Exception` and checks its own class.
64
+
28
65
  - 465ccb9: The `Err` that `makePageProto` returns has a named type, `PageErrConstructor`, exported from `akanjs/client` with `PageErrInstance` and `ErrPayload`, so the declaration every app's `useClient` emits no longer spells out the class shape for `Err` and each of its status classes. `akanjs/client`'s declaration of `makePageProto` drops from about 24,000 lines to about 30.
29
66
 
30
67
  `new Err(...)`, `Err.is`, `Err.fromJSON` and `instanceof Err` type as before, on `Err` and on each status class (`new Err.NotFound(...)`, `Err.NotFound.is(...)`). The statics `Err` inherited from `Error` — `captureStackTrace`, `prepareStackTrace`, `stackTraceLimit` and `isError` — are no longer on its type; call them on `Error`.
31
68
 
69
+ - 3b7247e: A failed tool call now names a code a client or a model can branch on, beside the text it already sent, which is unchanged. No upgrade step is needed: `AgentWireToolResult` and `use-agentic`'s `ToolCallResult` only gain an optional `code`, and `akanjs/common` adds `MCP_FAILURE_META`, `McpFailure` and `FailureCode`.
70
+
71
+ Every code is a bounded token, a dictionary key (`<module>.error.<key>`) or one camelCase identifier, never prose, so no text can pass for one.
72
+
73
+ - **An app's `/mcp`:**
74
+ - A tool error carries `_meta["akanjs/failure"]: { code, statusCode }`, beside the server's own `_meta` for a 2026-07-28 client. The code is the one an HTTP caller gets:
75
+ - a domain `Err` by its dictionary key, such as `base.error.documentNotFound`;
76
+ - an `AkanError` by its code, such as `invalidArgument` for an argument the call got wrong;
77
+ - a 401 or 403 by its status alone (`unauthorized`, `forbidden`);
78
+ - a 5xx by a dictionary key or this server's own `AkanError` code, else by its status (`internalError`, `serviceUnavailable`), never by a code a duck-typed error put in its body.
79
+ - A JSON-RPC error carries `data.code`, which tells apart what `-32602` covers:
80
+ - `unknownTool`, `unknownPrompt` (an unlisted page prompt included) and `unknownResource`;
81
+ - `invalidArgument` for bad arguments or a missing tool name, prompt name or resource uri;
82
+ - a refused screen's `forbidden` or `notFound`.
83
+ A rate-limited call names `tooManyRequests` and the catch-all names `internalError`.
84
+ - An MCP Apps view's call that fails without a domain `Err` restores as an error with that status and code, where it used to be a plain `Error`. A tool the view itself serves to the host names its code in the same `_meta` entry, without a `statusCode`.
85
+ - **`akan mcp`:** a tool error carries the same `_meta["akanjs/failure"]`, with one of these codes:
86
+ - `unknownTool` for a name no mode lists;
87
+ - `toolUnavailable` for a tool outside the server's mode;
88
+ - `invalidArgument` for a missing argument, an unknown guideline name, or a workflow path outside `.akan/workflows/`;
89
+ - `toolFailed` for anything else, with `statusCode` 500. A coded `AkanError` keeps its own code.
90
+ - **The code agent:** an MCP server's tool result keeps the code it named, from `_meta["akanjs/failure"]` or a JSON-RPC error's `data.code`, in the call's `details`.
91
+ - **The in-page agent:** a `toolResults` entry whose tool threw carries `code` beside `error` (see `use-agentic`'s WIRE.md): a dictionary `Err`'s key, else the thrown error's own `code`. A `taint: "source"` tool's result carries none, since its code would travel outside the page-content fence. The bundled Anthropic and OpenAI adaptors send `code` to the model inside the tool result, beside `error`.
92
+
32
93
  ### Patch Changes
33
94
 
34
95
  - bc792ab: What a coding agent needs to build its first app is now written where it looks, and two messages say what to do next.
@@ -190,6 +251,15 @@
190
251
  - It sits behind the same gate as the other `/_akan` devtools routes, and `akan tunnel` / `akan start --share` refuse it.
191
252
 
192
253
  - 96f9ff6: A `Binary` argument reaches `exec` typed as `Uint8Array<ArrayBuffer>`, so it can go straight to a service or a `fetch` body. Before, it was a copy of `Uint8Array` with every method stripped. A `Binary` return still takes any `Uint8Array`.
254
+ - af7c411: The five child-process restart loops now share one restart schedule, `RestartSchedule` from `akanjs/common`: the gateway's replicas, the RSC worker, the incremental builder, and `akan start`'s backend and builder recovery. It counts failed restarts, waits before the next one and cancels a pending one on stop. Each loop keeps its own delays (200ms–30s for the RSC worker, 2s–60s for `akan start`'s builder recovery, 1s–30s for the rest), its own give-up rule and its own log lines.
255
+
256
+ Two stop races in those loops are fixed:
257
+
258
+ - A replica whose restart timer had fired no longer respawns after the gateway stops.
259
+ - A builder `akan start` was still creating or booting when it stopped is now stopped too, instead of being started or retried after its ready timeout.
260
+
261
+ In `@akanjs/devkit`, `shouldAbandonBackendRecovery` is replaced by `backendRecoveryPolicy`, which gives up after five failed backend restarts as before.
262
+
193
263
  - 1ebc57a: The `Err` an app imports in client code now has `Err.is(error, ...keys)`, as the `Err` from the app's dictionary (the one services throw) already did. It was missing on the client one, so client code that checked a caught error with it failed to typecheck, or threw a `TypeError` when typed loosely. `Err.is` is true for an `Err`, or for any error carrying a string `error` key, so one restored from a failed `fetch` call passes too; naming keys accepts only those and narrows the error's type to them. Both `Err` classes now run the same check.
194
264
  - c3b5b3c: The framework no longer puts `@akanjs/native/core` on a web page. `isNativeApp()` and the other host checks read the platform the shell writes before the bundle runs, and a native shell still starts core with the page. A file that imports `akanjs/client/native` statically still brings core to every page that reaches it. On the minimal app this takes 15 KB raw (5.6 KB brotli) off the vendor floor and 20 KB raw (6.6 KB brotli) off every route entry. `akan build` also resolves the `production` export condition for the browser, SSR-client, CSR and MCP App view bundles, so a package such as Lexical ships its production build alone. On the minimal app the Agent editor chunk drops from 91 KB to 63 KB brotli. `akan start` is unchanged.
195
265
  - 6d5b544: A database service now has `create<Model>Many(rows)`. It creates the rows on the same path as `create<Model>`: `_preCreate` and `_postCreate`, the document's save and create hooks, and the live and pubsub events each row's commit fires. Every row's `_preCreate` and document pre hooks run first, so a check there that queries the table does not see the batch's own rows. The rows are then written in one transaction, joining the caller's when one is open, with one multi-row INSERT per 500 rows instead of one statement per row; if the database refuses one row, none is written. Every row's `_postCreate` runs once the transaction commits, as `create<Model>`'s runs once its row is stored, so a `_postCreate` that throws leaves the rows written. A service that already declares a method of that name, itself or in a lib service it extends, keeps its own at runtime, but its signature no longer typechecks against the generated one: rename it.
@@ -230,6 +300,19 @@
230
300
  - e143263: The optional `happy-dom` and `@happy-dom/global-registrator` peers now ask for `^21.0.4`. Versions 17.0.0 through 21.0.3 compile a `<script type="module">` import alias into code unchecked, so a page loaded into a happy-dom window could run code on the host (GHSA-834v-8h66-3h79). UI tests register one through `akanjs/test/registerDom`; run `bun update happy-dom @happy-dom/global-registrator` in a workspace that pins an older one.
231
301
  - e4f7876: A hidden field declared `.optional()` (`field.hidden(String).optional()`) is optional again in a service's `create<Model>` and `create<Model>Many` input, and in the document type `by()` makes of an input model or a scalar. It was typed there as a required, non-null value, though the model's own document already typed it optional, so a create that left it out needed a cast. A hidden field without `.optional()` stays required. Code that read such a field off a scalar's document as always present now handles its absence, as it already did on the model's document.
232
302
  - cb0fd5b: Reading the client address from a forwarded header no longer stalls the server on a crafted hop. `IpLiteral.parse` matched a bracketed IPv6 hop with a pattern that backtracked quadratically, so an `X-Forwarded-For` or `X-Real-IP` entry of `[` and a long run of colons kept the event loop busy for about 100 ms per 16 KB of header, on every request that carried it. The bracket is now matched in linear time and the colon checked apart; every address parses as before.
303
+ - 256b6e3: A lazily loaded chunk that fails to link during a rolling deploy now reloads its page as a document.
304
+
305
+ - **Before:** the chunk fallback covered only the chunks the Flight client loads. A chunk loaded through `import()` (`lazy` from `akanjs/webkit`, `React.lazy`, or a dynamic import in a client component) on a page from another build could fail to link against the document's import map. With no error boundary above it, the page went blank; with one, it showed that boundary's fallback. Nothing loaded the page again.
306
+ - **Now:** when a module link or resolve error reaches the React root (caught by an error boundary or not) or rejects an `import()` that nothing catches, the tab reloads the address it shows. It does so only when all of these hold:
307
+ - the page on screen was rendered from a client navigation's or refresh's response, not by the document itself;
308
+ - no navigation to another page is under way;
309
+ - the browser is online;
310
+ - no other document load is under way;
311
+ - the error is not one the Flight client's chunk loader already handled.
312
+ - **At most one reload per error per tab,** whichever page it shows up on, in the same per-tab list the chunk fallback uses.
313
+ - **An `import()` of your own that always fails to link** (a bare specifier missing from the import map, or a CDN module that lacks a name it is asked for) therefore costs one reload per distinct error per tab, the first time it happens on a page a client navigation rendered. After that it shows as it did before.
314
+ - This applies to `akan build` output only. There, React's own reporting is kept: a caught error is still logged, and an uncaught one is still reported, through a window `error` event where the browser has no `reportError`. `akan start` passes nothing new to the root.
315
+
233
316
  - c48d780: The `shared` and `util` libraries that `akan install-library` copies are refreshed. Apps that use them should check these changes:
234
317
 
235
318
  - Sign-up and sign-in steps run in a new `_sign` service. `generatePrepareUserWithAccountId`, `startPhoneSign` and `signinWithPhoneCode` are now one endpoint each, replacing store actions that chained several calls. `activateUserWithAgreePolicies` writes the agreed policies together with the activation. `leaveSelf` and `leaveAndSignoutSelf` take the leave survey with the deletion.
@@ -373,6 +456,14 @@
373
456
  - **`@akanjs/devkit`: the SSR runtime manifest keeps every client export of the segment outlet module.** Before, it kept only one.
374
457
 
375
458
  - 3537448: A navigation that a newer one overtakes before its page commits now cuts its `/__rsc` request once the response headers are in, so the server stops streaming it and the browser stops reading it. Before, it ran to the end and was only kept from committing. The cut waits for the headers because a session refresh may answer with a rotated single-use refresh token in `Set-Cookie`, and a request aborted before it lands leaves the browser holding the spent token. A refresh, a shallow push and a move back or forward overtake it the same way. A page that has already committed is never cut, so the Suspense content it still streams keeps arriving while the next navigation loads.
459
+ - a373d51: With partial RSC commit on (`AKAN_PUBLIC_RSC_PARTIAL_COMMIT=1`), a page reached by a patch is now replayed from the browser's cache on a revisit, even after a full navigation in between. Before, every full navigation dropped every cached patch, so a section change made every page of the section before it a network fetch again.
460
+
461
+ - **A cached patch remembers the full render it went under.** It is replayed only while that same render is on screen, which is the case when a navigation brings that page back from the full-page cache, a not-found view in between included.
462
+ - **It is never laid under other layouts.** A patch is refetched, never replayed, under another route group's layouts or another locale's at the same URL prefix. The same goes for a new render of the page it went under, once that page has left the full-page cache.
463
+ - **The cache stays bounded at 32 entries.** A patch whose full render can no longer come back is dropped. `clearRscNavigationCache()`, `refreshRsc()`, an HMR refresh and an account change still drop every cached patch.
464
+ - **The default is unchanged.** Partial commit is still off unless the flag is set.
465
+
466
+ - c723e7a: With `AKAN_PUBLIC_RSC_PARTIAL_COMMIT=1`, a Link prefetch now carries the router state, so a prefetched sibling page comes back as a patch. A prefetched patch is used only under the full commit it was requested from, and a link the patch cache would replay is no longer prefetched.
376
467
  - 6c3a303: A page that renders a string of 1024 characters or more, such as a post body or a long comment, now renders and hydrates whatever its lines say. React sends such a string, and every typed array or `ArrayBuffer`, as a length-prefixed Flight row whose raw bytes may hold newlines. The SSR sanitizer, the client navigation redirect guard and the partial-navigation patch check all split the stream on every newline, so they read lines inside the text as rows of their own. A line shaped like a debug row was dropped and a line shaped like a redirect row was rewritten, which broke the render. On a client navigation the guard could act on such a line as a redirect, and a partial navigation fell back to a full one.
377
468
 
378
469
  All three now share one Flight row reader that follows React's row headers. It skips a length-prefixed row by its byte length across any chunk boundary, and it checks only real rows, which keep their sanitizing and redirect handling. Long text is no longer split and pattern-tested line by line. The server-rendered HTML also carries one inline script per Flight row instead of one per line, about 9% less inline-script HTML on a 400 KB payload.
@@ -0,0 +1,18 @@
1
+
2
+
3
+ export class FailureCode {
4
+ static readonly #key = /^[A-Za-z][\w$-]{0,63}\.error\.[\w$.-]{1,120}$/;
5
+ static readonly #token = /^[a-z][A-Za-z0-9]{0,63}$/;
6
+
7
+ static isKey(value: unknown): value is string {
8
+ return typeof value === "string" && FailureCode.#key.test(value);
9
+ }
10
+
11
+ static isToken(value: unknown): value is string {
12
+ return typeof value === "string" && FailureCode.#token.test(value);
13
+ }
14
+
15
+ static is(value: unknown): value is string {
16
+ return FailureCode.isKey(value) || FailureCode.isToken(value);
17
+ }
18
+ }
package/common/index.ts CHANGED
@@ -97,6 +97,7 @@ export {
97
97
  } from "./codeAgentWire";
98
98
  export { type CookieEntry, CookieJar, type CookieRead } from "./cookieJar";
99
99
  export { EventStream, type EventStreamOptions } from "./eventStream";
100
+ export { FailureCode } from "./failureCode";
100
101
  export {
101
102
  type FileUploadCapability,
102
103
  fileUploadContract,
@@ -168,6 +169,7 @@ export {
168
169
  mcpHintsOf,
169
170
  mcpRefusalOf,
170
171
  } from "./mcpExposure";
172
+ export { MCP_FAILURE_META, type McpFailure } from "./mcpFailure";
171
173
  export { deepObjectify, objectify, plainFieldsOf } from "./objectify";
172
174
  export { pathGet, pathGetLoose, pathSet, toPathSegments } from "./objectPath";
173
175
  export { PipelineNames } from "./PipelineNames";
@@ -213,6 +215,7 @@ export { randomPick, randomPicks } from "./randomPick";
213
215
  export { RemoteAuthCode } from "./remoteAuthCode";
214
216
  export { RequestLocale, type RequestLocaleInput } from "./requestLocale";
215
217
  export { hostFromRequest, isJsonContentType, originFromRequest } from "./requestOrigin";
218
+ export { type RestartPolicy, RestartSchedule } from "./restartSchedule";
216
219
  export { RestClient, type RestClientOptions, type RestRequestOptions } from "./restClient";
217
220
  export { round } from "./round";
218
221
  export {
@@ -0,0 +1,9 @@
1
+
2
+
3
+ export const MCP_FAILURE_META = "akanjs/failure";
4
+
5
+ export interface McpFailure {
6
+ code: string;
7
+ /** The status HTTP would answer with; absent for a tool the page itself served. */
8
+ statusCode?: number;
9
+ }
@@ -0,0 +1,55 @@
1
+ import { Backoff, type BackoffPolicy } from "./backoff";
2
+
3
+ export interface RestartPolicy extends BackoffPolicy {
4
+ maxAttempts?: number;
5
+ }
6
+
7
+ export class RestartSchedule {
8
+ readonly #policy: RestartPolicy;
9
+ #attempts = 0;
10
+ #timer: ReturnType<typeof setTimeout> | null = null;
11
+
12
+ constructor({ jitter = 0, ...policy }: RestartPolicy = {}) {
13
+ this.#policy = { ...policy, jitter };
14
+ }
15
+
16
+ get attempts() {
17
+ return this.#attempts;
18
+ }
19
+
20
+ get pending() {
21
+ return this.#timer !== null;
22
+ }
23
+
24
+ get exhausted() {
25
+ return this.#policy.maxAttempts !== undefined && this.#attempts >= this.#policy.maxAttempts;
26
+ }
27
+
28
+ next() {
29
+ this.#attempts += 1;
30
+ return Backoff.delay(this.#attempts, this.#policy);
31
+ }
32
+
33
+ arm(delay: number, run: () => void) {
34
+ this.cancel();
35
+ this.#timer = setTimeout(() => {
36
+ this.#timer = null;
37
+ run();
38
+ }, delay);
39
+ }
40
+
41
+ schedule(run: () => void) {
42
+ const delay = this.next();
43
+ this.arm(delay, run);
44
+ return delay;
45
+ }
46
+
47
+ cancel() {
48
+ if (this.#timer) clearTimeout(this.#timer);
49
+ this.#timer = null;
50
+ }
51
+
52
+ reset() {
53
+ this.#attempts = 0;
54
+ }
55
+ }
@@ -208,12 +208,18 @@ export class HttpClient {
208
208
 
209
209
  if (res.status in transportErrorKeyMap && !HttpClient.#isServerAnswer(body, res.status))
210
210
  throw this.#transportError(url, res, JSON.stringify(body));
211
- throw this.#restoreError(body, res.status);
211
+ throw this.#restoreError(HttpClient.#asRateLimit(body, res), res.status);
212
212
  } finally {
213
213
  joined.dispose();
214
214
  }
215
215
  }
216
216
 
217
+ static #asRateLimit(body: unknown, res: Response) {
218
+ if (res.status !== 429 || !isRecord(body) || dictionaryErrorKey.test(String(body.error))) return body;
219
+ const seconds = HttpClient.#namedWaitOf(res);
220
+ return seconds === null ? body : { ...body, error: transportErrorKeyMap[429], data: { seconds } };
221
+ }
222
+
217
223
  static #isServerAnswer(body: unknown, status: number) {
218
224
  if (!isRecord(body) || typeof body.error !== "string") return false;
219
225
  return dictionaryErrorKey.test(body.error) || (typeof body.code === "string" && body.statusCode === status);
@@ -298,9 +304,13 @@ export class HttpClient {
298
304
  }
299
305
 
300
306
  static #retryAfterSeconds(res: Response): number {
307
+ return HttpClient.#namedWaitOf(res) ?? 60;
308
+ }
309
+
310
+ static #namedWaitOf(res: Response): number | null {
301
311
  const header = res.headers.get("retry-after")?.trim() ?? "";
302
312
  const seconds = /^\d+$/.test(header) ? Number(header) : Math.ceil((Date.parse(header) - Date.now()) / 1000);
303
- return Number.isFinite(seconds) ? Math.max(0, seconds) : 60;
313
+ return Number.isFinite(seconds) ? Math.max(0, seconds) : null;
304
314
  }
305
315
 
306
316
  #restoreError(body: unknown, fallbackStatusCode: number): RestoredError {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "akanjs",
3
- "version": "3.2.0-rc.7",
3
+ "version": "3.2.0-rc.9",
4
4
  "sourceType": "module",
5
5
  "type": "module",
6
6
  "publishConfig": {
package/server/akanApp.ts CHANGED
@@ -6,6 +6,7 @@ import path from "node:path";
6
6
  import { Logger, TrustedProxy } from "akanjs/common";
7
7
  import type { AkanChildRole, AkanChildStatus, AkanIpcMessage, AkanMetricsReport, AkanUpstream } from "akanjs/service";
8
8
  import { getApiPrefix, getWsPrefix, normalizeRoutePrefix, resetEnvCache } from "../base/baseEnv";
9
+ import { type RestartPolicy, RestartSchedule } from "../common/restartSchedule";
9
10
  import { CrossSiteGuard } from "../signal/CrossSiteGuard";
10
11
  import { isTraceEnabled } from "../signal/trace";
11
12
  import { AKAN_CHILD_HOST, makeAkanChildProxyHeaders } from "./akanAppHeaders";
@@ -46,9 +47,8 @@ interface ChildState {
46
47
  metrics: AkanMetricsReport;
47
48
  /** Monotonic (`performance.now()`) so sleep/wake wall-clock jumps cannot fake a health timeout. */
48
49
  lastPongAtMono?: number;
49
- restartAttempts: number;
50
+ restart: RestartSchedule;
50
51
  restartCount: number;
51
- restartTimer: Timer | null;
52
52
  restartPending: boolean;
53
53
  lastExitCode?: number | null;
54
54
  lastRestartAt?: number;
@@ -109,13 +109,16 @@ interface AkanReplicaConfig {
109
109
  }
110
110
 
111
111
  export class AkanApp {
112
- static readonly #childRestartBaseDelayMs = 1_000;
113
- static readonly #childRestartMaxDelayMs = 30_000;
114
112
  static readonly #childRestartGraceMs = 5_000;
115
113
  static readonly #devMaxChildBootFailures = 3;
116
114
 
117
115
  readonly logger = new Logger("AkanApp");
118
116
  readonly #devHosted = process.env.AKAN_COMMAND_TYPE === "start";
117
+ readonly #childRestartPolicy: RestartPolicy = {
118
+ min: 1_000,
119
+ max: 30_000,
120
+ ...(this.#devHosted ? { maxAttempts: AkanApp.#devMaxChildBootFailures - 1 } : {}),
121
+ };
119
122
  readonly #healthTimeoutMs = AkanApp.#parseHealthTimeoutMs();
120
123
  readonly #upstreamWaitMs = AkanApp.#parseUpstreamWaitMs();
121
124
  /** Child stderr is mostly bundler/runtime noise, kept to the log file; with none it may be a crash's only trace. */
@@ -327,8 +330,7 @@ export class AkanApp {
327
330
  this.#server?.stop(true);
328
331
  this.#server = null;
329
332
  for (const child of this.#children.values()) {
330
- if (child.restartTimer) clearTimeout(child.restartTimer);
331
- child.restartTimer = null;
333
+ child.restart.cancel();
332
334
  this.#sendToChild(child, { type: "shutdown", signal } satisfies AkanIpcMessage);
333
335
  }
334
336
  await Promise.race([
@@ -392,9 +394,9 @@ export class AkanApp {
392
394
  ready: false,
393
395
  status: "starting",
394
396
  metrics: {},
395
- restartAttempts: previous?.restartAttempts ?? 0,
397
+
398
+ restart: previous?.restart ?? new RestartSchedule(this.#childRestartPolicy),
396
399
  restartCount: previous?.restartCount ?? 0,
397
- restartTimer: null,
398
400
  restartPending: false,
399
401
  lastExitCode: previous?.lastExitCode,
400
402
  lastRestartAt: previous?.lastRestartAt,
@@ -442,11 +444,11 @@ export class AkanApp {
442
444
  #scheduleChildRestart(child: ChildState, proc: Bun.Subprocess<"ignore", "pipe", "pipe">, reason: string): void {
443
445
  if (this.#stopping) return;
444
446
  if (child.proc !== proc) return;
445
- if (child.restartPending || child.restartTimer) {
447
+ if (child.restartPending || child.restart.pending) {
446
448
  child.lastRestartReason = reason;
447
449
  return;
448
450
  }
449
- if (this.#devHosted && child.restartAttempts >= AkanApp.#devMaxChildBootFailures - 1 && !child.ready) {
451
+ if (child.restart.exhausted && !child.ready) {
450
452
  this.#markChildCrashed(child, reason);
451
453
  return;
452
454
  }
@@ -462,12 +464,10 @@ export class AkanApp {
462
464
  child.lastRestartAt = Date.now();
463
465
  this.#removeChildRooms(child.idx);
464
466
 
465
- const attempt = child.restartAttempts;
466
- const delay = Math.min(AkanApp.#childRestartBaseDelayMs * 2 ** attempt, AkanApp.#childRestartMaxDelayMs);
467
- child.restartAttempts = attempt + 1;
467
+ const delay = child.restart.next();
468
468
  child.restartCount += 1;
469
469
  this.logger.error(
470
- `Child ${child.idx}/${child.role} failed (${reason}); restarting in ${delay}ms (attempt ${child.restartAttempts})`,
470
+ `Child ${child.idx}/${child.role} failed (${reason}); restarting in ${delay}ms (attempt ${child.restart.attempts})`,
471
471
  );
472
472
 
473
473
  void this.#restartChildAfterDelay(child.idx, proc, reason, delay).catch((error) => {
@@ -493,8 +493,7 @@ export class AkanApp {
493
493
  if (this.#stopping) return;
494
494
  const current = this.#children.get(idx);
495
495
  if (!current || current.proc !== proc) return;
496
- current.restartTimer = setTimeout(() => {
497
- current.restartTimer = null;
496
+ current.restart.arm(delay, () => {
498
497
  void this.#respawnChild(idx, proc).catch((error) => {
499
498
  const latest = this.#children.get(idx);
500
499
  if (!latest || latest.proc !== proc || this.#stopping) return;
@@ -504,7 +503,7 @@ export class AkanApp {
504
503
  );
505
504
  this.#scheduleChildRestart(latest, proc, "respawn-failed");
506
505
  });
507
- }, delay);
506
+ });
508
507
  }
509
508
 
510
509
  async #respawnChild(idx: number, proc: Bun.Subprocess<"ignore", "pipe", "pipe">) {
@@ -512,6 +511,7 @@ export class AkanApp {
512
511
  const current = this.#children.get(idx);
513
512
  if (!current || current.proc !== proc) return;
514
513
  await this.#removeChildSocket(idx, current.role);
514
+ if (this.#stopping) return;
515
515
  current.restartPending = false;
516
516
  this.#spawn(idx);
517
517
  }
@@ -528,7 +528,7 @@ export class AkanApp {
528
528
  child.lastRestartReason = reason;
529
529
  this.#federationChildCache = null;
530
530
  this.#removeChildRooms(child.idx);
531
- const attempts = child.restartAttempts + 1;
531
+ const attempts = child.restart.attempts + 1;
532
532
  const detail = child.lastErrorMessage ?? reason;
533
533
  const message = `Backend replica ${child.idx}/${child.role} failed ${attempts} consecutive boots; waiting for a code change to retry: ${detail}`;
534
534
  this.logger.error(`[child-crash-loop] ${message}`);
@@ -810,7 +810,7 @@ export class AkanApp {
810
810
  ready: child.ready,
811
811
  pid: child.pid,
812
812
  upstream: child.upstream,
813
- restartAttempts: child.restartAttempts,
813
+ restartAttempts: child.restart.attempts,
814
814
  restartCount: child.restartCount,
815
815
  restartPending: child.restartPending,
816
816
  lastExitCode: child.lastExitCode,
@@ -852,7 +852,7 @@ export class AkanApp {
852
852
  role: child.role,
853
853
  metrics: child.metrics,
854
854
  rooms: this.#childRooms.get(child.idx)?.size ?? 0,
855
- restartAttempts: child.restartAttempts,
855
+ restartAttempts: child.restart.attempts,
856
856
  restartCount: child.restartCount,
857
857
  restartPending: child.restartPending,
858
858
  lastExitCode: child.lastExitCode,
@@ -1213,7 +1213,7 @@ export class AkanApp {
1213
1213
  child.healthPath = message.healthPath;
1214
1214
  if (message.crossSite) CrossSiteGuard.configure(message.crossSite);
1215
1215
  child.lastPongAtMono = performance.now();
1216
- child.restartAttempts = 0;
1216
+ child.restart.reset();
1217
1217
 
1218
1218
  if (this.#logHub && this.#logHub.floor !== null)
1219
1219
  this.#sendToChild(child, { type: "log.level", minSev: this.#logHub.floor });
@@ -6,7 +6,7 @@ import {
6
6
  type ImageResultValue,
7
7
  PrimitiveRegistry,
8
8
  } from "akanjs/base";
9
- import { interpolateTranslation, Logger } from "akanjs/common";
9
+ import { FailureCode, interpolateTranslation, Logger, MCP_FAILURE_META, type McpFailure } from "akanjs/common";
10
10
  import { agentRead, ConstantRegistry, mask } from "akanjs/constant";
11
11
  import { DictionaryLookup } from "akanjs/dictionary";
12
12
  import { NoDocumentError } from "akanjs/document";
@@ -40,6 +40,7 @@ export class McpDispatcher {
40
40
  static readonly logger = new Logger("McpDispatcher");
41
41
 
42
42
  static readonly structuredNote = "The result is in this call's structuredContent.";
43
+ static readonly #crashed: McpFailure = { code: AkanError.codeOfStatus(500), statusCode: 500 };
43
44
 
44
45
  readonly #props: McpDispatcherProps;
45
46
  #endpoints: Map<string, { endpointInfo: EndpointInfo; endpoint: Endpoint }> | null = null;
@@ -77,9 +78,12 @@ export class McpDispatcher {
77
78
  const status = McpDispatcher.#statusOf(error);
78
79
 
79
80
  if ((status === 401 || status === 403) && !req.headers.get("authorization")) throw new McpAuthRequiredError();
80
- const failure = McpDispatcher.#failure(this.#message(error, status, exposed.refName));
81
+ const failure = McpDispatcher.#failure(
82
+ this.#message(error, status, exposed.refName),
83
+ McpDispatcher.#codeOf(error, status),
84
+ );
81
85
  const restorable = forView ? McpDispatcher.#restorable(error, status) : null;
82
- return restorable ? { ...failure, _meta: { [MCP_APP_META.error]: restorable } } : failure;
86
+ return restorable ? { ...failure, _meta: { ...failure._meta, [MCP_APP_META.error]: restorable } } : failure;
83
87
  }
84
88
  }
85
89
 
@@ -184,6 +188,17 @@ export class McpDispatcher {
184
188
  return "The server failed to complete this request.";
185
189
  }
186
190
 
191
+ static #codeOf(error: unknown, status: number | undefined): McpFailure {
192
+ if (!status) return McpDispatcher.#crashed;
193
+ const byStatus = { code: AkanError.codeOfStatus(status), statusCode: status };
194
+ if (status === 401 || status === 403) return byStatus;
195
+ const wire = isExceptionLike(error) ? (error.toJSON() as { error?: unknown; code?: unknown }) : {};
196
+ if (FailureCode.isKey(wire.error)) return { code: wire.error, statusCode: status };
197
+ if (AkanError.is(error) && FailureCode.isToken(error.code)) return { code: error.code, statusCode: status };
198
+ if (status < 500 && FailureCode.isToken(wire.code)) return { code: wire.code, statusCode: status };
199
+ return byStatus;
200
+ }
201
+
187
202
  static #statusOf(error: unknown): number | undefined {
188
203
  if (isExceptionLike(error)) return error.statusCode;
189
204
  if (AkanError.is(error)) return SignalFailure.generalized(error).statusCode;
@@ -235,7 +250,7 @@ export class McpDispatcher {
235
250
  return { content, isError: false };
236
251
  }
237
252
 
238
- static #failure(message: string): McpToolResult {
239
- return { content: [{ type: "text", text: message }], isError: true };
253
+ static #failure(message: string, failure = McpDispatcher.#crashed): McpToolResult {
254
+ return { content: [{ type: "text", text: message }], isError: true, _meta: { [MCP_FAILURE_META]: failure } };
240
255
  }
241
256
  }
@@ -1,4 +1,5 @@
1
- import type { Logger } from "akanjs/common";
1
+ import { AkanError } from "akanjs/base";
2
+ import { type Logger, MCP_FAILURE_META, type McpFailure } from "akanjs/common";
2
3
  import {
3
4
  MCP_APP_META,
4
5
  MCP_META_CLIENT_CAPABILITIES,
@@ -8,7 +9,7 @@ import {
8
9
  } from "../../signal/mcp";
9
10
  import type { PromptMessage } from "../../signal/mcp/Msg";
10
11
  import type { McpPrompt } from "../../signal/mcp/mcpProtocol";
11
- import type { PagePromptEntry, PagePromptRun, PagePromptSource } from "../../signal/mcp/pagePrompt";
12
+ import type { PagePromptEntry, PagePromptRefusal, PagePromptRun, PagePromptSource } from "../../signal/mcp/pagePrompt";
12
13
  import { McpApps } from "./McpApps";
13
14
  import { McpAuthRequiredError, type McpDispatcher } from "./McpDispatcher";
14
15
  import type { McpUiSession } from "./McpUiSession";
@@ -35,7 +36,7 @@ interface McpPageCall {
35
36
 
36
37
  export type McpPageRun =
37
38
  | { badArguments: true }
38
- | { refusal: string }
39
+ | { refusal: string; failure: McpFailure }
39
40
  | { run: Extract<PagePromptRun, { ok: true }> | null; messages: PromptMessage[] };
40
41
 
41
42
  export class McpPages {
@@ -106,7 +107,14 @@ export class McpPages {
106
107
  const apps = this.#props.apps;
107
108
  const page = await this.run(call, document, entry, args);
108
109
  if ("badArguments" in page) return page;
109
- if ("refusal" in page) return { result: { content: [{ type: "text", text: page.refusal }], isError: true } };
110
+ if ("refusal" in page)
111
+ return {
112
+ result: {
113
+ content: [{ type: "text", text: page.refusal }],
114
+ isError: true,
115
+ _meta: { [MCP_FAILURE_META]: page.failure },
116
+ },
117
+ };
110
118
  if (!page.run || !apps) return { result: { content: page.messages.map((message) => message.content) } };
111
119
  const origin = this.#props.publicOrigin(call.req);
112
120
  const forView = call.ui ? { account: McpApps.accountOf(call.req) } : null;
@@ -121,7 +129,7 @@ export class McpPages {
121
129
  ): Promise<McpPageRun> {
122
130
  const source = this.#props.source;
123
131
  const { name } = entry;
124
- if (!source) return { refusal: `Unknown prompt: ${name}.` };
132
+ if (!source) return { refusal: `Unknown prompt: ${name}.`, failure: McpPages.#failureOf("unknown") };
125
133
  const strings = args ? McpPages.#pageArguments(args) : null;
126
134
  if (!strings) return { badArguments: true };
127
135
  const composer = new PagePromptComposer({
@@ -158,11 +166,18 @@ export class McpPages {
158
166
  : run.reason === "not-found"
159
167
  ? MCP_SCREEN_REFUSAL.notFound
160
168
  : MCP_SCREEN_REFUSAL.failed;
161
- return { refusal: message };
169
+ return { refusal: message, failure: McpPages.#failureOf(gated ? "forbidden" : run.reason) };
162
170
  }
163
171
  return { run, messages: await composer.compose(entry, run) };
164
172
  }
165
173
 
174
+ static #failureOf(reason: PagePromptRefusal): McpFailure {
175
+ if (reason === "argument") return { code: "invalidArgument", statusCode: 400 };
176
+ if (reason === "unknown") return { code: "unknownPrompt", statusCode: 404 };
177
+ const statusCode = reason === "forbidden" ? 403 : reason === "error" ? 500 : 404;
178
+ return { code: AkanError.codeOfStatus(statusCode), statusCode };
179
+ }
180
+
166
181
  async toolOf(name: unknown) {
167
182
  if (!this.#props.apps || typeof name !== "string" || this.#isEndpointName(name)) return undefined;
168
183
  const entry = await this.entry(name).catch(() => undefined);